OpenCV--直方图绘制以及直方图均衡化

OpenCV–直方图绘制以及直方图均衡化

一、直方图均衡化

函数:

hist = cv.calcHist( images, channels, mask, histSize, ranges[, hist[, accumulate]] )

  • images: 原图像图像格式为 uint8 或 float32,当传入函数时应用中括号 [] 括来例如[img];
  • channels: 同样用中括号括起来,告诉函数统计图像中的哪个颜色通道的直方图。如果输入图像是灰度图它的值就是 [0],如果是彩色图像传入的参数可以是 [0][1][2] 它们分别对应着 BGR;
  • mask: 掩模图像,统计整幅图像的直方图就把它设为 None。但是如果你想统计图像某一部分的直方图时,就需要使用它;
  • histSize:BIN 的数目,也应用中括号括来;
  • ranges: 像素值范围常为 [0,256] ;
  • hist:输出矩阵,表示整张图中bin的灰度图的个数。

代码示例:

import numpy as np 
import cv2 as cv
import matplotlib.pyplot as plt

#封装图像显示函数
def cv_show(name, img):
    cv.imshow(name, img)
    cv.waitKey(0)
    cv.destroyAllWindows()

#统计直方图
img_gray = cv.imread('./img/cat.jpg',0) 
hist = cv.calcHist([img_gray],[0],None,[256],[0,256])
hist.shape

(256, 1)

plt.hist(img_gray.ravel(), 256)
plt.show()

在这里插入图片描述

#多通道图像绘制
img = cv.imread("./img/cat.jpg")
color = ("b", "g", "r")

for i, color in enumerate(color):
    hist = cv.calcHist([img], [i], None, [256], [0, 256])
    plt.plot(hist, color = color)
    plt.xlim([0, 256])

在这里插入图片描述

mask操作

#创建一个mask
mask = np.zeros(img.shape[:2], np.uint8)
print(mask.shape)
mask[100:300, 100:400] = 255
cv_show("mask", mask)

(414, 500)

#用掩码对图像进行截取
img_masked = cv.bitwise_and(img_gray, img_gray, mask = mask )   #与操作

hist_full = cv.calcHist([img], [0], None, [256], [0, 256])
hist_mask = cv.calcHist([img], [0], mask, [256], [0, 256])

plt.subplot(221), plt.imshow(img_gray, "gray")
plt.subplot(222), plt.imshow(mask, "gray")
plt.subplot(223), plt.imshow(img_masked, "gray")
plt.subplot(224), plt.plot(hist_full), plt.plot(hist_mask)
plt.xlim([0, 256])
plt.show()

在这里插入图片描述

二、直方图均衡化(HE)

函数:

dst = cv.equalizeHist( src[, dst] )

  • src:8位单通道图像。

原理参考:https://www.cnblogs.com/tianyalu/p/5687782.html
本质上就是算出每个灰度级上的概率(依次累加之前的概率),在乘以灰度级分布范围(例如灰度分布为(0-255),则范围为255-0)

代码示例:

img = cv.imread("./img/clahe.jpg", 0)

plt.hist(img.ravel(), 256)
plt.show()

在这里插入图片描述

#均值化 
#dst = cv.equalizeHist( src[, dst] )
dst = cv.equalizeHist(img)
plt.hist(dst.ravel(), 256)
plt.show()

在这里插入图片描述

三、自适应直方图均衡化(CLAHE)

原理参考博客:https://blog.csdn.net/lwx309025167/article/details/103770834

函数:

retval = cv.createCLAHE( [, clipLimit[, tileGridSize]] )

  • clipLimit:限制对比度阈值;
  • tileGridSize:直方图均衡化的网格大小。

代码示例:

#自适应直方图均衡化
#retval = cv.createCLAHE([, clipLimit[, tileGridSize]])
clahe = cv.createCLAHE(clipLimit = 2.0, tileGridSize = (8,8))
res_clahe = clahe.apply(img) #img需要均衡化的图片

res = np.hstack((img, res_clahe))
cv_show("res", res)
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值