0.什么是直方图
通过直方图你可以对整幅图像的灰度分布有一个整体的了解。直方图的x 轴是灰度值(0 到255),y 轴是图片中具有同一个灰度值的点的数目。
统计直方图的几个重要参数:
BINS:
- 直方图显示了每个灰度值对应的像素数。如果像素值为0到255,你就需要256 个数来显示上面的直方图。但是,如果你不需要知道每一个像素值的像素点数目的,而只希望知道两个像素值之间的像素点数目怎么办呢?举例来说,我们想知道像素值在0 到15 之间的像素点的数目,接着是16 到31,…,240 到255。我们只需要16 个值来绘制直方图。
- 那到底怎么做呢?你只需要把原来的256 个值等分成16 小组,取每组的总和。而这里的每一个小组就被成为BIN。第一个例子中有256 个BIN,第二个例子中有16 个BIN。在OpenCV 的文档中用
histSize
表示BINS。
DIMS:
- 表示我们收集数据的参数数目。在本例中,我们对收集到的数据只考虑一件事:灰度值。所以这里就是1。
RANGE:
- 就是要统计的灰度值范围,一般来说为[0,256],也就是说所有的灰度值。
1.整幅图像的直方图
代码速记:
- plt.hist()
- cv2.calcHist()
- np.histogram()
- np.bincount()
参数解释:
plt.hist(raw_gray.ravel(),256,[0,256])#1:原图像展成一维数组。 2:bins。3.range
cv2.calcHist([raw_color],[i],None,[256],[0,256])#1:原图像。2:图像通道索引。3:mask。4:bins。5:range
np.histogram(raw_gray.ravel(), 256, [0, 256])#1:原图像展成一维数组。 2:bins。3.range
np.bincount(raw_gray.ravel(), minlength=256)#1:原图像展成一维数组。 2:bins的最小值
实战:
def accu_paint(self):
raw_gray=cv2.imread(self.infile,0)
raw_color=cv2.imread(self.infile)
#【1】plot统计单通道直方图,用plot绘制
plt.hist(raw_gray.ravel(),256,[0,256])
plt.show()
#【2】cv统计三通道直方图,用plot绘制
color=('b','g','r')
for i,col in enumerate(color):
histr=cv2.calcHist([raw_color],[i],None,[256],[0,256])
plt.plot(histr,color=col)
plt.xlim([0,256])
plt.show()
#【3】numpy方法统计直方图,用plot绘制
np_hist1, bins = np.histogram(raw_gray.ravel(), 256, [0, 256]) # cv函数比此函数快40倍
# img.ravel()把图像转为一维数组
np_hist2 = np.bincount(raw_gray.ravel(), minlength=256) # 比histogram快十倍
titles=['histogram','bincount']
hists=[np_hist1,np_hist2]
for i in range(2):
plt.subplot(1,2,i+1),plt.plot(hists[i])
plt.title(titles[i])
plt.show()
plot统计单通道直方图,用plot绘制:
cv统计三通道直方图,用plot绘制:
numpy方法统计直方图,用plot绘制:
2.部分图像的直方图(使用mask)
代码速记:
- mask=np.zero()
- mask[:,:]=255
- cv2.calcHist(,mask,)
实战:
def mask_hist(self):
raw_gray=cv2.imread(self.infile,0)
mask=np.zeros(raw_gray.shape[:2],np.uint8)#mask为全黑的图像
mask[100:500,100:600]=255#mask的该区域变白
masked_img=cv2.bitwise_and(raw_gray,raw_gray,mask=mask)
hist_full=cv2.calcHist([raw_gray],[0],None,[256],[0,256])
hist_mask=cv2.calcHist([raw_gray],[0],mask,[256],[0,256])
titles = ['raw_gray', 'mask','masked_img']
imgs = [raw_gray, mask,masked_img]
for i in range(3):
plt.subplot(2, 2, i + 1), plt.imshow(imgs[i],'gray')
plt.title(titles[i])
plt.xticks([]), plt.yticks([])
plt.subplot(2,2,4),plt.plot(hist_full),plt.plot(hist_mask)
plt.xlim([0,256])
plt.show()
来源:CSDN
作者:SuperWiwi
链接:https://blog.csdn.net/qq_36622009/article/details/104571752