云计算期末大作业 论文图像复用的机器自动检查 魏如蓝 10172100262
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

43 lines
1.4 KiB

3 years ago
  1. import matplotlib.pyplot as plt
  2. # 正则化图像
  3. def regularizeImage(img, size = (256, 256)):
  4. return img.resize(size).convert('RGB')
  5. # 画出直方图图像
  6. def drawHistogram(hg1, hg2):
  7. plt.plot(range(len(hg1)), hg1, color='blue', linewidth=1.5, label='img1')
  8. plt.plot(range(len(hg2)), hg2, color='red', linewidth=1.5, label='img2')
  9. plt.legend(loc='upper left')
  10. plt.title('Histogram Similarity')
  11. plt.show()
  12. # 分块图像4x4
  13. def splitImage(img, part_size = (64, 64)):
  14. w, h = img.size
  15. pw, ph = part_size
  16. data = []
  17. for i in range(0, w, pw):
  18. for j in range(0, h, ph):
  19. data.append(img.crop((i, j, i + pw, j + ph)).copy())
  20. return data
  21. # 利用单块图片的直方图距离计算相似度
  22. def calSingleHistogramSimilarity(hg1, hg2):
  23. if len(hg1) != len(hg2):
  24. raise Exception('样本点个数不一样')
  25. sum = 0
  26. for x1, x2 in zip(hg1, hg2):
  27. if x1 != x2:
  28. sum += 1 - float(abs(x1 - x2) / max(x1, x2))
  29. else:
  30. sum += 1
  31. return sum / len(hg1)
  32. # 利用分块图片的直方图距离计算相似度
  33. def calMultipleHistogramSimilarity(img1, img2):
  34. answer = 0
  35. for sub_img1, sub_img2 in zip(splitImage(img1), splitImage(img2)):
  36. answer += calSingleHistogramSimilarity(sub_img1.histogram(), sub_img2.histogram())
  37. return float(answer / 16.0)
  38. __all__ = ['regularizeImage', 'drawHistogram', 'calMultipleHistogramSimilarity']