Color thresholding an HLS jpeg image

Question:

I am trying to color threshold a jpeg image so that I can keep the lane lines and hopefully get rid of the rest of the world.
I am reading the image using cv2 as follows:

test_image = cv2.imread(myimage)
#convert to RGB space from BGR
test_image = cv2.cvtColor(test_image, cv2.COLOR_BGR2RGB)

Then, I convert the test_image to HLS color space, to retain l channel as below:

def get_l_channel_hls(img):
    # Convert to HLS color space and separate the l channel
    hls = cv2.cvtColor(img, cv2.COLOR_RGB2HLS).astype(np.float)
    l_channel = hls[:,:,1]
    return l_channel

Then I apply some thresholds to this l channel and replace the pixel values by 0 or 1, so that I can retain only the pixels I want. (I will later multiply these values by 255, to make the retained pixels appear white)

def get_color_channel_thresholded_binary(channel, thresh=(0,255):
    # Threshold color channel
    print("min color threshold: {}".format(thresh[0]))
    print("max color threshold: {}".format(thresh[1])) 
    binary = np.zeros_like(channel)
    binary[(channel > thresh[0]) | (channel <= thresh[1])] = 1
    return binary

Then, I take this binary map and replace the retained pixels with 255

def get_overall_combined_binary(binary1):
    grayscaled_binary = np.zeros_like(binary1)
    grayscaled_binary [(binary1 == 1)] = 255
    return grayscaled_binary

And I display this binary using matplotlib pyplot as below:

import matplotlib.pyplot as plt
#grayscaled_binary = # get the grayscaled binary using above APIs
imshow(grayscaled_binary, cmap='gray')

What I am observing here is rather strange. The image appears all black for ANY values for which thresh[1] < thresh[0]. i.e. maximum threshold is LESS than the minimum threshold. And I have no clue as to why this is happening.

I have reviewed the code a few times now and I don’t see any bugs in it. The only difference between the code I have pasted here vs the one I am using is that, I’m using IPython widgets in Jupyter notebook to interact.

I’d greatly appreciate any help or insight with this topic.
I’m also attaching two examples of what I am talking about.
Thanks in advance.Failure Scenario
enter image description here

Asked By: sdevikar

||

Answers:

The line

binary[(channel > thresh[0]) | (channel <= thresh[1])] = 1

sets all pixels to 1 if thresh[0] < thresh[1]. I suppose this is not what you want.

It’s not really clear what you really want instead. Assuming that those pixels which are within the two threshold values should be white, you’d use a logical and instead.

binary[(channel > thresh[0]) & (channel <= thresh[1])] = 1