内容:
- 计算直方图
- 画出直方图
- 学习几个函数cv.calcHist(), np.histogram(), etc
理论
直方图即使统计各个像素值频数的统计图。具体可以百度。
名词解析:
- BINS: 可以认为这是每个段的像素值的个数,比如设置16,则分别统计的是 0 to 15, then 16 to 31, …, 240 to 255.频数。默认是1。
- DIMS:表示的是数据的维度。默认为1。
- RANGE:表示的是要统计的强度值的范围。
其他函数
- ravel()表示将图片摊平,变成一维的
1.计算直方图
opencv中如何计算直方图
关于cv.calcHist()参数的介绍——
cv.calcHist(images, channels, mask, histSize, ranges[, hist[, accumulate]])
- images: 源图像(uint8 or float32),放入格式为“[img]”
- channels: 要统计直方图的通道,比如灰度图可以"[0]”,而RGB图形可以“[0]”,“[1]",“[2]",分别代表蓝、绿、红通道。
- mask: 掩膜图片。如果要感兴趣的范围需要用这个去限制,默认是None。
- histSize:表示BIN的数量,如果全部要计算那就是“[256]”.
- ranges:默认[0,256]
example
img = cv.imread('home.jpg',0)
hist = cv.calcHist([img],[0],None,[256],[0,256])
numpy中如何计算直方图
hist,bins = np.histogram(img.ravel(),256,[0,256])
2. 绘制直方图
一般来说有两种方法:
- 简单:Matplotlib
- 复杂:OpenCV
1)使用Matplotlib
2
import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
img = cv.imread('home.jpg',0)
plt.hist(img.ravel(),256,[0,256]); plt.show()
2
import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
img = cv.imread('home.jpg')
color = ('b','g','r')
for i,col in enumerate(color):
histr = cv.calcHist([img],[i],None,[256],[0,256])
plt.plot(histr,color = col)
plt.xlim([0,256])
plt.show()
快速构建掩膜图像
# create a mask
mask = np.zeros(img.shape[:2], np.uint8)
mask[100:300, 100:400] = 255
masked_img = cv.bitwise_and(img,img,mask = mask)
plt.subplot(221), plt.imshow(img[:,:,0],'gray')
plt.subplot(222), plt.imshow(mask[:,:],'gray')
plt.subplot(223), plt.imshow(masked_img[:,:,0],'gray'
参考链接:
https://docs.opencv.org/trunk/d1/db7/tutorial_py_histogram_begins.html