Python 2.7 opening multiple files from non-default directory (for opencv)

谁说我不能喝 提交于 2019-12-12 00:57:24

问题


I'm using python 2.7 on 64 bit win7 and have opencv 2.4.x.

When I write cv2.imread('pic') it opens pic in my default python path which is C:\Users\Myname. But how I will manage to browse different directory to open images? ie D:\MyPicLib.

Meanwhile, I do not want to change default directory, because all my python modules are saved in C:\Users\Myname. I just want to manage connecting pictures in D:\MyPicLib

After this part, can you also help me to browse not one but multiple images (in specific format, like just .jpg's in a directory) in for/while loop?

Thank you in advance, the problem seems easy but despite all my effort, I did not find any solution on changing default python path.


回答1:


Is this what you are looking for? I recommend looking for some tutorials that show basic os and os.path usage. They are very useful tools. Here is the first one I found.

import os
import cv2

mypath = os.path.join('c:\\', 'asdf', 'jkl')

images = list()
for item in os.listdir(mypath):
    if '.jpg' in item:  # this could be more correctly done with os.path.splitext
        image = cv2.imread(os.path.join(mypath, item))
        if image is not None:
            images.append(image)


来源:https://stackoverflow.com/questions/22312328/python-2-7-opening-multiple-files-from-non-default-directory-for-opencv

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!