Know a single RGB color in an image, not a range with OpenCV

Viewed 187

I'm working with ´OpenCV´ and I want to show a single colour in an image. Now I made this,

img = cv2.imread('im02.jpg')

L1 = np.array([255,0,102])
U1 = np.array([255,0,102])

m1 = cv2.inRange(img, L1, U1)

r1 = cv2.bitwise_and(img, img, mask=m1)

#print(r1.any()) #know if all the image is black

cv2.imshow("WM", np.hstack([img, r1]))

This works ok but it works when you need a range of colour tonalities. But in my case, I want to know the exact value of RGB, by the moment I'm writing the same value in the low and upper range but I'm trying to do it better, how can I do this without range?

Thank you very much.

1 Answers

I think I understand your question. Try this:

#!/usr/local/bin/python3
import numpy as np
import cv2

# Open image into numpy array
im=cv2.imread('start.png')

# Sought colour
sought = [255,0,102]

# Find all pixels where the 3 RGB values match the sought colour
matches = np.all(im==sought, axis=2)

# Make empty (black) output array same size as input image
result = np.zeros_like(im)

# Make anything matching our sought colour into magenta
result[matches] = [255,0,255]

# Or maybe you want to color the non-matching pixels yellow
result[~matches] = [0,255,255]

# Save result
cv2.imwrite("result.png",result) 

start.png looks like this - your colour is between green and blue:

enter image description here

result.png looks like this:

enter image description here

Related