python-3.x - 使用增量名称访问文件夹中的所有图像
问题描述
我正在尝试编写一个程序,我将在其中裁剪然后旋转文件夹中的每个图像。我目前能够为单个图像执行此操作,并且我知道我可以手动将它们全部输入。但是我想知道如何循环它,因为大约有 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)
解决方案
您可以考虑使用pathlib
. 这段代码定义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())
推荐阅读
- c++ - 堆栈变量和函数的 C++ 奇怪行为
- sql - 确定 SQL 间隙和孤岛中的连续日期
- javascript - 意外令牌{错误
- javascript - hml表单提交后如何运行jquery代码
- mysql - 使用 HeidiSql 访问 MySql
- haskell - 使用 catamorphism 忘记 Cofree 注释
- python - django-rest-framework-gis GeoFeatureModelSerializer 在序列化时返回更改/不正确的坐标
- javascript - chart.js : 圆环图中的标签
- php - 使用 PHP 和 AJAX 选择器表单查询 MySQL
- javascript - 如何在定义对象时访问它本身的属性?