怎么看两张图片的相似度_Python怎么判断重复

怎么看两张图片的相似度_Python怎么判断重复在 Python 中 判断两张图片是否相同可以通过多种方法实现 以下是几种常见的方法 像素值比较 使用 OpenCV 库读取图片 然后直接比较两个图像的像素值 pythonimport cv2 file1 path to image1 jpg file2 path to image2 jpg image1 cv2 imread file1 image2 cv2

在Python中,判断两张图片是否相同可以通过多种方法实现,以下是几种常见的方法:

像素值比较

使用OpenCV库读取图片,然后直接比较两个图像的像素值。

python

import cv2

file1 = "path/to/image1.jpg"

file2 = "path/to/image2.jpg"

image1 = cv2.imread(file1)

image2 = cv2.imread(file2)

if image1.any() == image2.any():

print("两张图片一样")

else:

print("两张图片不一样")

哈希值比较

使用平均哈希(aHash)或差值感知哈希(dHash)算法来比较图片的哈希值。

python

import cv2

def aHash(img):

img = cv2.resize(img, (8, 8), interpolation=cv2.INTER_CUBIC)

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

s = 0

hash_str = ""

for i in range(8):

for j in range(8):

s += gray[i, j]

avg = s / 64

for i in range(8):

for j in range(8):

if gray[i, j] > avg:

hash_str += "1"

else:

hash_str += "0"

return hash_str

读取图片并计算哈希值

image1 = cv2.imread(file1)

image2 = cv2.imread(file2)

hash1 = aHash(image1)

hash2 = aHash(image2)

if hash1 == hash2:

print("两张图片一样")

else:

print("两张图片不一样")

结构相似性指数(SSIM)

使用`scikit-image`库中的`ssim`函数来计算两张图片的SSIM值。

python

from skimage.metrics import structural_similarity as ssim

读取图片

image1 = cv2.imread(file1)

image2 = cv2.imread(file2)

计算SSIM

ssim_index = ssim(image1, image2, full=True)

if ssim_index == 1.0:

print("两张图片一样")

else:

print("两张图片不一样")

直方图比较

计算两张图片的颜色直方图,然后比较直方图的相似度。

python

from PIL import Image

def get_histogram(image):

img = Image.open(image)

img = img.convert('RGB')

hist = img.histogram()

return hist

读取图片并获取直方图

image1 = Image.open(file1)

image2 = Image.open(file2)

hist1 = get_histogram(image1)

hist2 = get_histogram(image2)

比较直方图

similarity = sum(1 - (0 if l == r else float(abs(l - r)) / max(l, r)) for l, r in zip(hist1, hist2)) / len(hist1)

if similarity == 1.0:

print("两张图片一样")

else:

print("两张图片不一样")

以上方法都可以用来判断两张图片是否相同,具体选择哪种方法取决于你的使用场景和对结果精度的要求。需要注意的是,以上代码示例可能需要根据你的实际文件路径和库版本进行调整。

编程小号
上一篇 2026-05-11 09:20
下一篇 2026-05-11 09:16

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/43457.html