Search code examples
pythoncomputer-visionopencvgrayscaleimage-thresholding

Threshold an image using RBG


I would like to threshold an image, but instead of the output being black and white I would like it to be white and some other color. I was able to achieve this using a nested for-loop however this is slow and I was wondering if anyone knows any method of doing this efficiently using CV2 functionality.

img = cv2.imread("Naas.png", 1)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
threshold, thresh = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY)

# Changing black to green and converting from Grayscale to RGB

lis = []
for i in thresh:
    for j in i:
        if j == 0:
            lis.append((0, 255, 0))
        else:
            lis.append((255, 255, 255))
        
img = np.array(lis, dtype = "uint8")
img = img.reshape(thresh.shape[0], thresh_inv.shape[], 3) 

This loop changes any black pixels to green in the thresholded image.


Solution

  • So the green channel is always 255 and the red and blue channels are just the threshold values?

    So you are looking at something like this

    import numpy as np 
    img = cv2.imread("Naas.png", 1)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    threshold, thresh = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY)
    img_result=np.ones(img.shape)*255 #set all to 255
    img_result[:,:,0]=thresh[:,:] #set red channel to threshold
    img_result[:,:,2]=thresh[:,:] #set blue channel to threshold