首页 > 解决方案 > 使用增量名称访问文件夹中的所有图像

问题描述

我正在尝试编写一个程序,我将在其中裁剪然后旋转文件夹中的每个图像。我目前能够为单个图像执行此操作,并且我知道我可以手动将它们全部输入。但是我想知道如何循环它,因为大约有 500 张图片,我可以在其中多次运行我的代码。另外,我在 Windows 上运行 Python3。

from PIL import Image

# Convert coordinate list into variables
print("Type in the coordinates for the upper left (x1,y1) and bottom right (x2,y2) points")
coordinates = list(map(int, input("Separate values with a space (x1 y1 x2 y2): ").strip().split()))[:4]
x1, y1, x2, y2 = coordinates
print("Generating image...")

# Accessing file from folder
im = Image.open("C:\\Users\\Alex\\Desktop\\Ps\\2.tiff")

# Cropping function
selected_region = (x1, y1, x2, y2)
cropped_region = im.crop(selected_region)

# If cropped area is vertical, rotate into horizontal position
if (y2 - y1) > (x2 - x1):
    rotated_image = cropped_region.rotate(90, expand=1) 
else:
    rotated_image = cropped_region # Does nothing is image is horizontal

# Saving image to a new folder
rotated_image.save("C:\\Users\\Alex\Desktop\\Ps\\Output\\rotated.tiff", quality=95)

标签: python-3.ximagedirectorypython-imaging-library

解决方案


您可以考虑使用pathlib. 这段代码定义pPath所示。然后循环提供该文件夹中的每个文件名。

>>> from pathlib import Path
>>> p = Path('C:/Camera/Children and yard/')
>>> for item in p.glob('*.jpg'):
...     item.name

回答问题:要获取文件的完整路径,您可以使用as_posix(). 因此,您需要的部分内容是......

im = Image.open(item.as_posix())

推荐阅读