该工具类参考制作:https://blog.csdn.net/enter89/article/details/90293971
工具类如下:
import cv2
import numpy as np
import requests
from PIL import Image
from io import BytesIO
class ImageMatchUtils:
"""图像识别工具类"""
@classmethod
def transfer_image_by_url(cls, url):
"""
根据链接下载图片,并转换为opencv格式
:param url: 图像链接
:return: openCV格式的image
"""
# 根据图片url获取图片对象
html = requests.get(url, verify=False)
image = Image.open(BytesIO(html.content))
# 转换为opencv格式
result = cv2.cvtColor(np.asarray(image), cv2.COLOR_RGB2BGR)
return result
@classmethod
def transfer_image(cls, image_path):
"""
根据图片路径转换为opencv格式
:param image_path: 图片路径
:return: openCV格式的image
"""
return cv2.imread(image_path)
@classmethod
def aHash(cls, img):
"""
使用均值哈希算法计算图片的哈希值
:param img: openCV格式的图片,物理路径用cv2.imread()方法转换,图片链接用cv2.cvtColor()方法转换
:return: 哈希值
"""
# 缩放为8*8
img = cv2.resize(img, (8, 8))
# 转换为灰度图
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# s为像素和初值为0,hash_str为hash值初值为''
s = 0
hash_str = ''
# 遍历累加求像素和
for i in range(8):
for j in range(8):
s = s + gray[i, j]
# 求平均灰度
avg = s / 64
# 灰度大于平均值为1相反为0生成图片的hash值
for i in range(8):
for j in range(8):
if gray[i, j] > avg:
hash_str = hash_str + '1'
else:
hash_str = hash_str + '0'
return hash_str
@classmethod
def dHash(cls, img):
"""
使用差值哈希算法计算图片的哈希值
:param img: openCV格式的图片,物理路径用cv2.imread()方法转换,图片链接用cv2.cvtColor()方法转换
:return: 哈希值
"""
# 缩放8*8
img = cv2.resize(img, (9, 8))
# 转换灰度图
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
hash_str = ''
# 每行前一个像素大于后一个像素为1,相反为0,生成哈希
for i in range(8):
for j in range(8):
if gray[i, j] > gray[i, j + 1]:
hash_str = hash_str + '1'
else:
hash_str = hash_str + '0'
return hash_str
@classmethod
def pHash(cls, img):
"""
使用感知哈希算法计算图片的哈希值
:param img: openCV格式的图片,物理路径用cv2.imread()方法转换,图片链接用cv2.cvtColor()方法转换
:return: 哈希值
"""
# 缩放32*32
img = cv2.resize(img, (32, 32)) # , interpolation=cv2.INTER_CUBIC
# 转换为灰度图
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 将灰度图转为浮点型,再进行dct变换
dct = cv2.dct(np.float32(gray))
# opencv实现的掩码操作
dct_roi = dct[0:8, 0:8]
hash = []
avreage = np.mean(dct_roi)
for i in range(dct_roi.shape[0]):
for j in range(dct_roi.shape[1]):
if dct_roi[i, j] > avreage:
hash.append(1)
else:
hash.append(0)
return hash
@classmethod
def compare_hash(cls, hash1, hash2):
"""
Hash值对比,值哈希算法、差值哈希算法和感知哈希算法都是值越小,相似度越高,取值为0-64。
算法中1和0顺序组合起来的即是图片的指纹hash。顺序不固定,但是比较的时候必须是相同的顺序。
对比两幅图的指纹,计算汉明距离,即两个64位的hash值有多少是不一样的,不同的位数越小,图片越相似。
汉明距离:一组二进制数据变成另一组数据所需要的步骤,可以衡量两图的差异,汉明距离越小,则相似度越高。汉明距离为0,即两张图片完全一样
:param hash1: 第一个哈希值
:param hash2: 第二个哈希值
:return: 对比结果
"""
n = 0
# hash长度不同则返回-1代表传参出错
if len(hash1) != len(hash2):
return -1
# 遍历判断
for i in range(len(hash1)):
# 不相等则n计数+1,n最终为相似度
if hash1[i] != hash2[i]:
n = n + 1
return n
@classmethod
def calculate(cls, image1, image2):
"""
使用单通道直方图算法计算图片相似度,值为0-1,值越大,相似度越高。
:param image1: openCV格式的图片,物理路径用cv2.imread()方法转换,图片链接用cv2.cvtColor()方法转换
:param image2: openCV格式的图片,物理路径用cv2.imread()方法转换,图片链接用cv2.cvtColor()方法转换
:return: 相似度
"""
# 灰度直方图算法
# 计算单通道的直方图的相似值
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
@classmethod
def classify_hist_with_split(cls, image1, image2, size=(256, 256)):
"""
使用三通道直方图算法计算图片相似度,值为0-1,值越大,相似度越高。
:param image1: openCV格式的图片,物理路径用cv2.imread()方法转换,图片链接用cv2.cvtColor()方法转换
:param image2: openCV格式的图片,物理路径用cv2.imread()方法转换,图片链接用cv2.cvtColor()方法转换
:param size: resize之后图片的大小,默认255到255
:return: 相似度
"""
# RGB每个通道的直方图相似度
# 将图像resize后,分离为RGB三个通道,再计算每个通道的相似值
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 += cls.calculate(im1, im2)
sub_data = sub_data / 3
return sub_data
使用案例:
import time
from ImageMatchUtils import ImageMatchUtils
# 将图片转换成openCV格式
image1 = ImageMatchUtils.transfer_image("./image1.png")
image2 = ImageMatchUtils.transfer_image("./image2.png")
# image1 = ImageMatchUtils.transfer_image_by_url("./image1.jpg")
# image2 = ImageMatchUtils.transfer_image_by_url("./image2.jpg")
# 均值哈希算法
start = time.time()
image1_hash = ImageMatchUtils.aHash(image1)
image2_hash = ImageMatchUtils.aHash(image2)
result = ImageMatchUtils.compare_hash(image1_hash,image2_hash)
end = time.time()
print(f"两张图片的均值哈希算法(aHash)分别是:\n"
f"image1->{image1_hash}\n"
f"image2->{image2_hash}\n"
f"对比结果:{result}\n"
f"运行时间:{end - start}")
# 差值哈希算法
start = time.time()
image1_hash = ImageMatchUtils.dHash(image1)
image2_hash = ImageMatchUtils.dHash(image2)
result = ImageMatchUtils.compare_hash(image1_hash,image2_hash)
end = time.time()
print(f"两张图片的差值哈希算法(dHash)分别是:\n"
f"image1->{image1_hash}\n"
f"image2->{image2_hash}\n"
f"对比结果:{result}\n"
f"运行时间:{end - start}")
# 差值哈希算法
start = time.time()
image1_hash = ImageMatchUtils.pHash(image1)
image2_hash = ImageMatchUtils.pHash(image2)
result = ImageMatchUtils.compare_hash(image1_hash,image2_hash)
end = time.time()
print(f"两张图片的感知哈希算法(pHash)分别是:\n"
f"image1->{image1_hash}\n"
f"image2->{image2_hash}\n"
f"对比结果:{result}\n"
f"运行时间:{end - start}")
# 单通道直方图算法
start = time.time()
result = ImageMatchUtils.calculate(image1,image2)
end = time.time()
print(f"两张图片的单通道直方图算法对比结果为:{result}\n"
f"运行时间:{end - start}")
# 三通道直方图算法
start = time.time()
result = ImageMatchUtils.classify_hist_with_split(image1,image2)
end = time.time()
print(f"两张图片的三通道直方图算法对比结果为:{result}\n"
f"运行时间:{end - start}")