我正在使用 subreddit 爬虫从墙纸 subreddits 下载图像。我遇到的问题是某些图像的分辨率很小,导致它们在用作墙纸时看起来很糟糕。我发现好看的墙纸所需的最低分辨率是 1920x1080。我现在需要制作一个持续运行的脚本来扫描图像文件夹,查看每个图像的分辨率并决定是删除它还是移动到下一个图像。我已经在 Python 中修修补补了一个小时左右,但感觉我无处可去,因为我只是一个初学者并且已经几个月没有使用 Python 了。对这个项目的任何帮助都会很棒 ;)!干杯。
更新:我现在陷入了如何让程序运行一个文件夹并查看每张图片的问题。目前我的代码是;
import os
from PIL import Image
while True:
for file in os.listdir(r"C:\\Users\\Barney\\Documents\\sam"):
im = Image.open(file)
x, y = im.size
totalsize = x*y
if totalsize < 2073600:
os.remove(file)
但这会返回错误;
Traceback (most recent call last):
File "C:\Users\Barney\Desktop\imagefilter.py", line 7, in <module>
im = Image.open(file)
File "C:\Python34\lib\site-packages\PIL\Image.py", line 2251, in open
fp = builtins.open(fp, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'Car - 1971 Ford Mustang Mach 1 351 [2560X1600].jpg'
在互联网上我看到我打开程序的地方可能有问题??非常困惑,因为程序正在查看此文件夹并读取内容,因为它说不存在的文件在该文件夹中?有帮助吗?
最佳答案
from PIL import Image
with Image.open(image_file_path) as im:
x, y = im.size
if x < 1920 or y < 1080:
....
更新
os.listdir
返回文件名列表,而不是文件路径列表。除非您在图像目录中运行该程序,否则它无法打开该文件。
在图像目录中运行您的程序,或将文件名转换为文件路径以便可以访问它们。
import os
from PIL import Image
img_dir = r"C:\Users\Barney\Documents\sam"
for filename in os.listdir(img_dir):
filepath = os.path.join(img_dir, filename)
with Image.open(filepath) as im:
x, y = im.size
totalsize = x*y
if totalsize < 2073600:
os.remove(filepath)
关于Python 3 - 从低于 1920x1080 的文件夹中删除图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27212091/