python - 检查包含数十万张图像的目录中损坏的文件的速度逐渐变慢

标签 python python-imaging-library

所以我有 600,000 多张图像。我估计其中大约 5-10% 已损坏。我正在生成一个日志,准确记录与该图像相关的图像。

使用Python,到目前为止我的方法是这样的:

def img_validator(source):
    files = get_paths(source)  # A list of complete paths to each image
    invalid_files = []
    for img in files:
        try:
            im = Image.open(img)
            im.verify()
            im.close()
        except (IOError, OSError, Image.DecompressionBombError):
            invalid_files.append(img)

     # Write invalid_files to file

前 200-250K 图像的处理速度相当快,大约只需要 1-2 小时。我让该进程运行一整夜(当时为 230K),8 小时后它只有 310K,但仍在进行中。

有人知道这是为什么吗?起初我以为这可能是由于图像存储在 HDD 上,但这并没有真正意义,因为前 200-250k 速度非常快。

最佳答案

如果您有那么多图像,我建议您使用多重处理。我创建了 100,000 个文件,其中 5% 已损坏,并按如下方式检查它们:

#!/usr/bin/env python3

import glob
from multiprocessing import Pool
from PIL import Image

def CheckOne(f):
    try:
        im = Image.open(f)
        im.verify()
        im.close()
        # DEBUG: print(f"OK: {f}")
        return
    except (IOError, OSError, Image.DecompressionBombError):
        # DEBUG: print(f"Fail: {f}")
        return f

if __name__ == '__main__':
    # Create a pool of processes to check files
    p = Pool()

    # Create a list of files to process
    files = [f for f in glob.glob("*.jpg")]

    print(f"Files to be checked: {len(files)}")

    # Map the list of files to check onto the Pool
    result = p.map(CheckOne, files)

    # Filter out None values representing files that are ok, leaving just corrupt ones
    result = list(filter(None, result)) 
    print(f"Num corrupt files: {len(result)}")

示例输出

Files to be checked: 100002
Num corrupt files: 5001

在我的带有 NVME 磁盘的 12 核 CPU 上,这需要 1.6 秒,但对您来说应该仍然明显更快。

关于python - 检查包含数十万张图像的目录中损坏的文件的速度逐渐变慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59155213/

相关文章:

python tkinter 使用 PIL 显示动画 GIF

python - 如何使用 Python 监视屏幕 session ?

python - 嵌套 For 循环到列表理解

python - 如何检测我的 python 代码是否在 PowerShell 或命令提示符 (cmd) 中运行

python - Pillow 中 float 图像的堆叠线图

python - 有没有一种精确的方法来测量Python(3.7)中特定字体的文本大小?

python - 从 PIL 获取像素值列表

python - 使用 Python 解析像素数据的最有效/最快速的方法?

python - BeautifulSoup find - 从感兴趣的 block 中排除嵌套标签

python复合和/或如果条件