如何使用python 实现照片去重

19 min read

照片去重可以通过计算照片的哈希值来实现。哈希值是根据照片的像素进行计算的数字指纹,相同的照片其哈希值也相同。

下面是利用Python实现照片去重的步骤:

  1. 安装imagehash库,可以使用pip install imagehash命令进行安装。

  2. 使用imagehash库中的phash函数计算照片的哈希值,比较两张照片的哈希值是否相同,如果相同,则认为这两张照片是同一张照片。代码如下:

from PIL import Image
import imagehash

def is_same_image(image_path1, image_path2):
    """判断两张照片是否相同"""
    hash1 = imagehash.phash(Image.open(image_path1))
    hash2 = imagehash.phash(Image.open(image_path2))
    return hash1 == hash2

  1. 对于多张照片,可以使用双重循环进行比较,找出重复的照片,然后进行删除。代码如下:
import os

def remove_duplicates(path):
    """删除重复照片"""
    images = os.listdir(path)
    for i in range(len(images)):
        for j in range(i+1, len(images)):
            if is_same_image(os.path.join(path, images[i]), os.path.join(path, images[j])):
                os.remove(os.path.join(path, images[j]))
  1. 调用remove_duplicates函数删除重复的照片。
path = 'path/to/your/photos'
remove_duplicates(path)

需要注意的是,该方法仅适用于完全相同的照片,对于轻微差异的照片无法去重。同时,也要确保照片的命名不能重复,否则无法正确删除重复的照片。