python实现相似图片识别相似度计算的四种方式代码
代码语言:python
所属分类:其他
代码描述:python实现相似图片识别相似度计算的四种方式代码,包含直方图法、图像指纹与汉明距离、平均哈希法(aHash)、感知哈希算法(pHash)。
下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开
#- * -coding: utf - 8 - import cv2 import numpy as np import matplotlib.pyplot as plt# 最简单的以灰度直方图作为相似比较的实现 def classify_gray_hist(image1, image2, size = (256, 256)): #先计算直方图# 几个参数必须用方括号括起来# 这里直接用灰度图计算直方图, 所以是使用第一个通道,# 也可以进行通道分离后, 得到多个通道的直方图# bins 取为16 image1 = cv2.resize(image1, size) image2 = cv2.resize(image2, size) hist1 = cv2.calcHist([image1], [0], None, [256], [0.0, 255.0]) hist2 = cv2.calcHist([image2], [0], None, [256], [0.0, 255.0])# 可以比较下直方图 plt.plot(range(256), hist1, 'r') plt.plot(range(256), hist2, 'b') plt.show()# 计算直方图的重合度 degree = 0 for i in range(len(hist1)): if hist1[i] != hist2[i]: degree = degree + (1 - abs(hist1[i] - hist2[i]) / max(hist1[i],hist2[i])) else : degree = degree + 1 degree = degree / len(hist1) return degree# 计算单通道的直方图的相似值 def calculate(image1, image2): hist1 = cv2.calcHist([image1], [0], None, [256], [0.0, 255.0]) hist2 = cv2.calcHist([image2], [0], None, [256], [0.0, 255.0])# 计算直方图的重合度 degree = 0 for i in range(len(hist1)): if hist1[i] != hist2[i]: degree = degree + (1 - abs(hist1[i] - hist2[i]) / max(hist1[i],hist2[i])) else : degree = degree + 1 degree = degree / len(hist1) return degree# 通过得到每个通道的直方图来计算相似度 def classify_hist_with_split(image1, image2, size = (256, 256)): #将图像resize后, 分离为三个通道, 再计算每个通道的相似值 image1 = cv2.resize(image1, size) image2 = cv2.resize(image2, size) sub_image1 = cv2.split(image1) sub_image2 = cv2.split(image2) sub_data = 0 for im1, im2 in zip(sub_image1, sub_image2): sub_data += calculate(im1, im2) sub_data = sub_data / 3 return sub_data# 平均哈希算法计算 def classify_aHash(image1, image2): image1 = cv2.resize(image1, (8, 8)) image2 = cv2.resize(image2, (8, 8)) gray1 = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY) gray2 = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY) hash1 = getHash(gray1) hash2 = getHash(gray2) return Hamming_distance(hash1.........完整代码请登录后点击上方下载按钮下载查看
网友评论0