【问题标题】:Accessing all images in a folder with incremental names使用增量名称访问文件夹中的所有图像
【发布时间】:2020-02-13 21:22:25
【问题描述】:

我正在尝试编写一个程序,我将在其中裁剪然后旋转文件夹中的每个图像。我目前能够为单个图像执行此操作,并且我知道我可以手动将它们全部输入。但是我想知道如何循环它,因为大约有 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.x image directory python-imaging-library


    【解决方案1】:

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

    >>> 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())
    

    【讨论】:

    • 感谢您的快速回复。如果这是一个愚蠢的问题,我很抱歉,但是,我将如何调用每个图像来应用裁剪功能。如果有帮助,我的每张照片都命名为 test1.tiff、test2.tiff...谢谢。
    • 请查看补充答案。
    • 我想我终于让它工作了。谢谢大家的帮助。
    猜你喜欢
    • 2018-11-30
    • 1970-01-01
    • 1970-01-01
    • 2012-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-25
    • 2012-10-24
    相关资源
    最近更新 更多