Python OpenCV 图像相识度对比

强大的openCV能做什么我就不啰嗦,你能想到的一切图像+视频处理.

这里,我们说说openCV的图像相似度对比, 嗯,说好听一点那叫图像识别,但严格讲, 图像识别是在一个图片中进行类聚处理,比如图片人脸识别,眼部识别,但相识度对比是指两个或两个以上的图片进行对比相似度.

先来几张图片

(a.png)     (a_cp.png)      (t1.png)        (t2.png)

其中,a_cp.png 是复制a.png,也就是说是同一个图片, t1.png 与t2.png 看起来相同,但都是通过PIL裁剪的图片,可以认为相似但不相同. 

我们先通过下面几个方法判断图片是否相同

operator对图片对象进行对比

operator.eq(a,b) 判断a,b 对象是否相同

import operator
from PIL import Image


a=Image.open("a.png")
a_cp=Image.open("a_cp.png")

t1=Image.open("t1.png")
t2=Image.open("t2.png")


c=operator.eq(a,a_cp)
e=operator.eq(t1,t2)
print(c)
print(e)

打印结果 c为True, e为False

numpy.subtract对图片对象进行对比

import numpy as np
from PIL import Image

a = Image.open("a.png")
a_cp = Image.open("a_cp.png")

t1 = Image.open("t1.png")
t2 = Image.open("t2.png")

difference = np.subtract(a, a_cp)  # 判断imgv 与v 的差值,存在差值,表示不相同
c = not np.any(difference)  # np.any 满足一个1即为真, (图片相同差值为0,np.any为false, not fasle 即为真认为存在相同的图片)

difference = np.subtract(t1, t2)
e = not np.any(difference)

print(c)
print(e)

打印结果 c为True, e为False

hashlib.md5对图片对象进行对比

import hashlib

a = open("a.png","rb")
a_cp = open("a_cp.png",'rb')

t1 = open("t1.png",'rb')
t2 = open("t2.png",'rb')

cmd5=hashlib.md5(a.read()).hexdigest()
ccmd5=hashlib.md5(a_cp.read()).hexdigest()

emd5=hashlib.md5(t1.read()).hexdigest()
eecmd5=hashlib.md5(t2.read()).hexdigest()

print(cmd5)
if cmd5==ccmd5:
    print(True)
else:
    print(False)

print(emd5)
if emd5==eecmd5:
    print(True)
else:
    print(False)

打印文件md5结果:

928f9df2d83fa5656bbd0f228c8f5f46
True
bff71ccd5d2c85fb0730c2ada678feea
False

 由 operator.eq  与 numpy.subtract   和 hashlib.md5 方法发现,这些方法得出的结论,要不相同,要不不相同,世界万物皆如此.

说的好! 你给我的是boolean值,我不要,不要,不......

我们想要的就是得到两个图片的相似值,某些场景,我们需要这样的值, 比如探头监控中的人与真人照片对比,因受到距离, 分辨率,移动速度等影响,相同的人有可能无法准确辨认,在比如,连连看中的小方块,通过PIL裁剪后,相同的图像图片因灰度,尺寸大小不同我们会认为相同的图片以上三个方法就返回False. 因此openCV更适合这种百分比的相似度计算.

之前用过sklearn 的 Linear Regression 做过线性回归的数据预处理计算概率,因数据量小,未做到样本训练,突发奇想,如果openCV能结合sklearn的机器学习,给一堆图片,经过fit样本训练获取图片的各种特征,随便给一张图片,然后便能知道图片来自那个地方,拍摄时间,都有哪些人物...

回来,回来... 我们继续说openCV相识度问题.

 一般通过三种哈希算法与灰度直方图算法进行判断

均值哈希算法

#均值哈希算法
def aHash(img):
    #缩放为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

差值哈希算法

def dHash(img):
    #缩放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

感知哈希算法

def pHash(img):
    #缩放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

灰度直方图算法

# 计算单通道的直方图的相似值
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
RGB每个通道的直方图计算相似度
def classify_hist_with_split(image1, image2, size=(256, 256)):
    # 将图像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 += calculate(im1, im2)
    sub_data = sub_data / 3
    return sub_data

啥? 

我为什么知道这三个哈希算法和通道直方图计算方法,嗯, 我也是从网上查的.

上素材

(x1y2.png)    (x2y4.png)     (x2y6.png)        (t1.png)         (t2.png)      (t3.png)

完整代码:

import cv2
import numpy as np


# 均值哈希算法
def aHash(img):
    # 缩放为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


# 差值感知算法
def dHash(img):
    # 缩放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


# 感知哈希算法(pHash)
def pHash(img):
    # 缩放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


# 通过得到RGB每个通道的直方图来计算相似度
def classify_hist_with_split(image1, image2, size=(256, 256)):
    # 将图像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 += calculate(im1, im2)
    sub_data = sub_data / 3
    return sub_data


# 计算单通道的直方图的相似值
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


# Hash值对比
def cmpHash(hash1, hash2):
    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


img1 = cv2.imread('openpic/x1y2.png')  #  11--- 16 ----13 ---- 0.43
img2 = cv2.imread('openpic/x2y4.png')

img1 = cv2.imread('openpic/x3y5.png')  #  10----11 ----8------0.25
img2 = cv2.imread('openpic/x9y1.png')

img1 = cv2.imread('openpic/x1y2.png')  #  6------5 ----2--------0.84
img2 = cv2.imread('openpic/x2y6.png')

img1 = cv2.imread('openpic/t1.png')  #    14------19---10--------0.70
img2 = cv2.imread('openpic/t2.png')

img1 = cv2.imread('openpic/t1.png')  #    39------33---18--------0.58
img2 = cv2.imread('openpic/t3.png')

hash1 = aHash(img1)
hash2 = aHash(img2)
n = cmpHash(hash1, hash2)
print('均值哈希算法相似度:', n)

hash1 = dHash(img1)
hash2 = dHash(img2)
n = cmpHash(hash1, hash2)
print('差值哈希算法相似度:', n)

hash1 = pHash(img1)
hash2 = pHash(img2)
n = cmpHash(hash1, hash2)
print('感知哈希算法相似度:', n)

n = classify_hist_with_split(img1, img2)
print('三直方图算法相似度:', n)

参考:

https://blog.csdn.net/haofan_/article/details/77097473?locationNum=7&fps=1

https://blog.csdn.net/feimengjuan/article/details/51279629

http://www.cnblogs.com/chujian1120/p/5512276.html

https://www.uisdc.com/head-first-histogram-design

原文地址:https://www.cnblogs.com/dcb3688/p/4610660.html