读取目录中的JPG文件?

时间:2017-02-19 19:08:55

标签: python jupyter-notebook jupyter os.path

我正在尝试浏览目录中的不同图像文件。我正在使用Jupyter来运行我的python代码。但是我一直收到这个错误。以下是我的代码和我收到的错误。

CODE:

import os
import os.path
for img in os.listdir('test_images'):
    if img.endswith("jpg"):
        scriptpath = os.path.dirname(img)
        print(os.path.join('test_images', img))
        # Read in the image
        image = os.path.join(scriptpath, img)
        image = mpimg.imread(image)
        # Grab the x and y size and make a copy of the image
        ysize = image.shape[0]
        xsize = image.shape[1]
        color_select = np.copy(image)
        # Define color selection criteria 
        red_threshold = 200
        green_threshold = 200
        blue_threshold = 200

        rgb_threshold = [red_threshold, green_threshold, blue_threshold]

        # Do a boolean or with the "|" character to identify
        # pixels below the thresholds
        thresholds = (image[:,:,0] < rgb_threshold[0]) \
                    | (image[:,:,1] < rgb_threshold[1]) \
                    | (image[:,:,2] < rgb_threshold[2])
        color_select[thresholds] = [red_threshold,green_threshold,blue_threshold]
        plt.imshow(color_select)
        # Display the image                 
        plt.imshow(color_select)
        continue
    else:
        continue

输出:

test_images/solidWhiteCurve.jpg

ERROR:

FileNotFoundError                         Traceback (most recent call last)
<ipython-input-3-6edf7c0860b7> in <module>()
      7         # Read in the image
      8         image = os.path.join(scriptpath, img)
----> 9         image = mpimg.imread(image)
     10         # Grab the x and y size and make a copy of the image
     11         ysize = image.shape[0]

/Users/steveburgos/anaconda/envs/carnd-term1/lib/python3.5/site-packages/matplotlib/image.py in imread(fname, format)
   1225 
   1226     if ext not in handlers:
-> 1227         im = pilread(fname)
   1228         if im is None:
   1229             raise ValueError('Only know how to handle extensions: %s; '

/Users/steveburgos/anaconda/envs/carnd-term1/lib/python3.5/site-packages/matplotlib/image.py in pilread(fname)
   1203         except ImportError:
   1204             return None
-> 1205         with Image.open(fname) as image:
   1206             return pil_to_array(image)
   1207 

/Users/steveburgos/anaconda/envs/carnd-term1/lib/python3.5/site-packages/PIL/Image.py in open(fp, mode)
   2310 
   2311     if filename:
-> 2312         fp = builtins.open(filename, "rb")
   2313 
   2314     try:

FileNotFoundError: [Errno 2] No such file or directory: 'solidWhiteCurve.jpg'

3 个答案:

答案 0 :(得分:2)

您的代码中存在路径不匹配,并且您的错误正在显示它(找不到文件)。当你这样做时:

for img in os.listdir('test_images'):

您在当前目录中列出了test_images目录。 img将包含file1.extfile2.ext等格式的值,因为os.listdir()仅列出其中的文件和目录的名称,因此当您致电时:

scriptpath = os.path.dirname(img)

你基本上没有任何东西,因为img不包含任何路径信息。所以,最后,当你这样做时:

image = os.path.join(scriptpath, img)

从技术上讲,您只传递文件名,因为scriptpath为空。由于您的图片位于test_images子目录中,而不在您的工作目录中,因此您通常会找不到文件。

有几种方法可以解决这个问题,最简单的方法是在变量中声明一个查找目录并在需要时使用它,例如:

target_path = "test_images"
# ...
for img in os.listdir(target_path):
# ...
    image = os.path.join(target_path, img)

答案 1 :(得分:0)

在我看来,我更喜欢使用glob库来返回目录中的文件列表。 import glob print (glob.glob("/home/peter/pictures/*.png")

返回: ['/home/peter/pictures/pic1.png', '/home/peter/pictures/pic2.png', '/home/peter/pictures/pic3.png', ...ect]

如果您想继续使用您的方法,我确信您没有提供文件夹目录的正确路径。 想一想,程序如何知道test_images的位置。

答案 2 :(得分:0)

使用glob之类的glob观点,或者您可以使用以下lambda语句

files = os.listdir(file_dir)
img_files = list(filter(lambda x: '.jpg' in x, files))