杜老师说

杜老师说

马上订阅 杜老师说 RSS 更新: https://dusays.com/atom.xml

使用 Python 脚本实现图片相似度匹配

2025年9月16日 00:00

随着相机像素越来越大,图片体积也变大了。在图片处理中,较大的文件体积会影响性能,因此杜老师会先生成缩略图,筛选完成后再通过 Python 脚本实现图片相似度匹配。这里是一个简单的示例,供需要的小伙伴们参考。

脚本说明

以下是个基于 Python 的脚本,使用 PIL 以及 imagehash 库来实现。

遍历目录 A 中所有图片。

在目录 B 中查找相似的图片「通过感知哈希算法判断」

如找到匹配项,则将图片复制到目录 C,并以目录 A 图片的名字命名。

安装依赖

1
pip install pillow imagehash

注意:在运行脚本前,需安装所需的 Python 库。

脚本示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import os
import shutil
from PIL import Image
import imagehash

# 定义目录路径
dir_a = 'path/to/dirA'
dir_b = 'path/to/dirB'
dir_c = 'path/to/dirC'

# 设置相似度阈值(越小越严格)
threshold = 5

# 获取图片的感知哈希值
def get_image_hash(filepath):
try:
return imagehash.phash(Image.open(filepath))
except Exception as e:
print(f"无法处理文件 {filepath}: {e}")
return None

# 判断两个哈希值是否相似
def is_similar(hash1, hash2):
return hash1 - hash2 <= threshold

# 确保目标目录存在
os.makedirs(dir_c, exist_ok=True)

# 遍历目录 A
for filename in os.listdir(dir_a):
file_a_path = os.path.join(dir_a, filename)

# 检查是否为图片
if not filename.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp')):
continue

hash_a = get_image_hash(file_a_path)
if hash_a is None:
continue

# 遍历目录 B 寻找相似图片
for b_filename in os.listdir(dir_b):
file_b_path = os.path.join(dir_b, b_filename)

# 检查是否为图片
if not b_filename.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp')):
continue

hash_b = get_image_hash(file_b_path)...

剩余内容已隐藏

查看完整文章以阅读更多