一杯清酒邀明月
天下本无事,庸人扰之而烦耳。

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的灰度图的个数。

代码示例:

 1 import numpy as np 
 2 import cv2 as cv
 3 import matplotlib.pyplot as plt
 4 
 5 #封装图像显示函数
 6 def cv_show(name, img):
 7     cv.imshow(name, img)
 8     cv.waitKey(0)
 9     cv.destroyAllWindows()
10 
11 #统计直方图
12 img_gray = cv.imread('./img/cat.jpg',0) 
13 hist = cv.calcHist([img_gray],[0],None,[256],[0,256])
14 hist.shape
(256, 1)
1 plt.hist(img_gray.ravel(), 256)
2 plt.show()

1 #多通道图像绘制
2 img = cv.imread("./img/cat.jpg")
3 color = ("b", "g", "r")
4 
5 for i, color in enumerate(color):
6     hist = cv.calcHist([img], [i], None, [256], [0, 256])
7     plt.plot(hist, color = color)
8     plt.xlim([0, 256])

 mask操作

1 #创建一个mask
2 mask = np.zeros(img.shape[:2], np.uint8)
3 print(mask.shape)
4 mask[100:300, 100:400] = 255
5 cv_show("mask", mask)
(414, 500)
 1 #用掩码对图像进行截取
 2 img_masked = cv.bitwise_and(img_gray, img_gray, mask = mask )   #与操作
 3 
 4 hist_full = cv.calcHist([img], [0], None, [256], [0, 256])
 5 hist_mask = cv.calcHist([img], [0], mask, [256], [0, 256])
 6 
 7 plt.subplot(221), plt.imshow(img_gray, "gray")
 8 plt.subplot(222), plt.imshow(mask, "gray")
 9 plt.subplot(223), plt.imshow(img_masked, "gray")
10 plt.subplot(224), plt.plot(hist_full), plt.plot(hist_mask)
11 plt.xlim([0, 256])
12 plt.show()

二、直方图均衡化(HE)

函数:

dst = cv.equalizeHist( src[, dst] )
  • src:8位单通道图像。

本质上就是算出每个灰度级上的概率(依次累加之前的概率),在乘以灰度级分布范围(例如灰度分布为(0-255),则范围为255-0)

代码示例:

1 img = cv.imread("./img/clahe.jpg", 0)
2 
3 plt.hist(img.ravel(), 256)
4 plt.show()

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

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

函数:

retval = cv.createCLAHE( [, clipLimit[, tileGridSize]] )
  • clipLimit:限制对比度阈值;
  • tileGridSize:直方图均衡化的网格大小。

代码示例:

1 #自适应直方图均衡化
2 #retval = cv.createCLAHE([, clipLimit[, tileGridSize]])
3 clahe = cv.createCLAHE(clipLimit = 2.0, tileGridSize = (8,8))
4 res_clahe = clahe.apply(img) #img需要均衡化的图片
5 
6 res = np.hstack((img, res_clahe))
7 cv_show("res", res)

 

posted on 2021-08-25 10:40  一杯清酒邀明月  阅读(442)  评论(0编辑  收藏  举报