Search code examples
pythonopencvnumpyhistogramhue

OpenCV- ignoring pixels when generating a hue histogram


I'm using the calcHist() function from OpenCV in Python to generate Hue histograms for HSV images However I want the function to be able to ignore pixels with either ~0% or ~100% lightness (black and white respectively) or ~0% saturation (grey). Any ideas? Thanks in advance.


Solution

  • The calcHist function accepts a mask parameter. You can create a mask with this properties that you mentioned and pass it to the function. I suggest you to create something that analyse the pixels once... but an easy way to do it would be:

    h,s,v = cv2.split(img)
    mask = (v == 0) + (v == 100) + (s == 0)
    mask = numpy.logical_not(mask)
    

    Then you can use your mask matrix in the function. It will ignore the pixels that have false value. I have used this in c++, so I am not sure if false value will work or if you need integers as in c++ version... in the worst case just add another extra line mask *= 1 and you will be done.

    Hope this helps.