How to calculate histogram on opencv without taking into consideration all black pixels on the image (due to a mask)

Viewed 479

I am trying to get HSV, LAB histogram of an image in order to extract certain features, but I actually can't get any accurate results from my features if the histogram is taking into consideration the black pixles of the areas I have masked, how can I overcome this problem please, any help is much appreciated.

I am working with python.

Here is an example image, and here is the code I am trying to use.enter image description here

hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
hue = hsv_image[:,:,0].astype(float)
sat = hsv_image[:,:,1].astype(float)
val = hsv_image[:,:,2].astype(float)
hue[hue == 0] = np.nan
histr_lab = cv2.calcHist([hsv_image], [0], None, [255], [0, 255])
histr_lab1 = cv2.calcHist([hsv], [1], None, [255], [0, 255])
histr_lab2 = cv2.calcHist([hsv], [2], None, [255], [0, 255])
1 Answers

Try to filter out the black pixels (val = 0) before you do the histogram by applying:

hue = hue[numpy.where(val > 0,True,False)]
sat = sat[numpy.where(val > 0,True,False)]
val = val[numpy.where(val > 0,True,False)]

in your case when calculating the histogram try:

cv2.calcHist(hsv_image[np.where(val > 0,True, False)], [1],None, [255], [0, 255])
Related