赞
踩
2.6 直方图匹配
什么是直方图匹配?
找到一个变换函数,尽可能使处理图像的灰度直方图与指定图像的灰度直方图相匹配。其原理则是
让输入图像灰度值的累积直方图尽可能等于指定图像灰度值的累积直方图。
- import numpy as np
- import matplotlib.pyplot as plt
- from skimage import io, exposure
- import os
-
- # 定义图像文件路径
- img_path = 'slpn_gray.jpg'
- imgref_path = 'slpn2.jpg'
-
- # 检查文件是否存在
- if not os.path.exists(img_path) or not os.path.exists(imgref_path):
- raise FileNotFoundError("One of the specified image files does not exist.")
-
- # 读入原图像和参考图像
- img = io.imread(img_path)
- imgref = io.imread(imgref_path)
-
- # 检查图像是否为灰度图,如果不是,则转换为灰度图
- if img.ndim == 3:
- img = img.mean(axis=2)
- if imgref.ndim == 3:
- imgref = imgref.mean(axis=2)
-
- # 确保图像数据类型为float,因为match_histograms期望float类型的输入
- if img.dtype != np.float64:
- img = img.astype(np.float64)
- if imgref.dtype != np.float64:
- imgref = imgref.astype(np.float64)
-
- # 标准化图像到[0, 1]范围(如果它们不是)
- img /= 255.0
- imgref /= 255.0
-
- # 进行直方图匹配
- imgmatched = exposure.match_histograms(img, imgref)
-
- # 转换回uint8以便显示
- img_to_show = np.uint8(img * 255)
- imgref_to_show = np.uint8(imgref * 255)
- imgmatched_to_show = np.uint8(imgmatched * 255)
-
- # 创建一个带有额外轴的图形来显示直方图
- fig, axs = plt.subplots(3, 2, figsize=(12, 12))
-
- # 原始图像
- axs[0, 0].imshow(img_to_show, cmap='gray')
- axs[0, 0].set_title('Original Image')
- axs[0, 0].axis('off')
- # 原始图像的直方图
- axs[0, 1].hist(img_to_show.ravel(), bins=256, range=[0, 256])
- axs[0, 1].set_title('Histogram')
- axs[0, 1].axis('off')
-
- # 参考图像
- axs[1, 0].imshow(imgref_to_show, cmap='gray')
- axs[1, 0].set_title('Reference Image')
- axs[1, 0].axis('off')
- # 参考图像的直方图
- axs[1, 1].hist(imgref_to_show.ravel(), bins=256, range=[0, 256])
- axs[1, 1].set_title('Histogram')
- axs[1, 1].axis('off')
-
- # 匹配后的图像
- axs[2, 0].imshow(imgmatched_to_show, cmap='gray')
- axs[2, 0].set_title('Matched Image')
- axs[2, 0].axis('off')
- # 匹配后图像的直方图
- axs[2, 1].hist(imgmatched_to_show.ravel(), bins=256, range=[0, 256])
- axs[2, 1].set_title('Histogram')
- axs[2, 1].axis('off')
-
- plt.tight_layout()
- plt.show()

imgmatched = exposure.match_histograms(img, imgref)
此处为直方图匹配代码,调用了
scikit-image
库中的exposure
模块的match_histograms
函数
本节内容是该章节最后一小节,内容较少,所以又水了一节。
注,本人为在校学生,博客是边学边写的,主要是为了巩固知识,如有错误请积极指正。
“本文章中所使用的圣灵谱尼图片来源于网络,版权归属原作者所有。若您认为本文章/作品的使用侵犯了您的权益,请及时与我联系,我将尽快核实并删除相关内容。
本文的内容主要基于我对张运楚教授编著的《数字图像处理》一书的学习和理解。这本书深入浅出地介绍了数字图像处理的基本理论以及经典算法等,并且提供了丰富的示例代码和实际用例,极大地帮助了我学习图像处理知识。在此,我推荐大家阅读这本书,更加深入的学习有关图像处理的知识。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。