Change all other colors in the image to black except ONE specified color in Python OpenCV/Numpy

Viewed 1233

I basically have a semantic segmentation mask and I would like to change all colors to black in the image except one color (the road - violet).

How do I do it in numpy or opencv?

enter image description here

Updated image This image has tiny corrupted pixels on it Changed the code to

import cv2

img = cv2.imread("image.png", cv2.COLOR_RGB2BGR)

 colors = [
  (100, 100, 150),
  (32, 11, 119),
  (70, 70, 70),
  (100, 60, 0),
  (142, 0, 0),
  (255, 255, 255)
]

# colors = np.array(colors)
# all other colors
mask = np.zeros(img.shape[:2], dtype=bool)

for color in colors:   
    mask |= (img == color).all(-1)

img[mask] = (255,255,255)

and the result is the following image with still the same minor corruption (or added colors (just peek at the top row pixels) that I want to remove) enter image description here

1 Answers

You can try:

# special color
colors = [ (100, 100, 150), (32, 11, 119), (70, 70, 70), (100, 60, 0), (255, 255, 255) ]


# all other colors
mask = np.zeros(img.shape[:2], dtype=bool)

for color in colors:   
    mask |= (img == color).all(-1)

img[~mask] = (255,255,255)

Output (shown by plt.imshow):

enter image description here

Related