OpenCV+Python 直方图
2018-11-06 本文已影响81人
音符纸飞机
一维直方图
def calcHist(images, channels, mask, histSize, ranges, hist=None, accumulate=None):
"""
images : it is the source image of type uint8 or float32. it should be given in square brackets, ie, “[img]”.
channels : it is also given in square brackets. It the index of channel for which we calculate histogram.
For example, if input is grayscale image, its value is [0]. For color image, you can pass [0],
[1] or [2] to calculate histogram of blue,green or red channel respectively.
mask : mask image. To find histogram of full image, it is given as “None”. But if you want to find histogram
of particular region of image, you have to create a mask image for that and give it as mask.
histSize : this represents our BIN count. Need to be given in square brackets. For full scale, we pass [256]. 传入数组是因为要确定每个维度上的bin数量
ranges : this is our RANGE. Normally, it is [0,256]. 用来进行统计的范围。比如统计[0, 20] 就是对0,20范围的值进行统计。
uniform:每一个竖条的宽度是否相等。
accumulate:是否累加。如果为true,在下次计算的时候不会首先清空hist。
"""
img = cv2.imread('home.jpg',0)
hist = cv2.calcHist([img],[0],None,[256],[0,256])
二维直方图
It is quite simple and calculated using the same function, cv2.calcHist(). For color histograms, we need to convert the image from BGR to HSV. (Remember, for 1D histogram, we converted from BGR to Grayscale). For 2D histograms, its parameters will be modified as follows:
channels = [0,1] because we need to process both H and S plane.
bins = [180,256] 180 for H plane and 256 for S plane.
range = [0,180,0,256] Hue value lies between 0 and 180 & Saturation lies between 0 and 256.
import cv2
img = cv2.imread('home.jpg')
hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
hist = cv2.calcHist([hsv], [0, 1], None, [180, 256], [0, 180, 0, 256])
直方图反向投影
Indexing via color histograms - Computer Vision, 1990
OpenCV官方文档
原理博文
应用于图像分割和物体检测。
输出图像与输入图像大小相同,每个像素的值等于原图像中该像素属于被测对象的概率,也就是说,越明亮的地方越有可能是待测物体。
def calcBackProject(images, channels, hist, ranges, scale, dst=None):
"""
Its parameters are almost same as the cv2.calcHist() function.
One of its parameter is histogram which is histogram of the object and we have to find it
"""
图二是直方图方向投影的结果