本文介绍了检测像素是否为红色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们可以如下定义HSV中红色的范围.我想检测某个像素是否为红色?如何在Python中做到这一点?我花了一整天,但找不到解决方案.请解决我的问题.我是Python的新手.我正在使用的代码是:
We can define the range of red color in HSV as below. I want to detect that whether a certain pixel is red or not? How can I do that in Python? I spend whole day, but unable to find solution. Please resolve my problem. I'm very new to Python. Code that I'm using is:
img=cv2.imread("img.png")
img_hsv=cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# lower mask (0-10)
lower_red = np.array([0,50,50])
upper_red = np.array([10,255,255])
mask0 = cv2.inRange(img_hsv, lower_red, upper_red)
# upper mask (170-180)
lower_red = np.array([170,50,50])
upper_red = np.array([180,255,255])
mask1 = cv2.inRange(img_hsv, lower_red, upper_red)
image_height,image_width,_=img.shape
for i in range(image_height):
for j in range(image_width):
if img_hsv[i][j][1]>=lower_red and img_hsv[i][j][1]<=upper_red:
print("Found red")
推荐答案
您几乎是正确的.您可以将较低RED和较高RED的蒙版合并到一个蒙版中.
You are almost right. You can merge the masks of lower RED and higher RED together to a single mask.
为此ColorChecker.png
:
找到红色的步骤:
-
读取图像并转换为
hsv
.
我使用此色图选择红色范围(lower 0~5, upper 175~180
):
I choose the red ranges (lower 0~5, upper 175~180
) using this colormap:
- 然后合并遮罩,您可以通过遮罩判断像素是否为红色.或裁剪"区域以进行可视化:
#!/usr/bin/python3
# 2018.07.08 10:39:15 CST
# 2018.07.08 11:09:44 CST
import cv2
import numpy as np
## Read and merge
img = cv2.imread("ColorChecker.png")
img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
## Gen lower mask (0-5) and upper mask (175-180) of RED
mask1 = cv2.inRange(img_hsv, (0,50,20), (5,255,255))
mask2 = cv2.inRange(img_hsv, (175,50,20), (180,255,255))
## Merge the mask and crop the red regions
mask = cv2.bitwise_or(mask1, mask2 )
croped = cv2.bitwise_and(img, img, mask=mask)
## Display
cv2.imshow("mask", mask)
cv2.imshow("croped", croped)
cv2.waitKey()
这篇关于检测像素是否为红色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!