答案:通过计算图片哈希值可判断文件夹内是否有重复图片。1. 使用imagehash库的average_hash进行感知哈希比对,识别视觉相似图像;2. 用MD5哈希检测字节完全相同的文件;3. 统一转换为RGB模式后再计算哈希,解决不同格式但内容相同问题;4. 结合文件大小筛选、跳过特定文件、递归遍历子目录提升效率。根据需求选择合适方法即可准确找出重复图片。

判断文件夹内是否有重复图片,关键不是看文件名,而是比较图片内容是否相同。Python可以通过计算图片的哈希值来快速识别重复项。以下是几种实用方法:
将图片转换为哈希值,内容相同的图片哈希一致。常用的是感知哈希(Perceptual Hash),对轻微变化不敏感,适合找视觉上几乎一样的图。
# 安装依赖:pip install Pillow imagehash示例代码:
import os
from PIL import Image
import imagehash
<p>def find_duplicate_images(folder_path):
hashes = {}
duplicates = []</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">for filename in os.listdir(folder_path):
filepath = os.path.join(folder_path, filename)
if not os.path.isfile(filepath):
continue
try:
with Image.open(filepath) as img:
img_hash = imagehash.average_hash(img)
if img_hash in hashes:
duplicates.append((filename, hashes[img_hash]))
else:
hashes[img_hash] = filename
except Exception as e:
print(f"无法处理文件 {filename}: {e}")
return duplicates立即学习“Python免费学习笔记(深入)”;
运行后返回重复图片对,比如 ('pic2.jpg', 'pic1.jpg') 表示 pic2 和 pic1 内容重复。
如果想找出完全一致的文件(字节级别相同),可以用文件的MD5值:
import os
import hashlib
<p>def get_file_hash(filepath):
with open(filepath, 'rb') as f:
return hashlib.md5(f.read()).hexdigest()</p><p>def find_exact_duplicates(folder_path):
hash_dict = {}
duplicates = []</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">for filename in os.listdir(folder_path):
filepath = os.path.join(folder_path, filename)
if not os.path.isfile(filepath):
continue
file_hash = get_file_hash(filepath)
if file_hash in hash_dict:
duplicates.append((filename, hash_dict[file_hash]))
else:
hash_dict[file_hash] = filename
return duplicates立即学习“Python免费学习笔记(深入)”;
有时同一张图保存为 .jpg 和 .png,内容一样但格式不同。这时用PIL加载后转成统一格式再哈希更可靠:
with Image.open(filepath) as img:
img = img.convert('RGB') # 统一颜色模式
img_hash = imagehash.average_hash(img)
这样即使格式不同,只要视觉内容接近,也能识别为重复。
基本上就这些。用 imagehash 最省事,准确率高;用 MD5 可以确保字节一致。根据需求选合适的方法就行。
以上就是python如何判断文件夹内的重复图片的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号