How do you lightness thresh hold with HSL on OpenCV?

前端 未结 1 1809
栀梦
栀梦 2021-02-06 20:00

There is a project that im working on which required the color white detection, after some research i decided to use covert RGB image to HSL image and thresh hold the lightness

相关标签:
1条回答
  • 2021-02-06 20:17

    You can do it with 4 easy steps:

    Convert HLS

    img = cv2.imread("HLS.png")
    imgHLS = cv2.cvtColor(img, cv2.COLOR_BGR2HLS)
    

    Get the L channel

    Lchannel = imgHLS[:,:,1]
    

    Create the mask

    #change 250 to lower numbers to include more values as "white"
    mask = cv2.inRange(Lchannel, 250, 255)
    

    Apply Mask to original image

    res = cv2.bitwise_and(img,img, mask= mask)
    

    This also depends on what is white for you, and you may change the values :) I used inRange in the L channel but you can save one step and do

    mask = cv2.inRange(imgHLS, np.array([0,250,0]), np.array([255,255,255]))
    

    instead of the lines:

    Lchannel = imgHLS[:,:,1]
    mask = cv2.inRange(Lchannel, 250, 255)
    

    It is shorter, but I did it the other way first to make it more explicit and to show what I was doing.

    Image:

    Result:

    The result looks almost as the mask (almost binary), but depending on your lowerbound (I chose 250) you may get even some almost white colors.

    0 讨论(0)
提交回复
热议问题