如何使用枕头库递归访问子目录中的图像文件?

时间:2019-05-20 07:14:12

标签: python-imaging-library python-3.6

我想在许多子目录中裁剪和调整多个图像的大小。如果图像位于同一目录中,则该代码有效,但无法从其他目录读取。

我尝试使用os.walk()模块。它成功地遍历了所有子目录中的文件,但是枕头的Image.open()函数无法访问图像,从而显示错误:未找到“ image ..”。

import os
from PIL import Image

for dirpath, dirnames, files in os.walk('.'):
    for filename in files:
        t = filename.split(".")
        ext = t[-1]
        if ext in ["jpg"]:
            print(filename)
            coords = (500, 250, 810,720)
            image_obj = Image.open(filename)
            cropped_image = image_obj.crop(coords)
            resized_image =cropped_image.resize([227,227])
            # name = "./data2" + str(i) +".jpg"
            resized_image.save("new" + filename)

我希望代码可以递归裁剪所有子目录中的图像并调整其大小。发生以下错误。

frame0.jpg
Traceback (most recent call last):
  File "........./data2/cropitall.py", line 18, in <module>
    image_obj = Image.open(filename) #path of image to be cropped
  File "C:\Python36\lib\site-packages\PIL\Image.py", line 2652, in open
    fp = builtins.open(filename, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'frame0.jpg'

Process finished with exit code 1

1 个答案:

答案 0 :(得分:0)

要打开图像,您需要文件的完整路径,而不仅仅是文件名。 代替

image_obj = Image.open(filename)

path = os.path.join(dirpath, filename)
image_obj = Image.open(path)