本文共 1250 字,大约阅读时间需要 4 分钟。
如何进行图像直方图均衡化处理以提升图像质量
在图像处理领域,直方图均衡化是提升图像质量的重要技术之一。通过对图像的直方图进行规范化处理,可以有效地提高图像的对比度,增强视觉效果。本文将详细介绍如何使用Python进行图像直方图均衡化,并分析其效果。
首先,我们需要准备输入图像。代码如下:
import cv2import numpy as npfrom matplotlib import pyplot as plt# 读取图像img = cv2.imread('fish.jpg', 0) 接下来,我们计算原始图像的直方图。使用NumPy的np.histogram函数可以实现这一点。代码如下:
# 计算直方图hist, bins = np.histogram(img.flatten(), 256, [0, 256])# 计算累积分布函数(CDF)cdf = hist.cumsum()cdf_normalized = (cdf * hist.max()) / cdf.max()
通过计算并标准化累积分布函数(CDF),我们可以更直观地观察图像的直方图特性。plt.figure()创建一个新-figure窗口,plt.plot(cdf_normalized, 'b')绘制标准化的CDF曲线。
plt.figure()plt.plot(cdf_normalized, color='b')plt.hist(img.flatten(), 256, [0, 256], color='r')plt.xlim([0, 256])plt.legend(('CDF', 'histogram'), loc='upper left') 运行上述代码后,可以看到原始图像和其直方图的对比。接下来,我们对图像进行均衡化处理。具体步骤如下:
# 均衡化处理cdf_m = np.ma.masked_equal(cdf, 0)cdf_m = (cdf_m - cdf_m.min()) * 255 / (cdf_m.max() - cdf_m.min())cdf = np.ma.filled(cdf_m, 0).astype('uint8')# 应用均衡化图像img2 = cdf[img]# 显示结果plt.figure()plt.subplot(121)plt.imshow(img, 'gray')plt.subplot(122)plt.imshow(img2, 'gray') 通过上述处理后,均衡化后的图像(img2)应显著提升图像质量。为了进一步验证效果,我们可以计算并比较原始图像和处理后图像的直方图。
# 处理后直方图hist, bins = np.histogram(img2.flatten(), 256, [0, 256])# 查看处理后图像的直方图特性
通过比较直方图图像,可以更直观地观察均衡化处理对图像质量的提升效果。本文介绍的直方图均衡化方法简单有效,是图像处理的基础步骤之一。
转载地址:http://rwfqz.baihongyu.com/