Python受欢迎的原因之一就是其计算生态丰富,据不完全统计,Python 目前为止有约13万+的第三方库。
本系列将会陆续整理分享一些有趣、有用的第三方库。
-
通过百度网盘获取:
链接:https://pan.baidu.com/s/1FSGLd7aI_UQlCQuovVHc_Q?pwd=mnsj提取码:mnsj
-
前往GitHub获取:
https://github.com/returu/Python_Ecosystem
-
平均哈希(Average Hash):
-
原理:
-
特点:
-
感知哈希(Perceptual Hash):
-
原理:
-
特点:
-
差异哈希(Difference Hash):
-
原理:
-
特点:
-
小波哈希(Wavelet Hash):
-
原理:
-
特点:
-
HSV 颜色哈希(Color Hash):
-
原理:
-
特点:
-
抗裁剪哈希(Crop-Resistant Hashing):
-
原理:
-
特点:
pip install imagehash
https://github.com/Zulko/moviepy
本次使用 ImageHash 库中的不同哈希方法分别计算以下三张图片的哈希值,然后根据manhattan distance (hash1 – hash2 < threshold)判断哪些图像是相似的。
![]() |
![]() |
![]() |
示例代码:
每种哈希算法还可以通过hashsize参数调整哈希大小(对于颜色哈希,可以调整 binbits参数)。增加哈希大小可以让算法在哈希中存储更多细节,从而提高对细节变化的敏感性。
在 crop_resistant_hash 方法中,通过以下两个参数控制图像分割的方式和哈希计算的精度:
-
min_segment_size参数用于指定每个分割区域的最小像素数量。如果某个区域的像素数量小于该值,则会被忽略。
-
hsegmentation_image_size参数用于控制图像在进行分割时的缩放尺寸。图像会先缩放到 segmentation_image_size 的大小,然后再进行分割。
from PIL import Image
import imagehash
import os
# 图像路径
image_paths = ['img_1.png', 'img_2.png', 'img_3.png']
# 哈希方法列表
hash_methods = {
"Average Hash": imagehash.average_hash,
"Perceptual Hash": imagehash.phash,
"Difference Hash": imagehash.dhash,
"Wavelet Hash": imagehash.whash,
"Color Hash": imagehash.colorhash,
"Crop-Resistant Hash": imagehash.crop_resistant_hash
}
# 相似性阈值
threshold = 20 # 可根据需求调整
# 计算所有图像的哈希值
hashes = {}
for method_name, method in hash_methods.items():
print(f"计算 {method_name}...")
hashes[method_name] = {}
for path in image_paths:
try:
img = Image.open(path)
hash_value = method(img)
hashes[method_name][path] = hash_value
print(f"{path}: {hash_value}")
except Exception as e:
print(f"无法处理 {path}: {e}")
# 比较图像相似性
for method_name, hash_dict in hashes.items():
print(f"n使用 {method_name} 比较图像相似性:")
images = list(hash_dict.keys())
for i in range(len(images)):
for j in range(i + 1, len(images)):
img1 = images[i]
img2 = images[j]
hash1 = hash_dict[img1]
hash2 = hash_dict[img2]
distance = hash1 - hash2 # 计算距离
if distance <= threshold:
print(f"'{img1}' 和 '{img2}' 相似 (距离: {distance})")
输出结果:

-
对于单个感知哈希:
original_hash = imagehash.phash(Image.open('./img_1.png'))
# 哈希值转换为字符串
hash_as_str = str(original_hash)
print(hash_as_str)
# 输出:92a71cdc79d980e3
# 字符串重新转换为ImageHash对象
restored_hash = imagehash.hex_to_hash(hash_as_str)
print(restored_hash)
# 输出:92a71cdc79d980e3
print(restored_hash == original_hash)
# 输出:True
print(str(restored_hash) == hash_as_str)
# 输出:True
-
对于抗裁剪哈希:
original_hash = imagehash.crop_resistant_hash(Image.open('./img_1.png'), min_segment_size=500, segmentation_image_size=1000)
# 哈希值转换为字符串
hash_as_str = str(original_hash)
print(hash_as_str)
# 输出:ccd9f3e5e1c18100,706c6e66464cb9b1,......
# 字符串重新转换为ImageHash对象
restored_hash = imagehash.hex_to_multihash(hash_as_str)
print(restored_hash)
# 输出:ccd9f3e5e1c18100,706c6e66464cb9b1,......
print(restored_hash == original_hash)
# 输出:True
print(str(restored_hash) == hash_as_str)
# 输出:True
更多内容可以前往官方文档查看:
https://zulko.github.io/moviepy/


本篇文章来源于微信公众号: 码农设计师



