使用OpenCV识别图像中的单个RGB颜色,而不是一个范围

3

我正在使用OpenCV,并希望在图像中显示单一颜色。目前,我实现了如下代码:

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]))

这对于需要一系列颜色调性的情况下能够正常运作。但是在我的情况下,我想要知道RGB的确切值,在此刻,我正在将相同的值写入低和高范围,但我想更好地完成它,如何在没有范围的情况下实现呢?

非常感谢。


红色 140,50,0 和 80,255,255 绿色 40,50,50 和 80,255,255 蓝色 100,50,50 和 140,255,255 - Shubham Kumar Gupta
我不想知道颜色的范围,我想在我的图像上找到一个精确的RGB值。但还是谢谢! - mmr689
1个回答

2
我想我理解了你的问题。试试这个:
#!/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 看起来像这样 - 你的颜色在绿色和蓝色之间:

enter image description here

result.png 看起来像这样:

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接