Search code examples
pythonopencvpixelhsv

Trying to convert HSV image to Black and white [opencv]


I have a skin detection code that works nicely to separate out skin pixels from the background of a HSV image.

enter image description here

Now, I want to convert the image on right to Black and white. My logic is to check all non-black pixels and change their Saturation value to 0 and Intensity value to 255.

So essentially, pixels would be [0-255,0,255]. I am using python with opencv.

h,b = skin.shape[:2]    

    for i in xrange(h):
        for j in xrange(b):
            # check if it is a non-black pixel
            if skin[i][j][2]>0:
                # set non-black pixel intensity to full
                skin[i][j][2]=255
                # set saturation zero
                skin[i][j][1]=0

But it produces this output -

enter image description here

How can I convert those pink pixels to white??


Solution

  • You are basically looking for Thresholding, basically the concept is selecting a threshold value and any pixel value (grayscale) greater than threshold is set to be white and black otherwise. OpenCV has some beautiful inbuilt methods to do the same but it is really simple code:

    skin = #Initialize this variable with the image produced after separating the skin pixels from the image.
    
    bw_image = cv2.cvtColor(skin, cv2.HSV2GRAY)
    
    new_image = bw_image[:]
    
    threshold = 1 
     #This value is set to 1 because We want to separate out the pixel values which are purely BLACK whose grayscale value is constant (0) 
    

    Now we simply iterate over the image and substitute the values accordingly.

    h,b = skin.shape[:2]    
    
    for i in xrange(h):
        for j in xrange(b):
            if bw_image[i][j] > threshold:
                new_image[i][j] = 255 #Setting the skin tone to be White
            else:
                new_image[i][j] = 0 #else setting it to zero.