Ask Your Question

# calcHist on BGR in python

Hey,

I want to use the calcHist function in python on an BGR, but I get some unexpected results. The code I use to compute the histogram is as follows:

hist = cv2.calcHist([image], [0,1,2], (seg == 1).astype(np.uint8), [25,25,25], [0, 255, 0, 255, 0, 255])


However the result of hist is of shape (25, 25, 25). I was expecting to get (25,3), as in 25 bins per channel. What is this result I am getting? The opencv documentation simply states

hist – Output histogram, which is a dense or sparse dims -dimensional array.


But I don't quite understand what this means exactly.

Best regards, Hans

edit retag close merge delete

## 1 answer

Sort by » oldest newest most voted I will try to explain. I recommend you to read OpenCV-Python tutorials on histograms. I will give a short explanation below.

Case 1: finding histogram of a single channel, say histogram of intensity values

hist = cv2.calcHist([img],,None,,[0,256])


You get a simple histogram of 256 bins where each element denotes number of pixels with particular intensity in that image. (Good to calculate histogram of a grayscale image.)

Case 2: finding histogram of two channels, say B&G channels

hist = cv2.calcHist([img],,None,[256, 256],[0,256,0,256])


Now you get a 256x256 array, where each element corresponds to number of pixels with particular (B,G) values. For example, hist[50,100] denotes number of pixels who have B=50 and G=100. (Good to calculate Hue-Saturation histogram during backprojection.

Case 3: finding histogram of three channels, say BGR channels

hist = cv2.calcHist([img],,None,[256, 256],[0,256,0,256])


Extend the idea from case 2. Now you have 256x256x256 array (more like a CUBE). hist[50,100,150] denotes number of pixels who have the values B=50, G=100, R=150.

Case 4: How to find histogram of B,G,R channels separately?

Put a for loop for case 1.

color = ('b','g','r')
for i,col in enumerate(color):
histr = cv2.calcHist([img],[i],None,,[0,256])
plt.plot(histr,color = col)
plt.xlim([0,256])
plt.show()

more

## Comments

Aha I see, very clear answer. Thank you! I didn't realize the histogram was of combinations of the channels.

Official site

GitHub

Wiki

Documentation

## Stats

Asked: 2014-05-22 16:13:36 -0500

Seen: 2,004 times

Last updated: May 23 '14