《LearnPython-Python学习笔记》-PythonOpenCV图像相识度对比

admin 2025-11-07 01:30:43 编程 来源:ZONE.CI 全球网 0 阅读模式
  • 我们先通过下面几个方法判断图片是否相同
  • operator对图片对象进行对比
  • numpy.subtract对图片对象进行对比
  • hashlib.md5对图片对象进行对比
  • 均值哈希算法
  • 差值哈希算法
  • 感知哈希算法
  • 灰度直方图算法
  • 参考:

    强大的openCV能做什么我就不啰嗦,你能想到的一切图像+视频处理.这里,我们说说openCV的图像相似度对比, 嗯,说好听一点那叫图像识别,但严格讲, 图像识别是在一个图片中进行类聚处理,比如图片人脸识别,眼部识别,但相识度对比是指两个或两个以上的图片进行对比相似度.先来几张图片(a.png)image.png (a_cp.png)image.png (t1.png)image.png (t2.png)image.png其中,a_cp.png 是复制a.png,也就是说是同一个图片, t1.png 与t2.png 看起来相同,但都是通过PIL裁剪的图片,可以认为相似但不相同.

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

    operator对图片对象进行对比

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

    1. import operator
    2. from PIL import Image
    3. a=Image.open("a.png")
    4. a_cp=Image.open("a_cp.png")
    5. t1=Image.open("t1.png")
    6. t2=Image.open("t2.png")
    7. c=operator.eq(a,a_cp)
    8. e=operator.eq(t1,t2)
    9. print(c)
    10. print(e)

    打印结果 c为True, e为False

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

    1. import numpy as np
    2. from PIL import Image
    3. a = Image.open("a.png")
    4. a_cp = Image.open("a_cp.png")
    5. t1 = Image.open("t1.png")
    6. t2 = Image.open("t2.png")
    7. difference = np.subtract(a, a_cp) # 判断imgv 与v 的差值,存在差值,表示不相同
    8. c = not np.any(difference) # np.any 满足一个1即为真, (图片相同差值为0,np.any为false, not fasle 即为真认为存在相同的图片)
    9. difference = np.subtract(t1, t2)
    10. e = not np.any(difference)
    11. print(c)
    12. print(e)

    打印结果 c为True, e为False

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

    1. import hashlib
    2. a = open("a.png","rb")
    3. a_cp = open("a_cp.png",'rb')
    4. t1 = open("t1.png",'rb')
    5. t2 = open("t2.png",'rb')
    6. cmd5=hashlib.md5(a.read()).hexdigest()
    7. ccmd5=hashlib.md5(a_cp.read()).hexdigest()
    8. emd5=hashlib.md5(t1.read()).hexdigest()
    9. eecmd5=hashlib.md5(t2.read()).hexdigest()
    10. print(cmd5)
    11. if cmd5==ccmd5:
    12. print(True)
    13. else:
    14. print(False)
    15. print(emd5)
    16. if emd5==eecmd5:
    17. print(True)
    18. else:
    19. print(False)

    打印文件md5结果:

    1. 928f9df2d83fa5656bbd0f228c8f5f46
    2. True
    3. bff71ccd5d2c85fb0730c2ada678feea
    4. False

    由 operator.eq 与 numpy.subtract 和 hashlib.md5 方法发现,这些方法得出的结论,要不相同,要不不相同,世界万物皆如此.说的好! 你给我的是boolean值,我不要,不要,不……我们想要的就是得到两个图片的相似值,某些场景,我们需要这样的值, 比如探头监控中的人与真人照片对比,因受到距离, 分辨率,移动速度等影响,相同的人有可能无法准确辨认,在比如,连连看中的小方块,通过PIL裁剪后,相同的图像图片因灰度,尺寸大小不同我们会认为相同的图片以上三个方法就返回False. 因此openCV更适合这种百分比的相似度计算.之前用过sklearn 的 Linear Regression 做过线性回归的数据预处理计算概率,因数据量小,未做到样本训练,突发奇想,如果openCV能结合sklearn的机器学习,给一堆图片,经过fit样本训练获取图片的各种特征,随便给一张图片,然后便能知道图片来自那个地方,拍摄时间,都有哪些人物…回来,回来… 我们继续说openCV相识度问题.一般通过三种哈希算法与灰度直方图算法进行判断

    均值哈希算法

    1. #均值哈希算法
    2. def aHash(img):
    3. #缩放为8*8
    4. img=cv2.resize(img,(8,8))
    5. #转换为灰度图
    6. gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    7. #s为像素和初值为0,hash_str为hash值初值为''
    8. s=0
    9. hash_str=''
    10. #遍历累加求像素和
    11. for i in range(8):
    12. for j in range(8):
    13. s=s+gray[i,j]
    14. #求平均灰度
    15. avg=s/64
    16. #灰度大于平均值为1相反为0生成图片的hash值
    17. for i in range(8):
    18. for j in range(8):
    19. if gray[i,j]>avg:
    20. hash_str=hash_str+'1'
    21. else:
    22. hash_str=hash_str+'0'
    23. return hash_str

    差值哈希算法

    1. def dHash(img):
    2. #缩放8*8
    3. img=cv2.resize(img,(9,8))
    4. #转换灰度图
    5. gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    6. hash_str=''
    7. #每行前一个像素大于后一个像素为1,相反为0,生成哈希
    8. for i in range(8):
    9. for j in range(8):
    10. if gray[i,j]>gray[i,j+1]:
    11. hash_str=hash_str+'1'
    12. else:
    13. hash_str=hash_str+'0'
    14. return hash_str

    感知哈希算法

    1. def pHash(img):
    2. #缩放32*32
    3. img = cv2.resize(img, (32, 32)) # , interpolation=cv2.INTER_CUBIC
    4. # 转换为灰度图
    5. gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    6. # 将灰度图转为浮点型,再进行dct变换
    7. dct = cv2.dct(np.float32(gray))
    8. #opencv实现的掩码操作
    9. dct_roi = dct[0:8, 0:8]
    10. hash = []
    11. avreage = np.mean(dct_roi)
    12. for i in range(dct_roi.shape[0]):
    13. for j in range(dct_roi.shape[1]):
    14. if dct_roi[i, j] > avreage:
    15. hash.append(1)
    16. else:
    17. hash.append(0)
    18. return hash

    灰度直方图算法

    1. # 计算单通道的直方图的相似值
    2. def calculate(image1, image2):
    3. hist1 = cv2.calcHist([image1], [0], None, [256], [0.0, 255.0])
    4. hist2 = cv2.calcHist([image2], [0], None, [256], [0.0, 255.0])
    5. # 计算直方图的重合度
    6. degree = 0
    7. for i in range(len(hist1)):
    8. if hist1[i] != hist2[i]:
    9. degree = degree + (1 - abs(hist1[i] - hist2[i]) / max(hist1[i], hist2[i]))
    10. else:
    11. degree = degree + 1
    12. degree = degree / len(hist1)
    13. return degree

    RGB每个通道的直方图计算相似度

    1. def classify_hist_with_split(image1, image2, size=(256, 256)):
    2. # 将图像resize后,分离为RGB三个通道,再计算每个通道的相似值
    3. image1 = cv2.resize(image1, size)
    4. image2 = cv2.resize(image2, size)
    5. sub_image1 = cv2.split(image1)
    6. sub_image2 = cv2.split(image2)
    7. sub_data = 0
    8. for im1, im2 in zip(sub_image1, sub_image2):
    9. sub_data += calculate(im1, im2)
    10. sub_data = sub_data / 3
    11. return sub_data

    啥? 我为什么知道这三个哈希算法和通道直方图计算方法,嗯, 我也是从网上查的.上素材(x1y2.png)image.png (x2y4.png)image.png (x2y6.png)image.png (t1.png)image.png (t2.png)image.png (t3.png)image.png

    完整代码:

    1. import cv2
    2. import numpy as np
    3. # 均值哈希算法
    4. def aHash(img):
    5. # 缩放为8*8
    6. img = cv2.resize(img, (8, 8))
    7. # 转换为灰度图
    8. gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    9. # s为像素和初值为0,hash_str为hash值初值为''
    10. s = 0
    11. hash_str = ''
    12. # 遍历累加求像素和
    13. for i in range(8):
    14. for j in range(8):
    15. s = s + gray[i, j]
    16. # 求平均灰度
    17. avg = s / 64
    18. # 灰度大于平均值为1相反为0生成图片的hash值
    19. for i in range(8):
    20. for j in range(8):
    21. if gray[i, j] > avg:
    22. hash_str = hash_str + '1'
    23. else:
    24. hash_str = hash_str + '0'
    25. return hash_str
    26. # 差值感知算法
    27. def dHash(img):
    28. # 缩放8*8
    29. img = cv2.resize(img, (9, 8))
    30. # 转换灰度图
    31. gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    32. hash_str = ''
    33. # 每行前一个像素大于后一个像素为1,相反为0,生成哈希
    34. for i in range(8):
    35. for j in range(8):
    36. if gray[i, j] > gray[i, j + 1]:
    37. hash_str = hash_str + '1'
    38. else:
    39. hash_str = hash_str + '0'
    40. return hash_str
    41. # 感知哈希算法(pHash)
    42. def pHash(img):
    43. # 缩放32*32
    44. img = cv2.resize(img, (32, 32)) # , interpolation=cv2.INTER_CUBIC
    45. # 转换为灰度图
    46. gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    47. # 将灰度图转为浮点型,再进行dct变换
    48. dct = cv2.dct(np.float32(gray))
    49. # opencv实现的掩码操作
    50. dct_roi = dct[0:8, 0:8]
    51. hash = []
    52. avreage = np.mean(dct_roi)
    53. for i in range(dct_roi.shape[0]):
    54. for j in range(dct_roi.shape[1]):
    55. if dct_roi[i, j] > avreage:
    56. hash.append(1)
    57. else:
    58. hash.append(0)
    59. return hash
    60. # 通过得到RGB每个通道的直方图来计算相似度
    61. def classify_hist_with_split(image1, image2, size=(256, 256)):
    62. # 将图像resize后,分离为RGB三个通道,再计算每个通道的相似值
    63. image1 = cv2.resize(image1, size)
    64. image2 = cv2.resize(image2, size)
    65. sub_image1 = cv2.split(image1)
    66. sub_image2 = cv2.split(image2)
    67. sub_data = 0
    68. for im1, im2 in zip(sub_image1, sub_image2):
    69. sub_data += calculate(im1, im2)
    70. sub_data = sub_data / 3
    71. return sub_data
    72. # 计算单通道的直方图的相似值
    73. def calculate(image1, image2):
    74. hist1 = cv2.calcHist([image1], [0], None, [256], [0.0, 255.0])
    75. hist2 = cv2.calcHist([image2], [0], None, [256], [0.0, 255.0])
    76. # 计算直方图的重合度
    77. degree = 0
    78. for i in range(len(hist1)):
    79. if hist1[i] != hist2[i]:
    80. degree = degree + (1 - abs(hist1[i] - hist2[i]) / max(hist1[i], hist2[i]))
    81. else:
    82. degree = degree + 1
    83. degree = degree / len(hist1)
    84. return degree
    85. # Hash值对比
    86. def cmpHash(hash1, hash2):
    87. n = 0
    88. # hash长度不同则返回-1代表传参出错
    89. if len(hash1)!=len(hash2):
    90. return -1
    91. # 遍历判断
    92. for i in range(len(hash1)):
    93. # 不相等则n计数+1,n最终为相似度
    94. if hash1[i] != hash2[i]:
    95. n = n + 1
    96. return n
    97. img1 = cv2.imread('openpic/x1y2.png') # 11--- 16 ----13 ---- 0.43
    98. img2 = cv2.imread('openpic/x2y4.png')
    99. img1 = cv2.imread('openpic/x3y5.png') # 10----11 ----8------0.25
    100. img2 = cv2.imread('openpic/x9y1.png')
    101. img1 = cv2.imread('openpic/x1y2.png') # 6------5 ----2--------0.84
    102. img2 = cv2.imread('openpic/x2y6.png')
    103. img1 = cv2.imread('openpic/t1.png') # 14------19---10--------0.70
    104. img2 = cv2.imread('openpic/t2.png')
    105. img1 = cv2.imread('openpic/t1.png') # 39------33---18--------0.58
    106. img2 = cv2.imread('openpic/t3.png')
    107. hash1 = aHash(img1)
    108. hash2 = aHash(img2)
    109. n = cmpHash(hash1, hash2)
    110. print('均值哈希算法相似度:', n)
    111. hash1 = dHash(img1)
    112. hash2 = dHash(img2)
    113. n = cmpHash(hash1, hash2)
    114. print('差值哈希算法相似度:', n)
    115. hash1 = pHash(img1)
    116. hash2 = pHash(img2)
    117. n = cmpHash(hash1, hash2)
    118. print('感知哈希算法相似度:', n)
    119. n = classify_hist_with_split(img1, img2)
    120. print('三直方图算法相似度:', n)

    参考:

    https://blog.csdn.net/haofan_/article/details/77097473?locationNum=7&fps=1https://blog.csdn.net/feimengjuan/article/details/51279629http://www.cnblogs.com/chujian1120/p/5512276.htmlhttps://www.uisdc.com/head-first-histogram-design

    https://www.cnblogs.com/dcb3688/p/4610660.html