使用Python找到重复图片的方法

作者:安静到无声

摘要:在日常生活中,我们可能会遇到需要清理计算机中的大量图片文件的情况。其中一个常见的问题是重复的图片占据了大量的存储空间,因此我们需要找到并删除这些重复的图片。本文将介绍如何使用Python代码来快速找到重复图片,并将它们复制到指定文件夹。

  1. 导入所需的库和模块:
import os
from PIL import Image
  1. 定义一个函数,用于计算图片的哈希值:
def get_image_hash(image_path):
    with Image.open(image_path) as img:
        img = img.convert("L").resize((8, 8), Image.ANTIALIAS)
        avg_pixel = sum(list(img.getdata())) / 64
        hash_value = ''.join(map(lambda x: '1' if x > avg_pixel else '0', list(img.getdata())))

        return hash_value
  1. 定义一个函数,用于找到重复的图片:
def find_duplicate_images(folder_path, target_folder_path):
    image_paths = []

    for root, dirs, files in os.walk(folder_path):
        for file_name in files:
            if file_name.endswith('.png') or file_name.endswith('.jpg') or file_name.endswith('.jpeg'):
                image_paths.append(os.path.join(root, file_name))

    processed_hashes = set()
    duplicate_image_paths = set()
    duplicate_image_mapping = {}

    for image_path in image_paths:
        image_hash = get_image_hash(image_path)
        if image_hash in processed_hashes:
            duplicate_image_paths.add(image_path)
        else:
            processed_hashes.add(image_hash)

    for image_path in duplicate_image_paths:
        image_name = os.path.basename(image_path)
        target_path = os.path.join(target_folder_path, image_name)
        os.makedirs(target_folder_path, exist_ok=True)
        os.rename(image_path, target_path)
        duplicate_image_mapping[image_name] = image_name

    with open(os.path.join(target_folder_path, 'duplicate_mapping.txt'), 'w', encoding='utf-8') as f:
        for key, value in duplicate_image_mapping.items():
            f.write(f"{key} : {value}\n")
  1. 执行主程序:
if __name__ == '__main__':
    find_duplicate_images(r'图片文件夹路径', r'目标文件夹路径')

将代码中的图片文件夹路径替换为包含需要检查的图片的文件夹的路径,将目标文件夹路径替换为希望将重复图片复制到的文件夹的路径。

  1. 运行程序并等待结果。程序会在指定的目标文件夹中复制重复的图片,并生成一个名为duplicate_mapping.txt的文件,其中包含每个重复图片与其对应重复图片的映射关系。

结论:使用以上代码,我们可以快速找到并删除重复的图片,从而节省存储空间并提高计算机的整体性能。