【问题标题】:Python 3 - Deleting pictures from a folder that are under 1920x1080Python 3 - 从 1920x1080 以下的文件夹中删除图片
【发布时间】:2014-11-30 10:07:59
【问题描述】:

我正在使用 subreddit 刮板从壁纸 subreddit 下载图像。我遇到的问题是某些图像的分辨率很小,导致它们在用作壁纸时看起来很糟糕。我发现一张好看的壁纸所需的最低分辨率是 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'

查看互联网我发现我打开程序的位置可能有问题??当程序正在查看此文件夹并读取内容时非常困惑,因为它说不存在的文件在该文件夹中?有什么帮助吗?

【问题讨论】:

标签: python python-3.x file-handling


【解决方案1】:

您可以使用PillowPIL

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)

【讨论】:

  • 很抱歉再次打扰您,但现在我收到一个新错误:PermissionError: [WinError 32] 该进程无法访问该文件,因为它正被另一个进程使用。你知道解决办法吗?
  • @user2885647,您需要关闭图像。我相应地更新了答案。如果这对您有帮助,您能否再次接受我的回答?
【解决方案2】:

如果主文件夹下有很多子文件夹,可以使用以下代码:

[for directory_path in glob.glob(r'F:\Data\Main_folder\*'):
    print(directory_path)
    for filename in os.listdir(directory_path):
        filepath = os.path.join(directory_path, filename)
        print(filepath)
        with Image.open(filepath) as im:
            x, y = im.size
        totalsize = x*y
        if totalsize < 50176:
            os.remove(filepath)][1]
   

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-13
    • 2017-08-11
    • 2012-07-07
    • 1970-01-01
    • 2016-12-10
    • 2016-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多