![](/img/trans.png)
[英]How do convert a full color image into just three color image (red, blue, green) using python?
[英]How to find Blue, Green, Red color of detected shapes
import cv2
import numpy as np
img = cv2.imread('img.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(gray,127,255,1)
contours,h = cv2.findContours(thresh,1,2)
for cnt in contours:
approx = cv2.approxPolyDP(cnt,0.01*cv2.arcLength(cnt,True),True)
if len(approx)==3:
print('Triangle')
elif len(approx)==4:
print('Sq')
elif len(approx)==5:
print('Pen')
elif len(approx) ==6:
print('Hex')
else:
print('Cir')
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
**我们如何仅在 BRG 颜色中找到检测到的形状的颜色。此代码能够找到形状,但我不知道检测此检测到的形状的颜色。 **
某种颜色有一定的RGB值。 您可以在某些网站上上传图像,它会为您提供所需颜色的确切 RGB 值。
您可以编写条件,定义从网站获得的颜色的某个范围,如果图像中的颜色在您定义的范围内,则它是您的颜色。
这是 Python/OpenCV 中的一种方式。 鉴于您知道轮廓或多边形,您可以为给定的轮廓创建遮罩。 然后使用遮罩找出图像中所有与遮罩白色像素对应的像素。 得到这些像素的平均值。
输入:
这里为了简单起见,我只是简单地对绿色的灰度版本进行阈值制作蒙版。
import cv2
import numpy as np
# Read image
img = cv2.imread('rgb.png')
# convert to gray
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Define graylevel lower and uppper limits for green
lower = 145
upper = 155
# Create mask
mask = cv2.inRange(gray, lower, upper)
# get mean color
region = img[np.where(mask == 255)]
mean = np.mean(region, axis=0)
print(mean)
# save results
cv2.imwrite('rgb_gray.png', gray)
cv2.imwrite('rgb_mask.png', mask)
cv2.imshow('gray', gray)
cv2.imshow('mask', mask)
cv2.waitKey(0)
cv2.destroyAllWindows()
灰色图像:
面具:
平均颜色:
[ 0. 255. 0.]
正如预期的那样是绿色的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.