Ask Your Question
0

calcHist on BGR in python

asked 2014-05-22 16:13:36 -0600

Hansg91 gravatar image

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 flag offensive close merge delete

1 answer

Sort by » oldest newest most voted
1

answered 2014-05-23 00:37:54 -0600

Abid Rahman K gravatar image

updated 2014-05-23 00:46:43 -0600

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],[0],None,[256],[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],[0],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],[0],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,[256],[0,256])
    plt.plot(histr,color = col)
    plt.xlim([0,256])
plt.show()
edit flag offensive delete link more

Comments

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

Hansg91 gravatar imageHansg91 ( 2014-05-23 03:27:17 -0600 )edit

Question Tools

Stats

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

Seen: 3,364 times

Last updated: May 23 '14