当前位置:   article > 正文

图像数据处理12

图像数据处理12

2.6 直方图匹配

什么是直方图匹配?

找到一个变换函数,尽可能使处理图像的灰度直方图与指定图像的灰度直方图相匹配。其原理则是

让输入图像灰度值的累积直方图尽可能等于指定图像灰度值的累积直方图

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from skimage import io, exposure
  4. import os
  5. # 定义图像文件路径
  6. img_path = 'slpn_gray.jpg'
  7. imgref_path = 'slpn2.jpg'
  8. # 检查文件是否存在
  9. if not os.path.exists(img_path) or not os.path.exists(imgref_path):
  10. raise FileNotFoundError("One of the specified image files does not exist.")
  11. # 读入原图像和参考图像
  12. img = io.imread(img_path)
  13. imgref = io.imread(imgref_path)
  14. # 检查图像是否为灰度图,如果不是,则转换为灰度图
  15. if img.ndim == 3:
  16. img = img.mean(axis=2)
  17. if imgref.ndim == 3:
  18. imgref = imgref.mean(axis=2)
  19. # 确保图像数据类型为float,因为match_histograms期望float类型的输入
  20. if img.dtype != np.float64:
  21. img = img.astype(np.float64)
  22. if imgref.dtype != np.float64:
  23. imgref = imgref.astype(np.float64)
  24. # 标准化图像到[0, 1]范围(如果它们不是)
  25. img /= 255.0
  26. imgref /= 255.0
  27. # 进行直方图匹配
  28. imgmatched = exposure.match_histograms(img, imgref)
  29. # 转换回uint8以便显示
  30. img_to_show = np.uint8(img * 255)
  31. imgref_to_show = np.uint8(imgref * 255)
  32. imgmatched_to_show = np.uint8(imgmatched * 255)
  33. # 创建一个带有额外轴的图形来显示直方图
  34. fig, axs = plt.subplots(3, 2, figsize=(12, 12))
  35. # 原始图像
  36. axs[0, 0].imshow(img_to_show, cmap='gray')
  37. axs[0, 0].set_title('Original Image')
  38. axs[0, 0].axis('off')
  39. # 原始图像的直方图
  40. axs[0, 1].hist(img_to_show.ravel(), bins=256, range=[0, 256])
  41. axs[0, 1].set_title('Histogram')
  42. axs[0, 1].axis('off')
  43. # 参考图像
  44. axs[1, 0].imshow(imgref_to_show, cmap='gray')
  45. axs[1, 0].set_title('Reference Image')
  46. axs[1, 0].axis('off')
  47. # 参考图像的直方图
  48. axs[1, 1].hist(imgref_to_show.ravel(), bins=256, range=[0, 256])
  49. axs[1, 1].set_title('Histogram')
  50. axs[1, 1].axis('off')
  51. # 匹配后的图像
  52. axs[2, 0].imshow(imgmatched_to_show, cmap='gray')
  53. axs[2, 0].set_title('Matched Image')
  54. axs[2, 0].axis('off')
  55. # 匹配后图像的直方图
  56. axs[2, 1].hist(imgmatched_to_show.ravel(), bins=256, range=[0, 256])
  57. axs[2, 1].set_title('Histogram')
  58. axs[2, 1].axis('off')
  59. plt.tight_layout()
  60. plt.show()

imgmatched = exposure.match_histograms(img, imgref)

此处为直方图匹配代码,调用了scikit-image库中的 exposure 模块的 match_histograms 函数

本节内容是该章节最后一小节,内容较少,所以又水了一节。

注,本人为在校学生,博客是边学边写的,主要是为了巩固知识,如有错误请积极指正。

“本文章中所使用的圣灵谱尼图片来源于网络,版权归属原作者所有。若您认为本文章/作品的使用侵犯了您的权益,请及时与我联系,我将尽快核实并删除相关内容。

本文的内容主要基于我对张运楚教授编著的《数字图像处理》一书的学习和理解。这本书深入浅出地介绍了数字图像处理的基本理论以及经典算法等,并且提供了丰富的示例代码和实际用例,极大地帮助了我学习图像处理知识。在此,我推荐大家阅读这本书,更加深入的学习有关图像处理的知识。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/空白诗007/article/detail/1007074
推荐阅读
相关标签
  

闽ICP备14008679号