简体   繁体   English

检测像素是否为红色

[英]Detect whether a pixel is red or not

We can define the range of red color in HSV as below. 我们可以如下定义HSV中红色的范围。 I want to detect that whether a certain pixel is red or not? 我想检测某个像素是否为红色? How can I do that in Python? 如何在Python中做到这一点? I spend whole day, but unable to find solution. 我花了一整天,但找不到解决方案。 Please resolve my problem. 请解决我的问题。 I'm very new to Python. 我是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")

You are almost right. 你几乎是对的。 You can merge the masks of lower RED and higher RED together to a single mask. 您可以将较低RED和较高RED的蒙版合并为一个蒙版。


For this ColorChecker.png : 为此ColorChecker.png

在此处输入图片说明

My Steps to find the RED: 我找到红色的步骤:

  1. Read the image and convert to hsv . 读取图像并转换为hsv

  2. I choose the red ranges ( lower 0~5, upper 175~180 ) using this colormap: 我使用此颜色图选择红色范围( lower 0~5, upper 175~180 175〜180):

在此处输入图片说明

  1. Then merge the masks, you can judge whether the pixel is red or not by the mask. 然后合并蒙版,可以通过蒙版判断像素是否为红色。 Or "crop" the region(s) for visualization: 或“裁剪”区域以进行可视化:

在此处输入图片说明


#!/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()

  1. Choosing the correct upper and lower HSV boundaries for color detection with`cv::inRange` (OpenCV) 选择正确的HSV上下边界以使用`cv :: inRange`(OpenCV)进行颜色检测

  2. How to detect two different colors using `cv2.inRange` in Python-OpenCV? 如何在Python-OpenCV中使用`cv2.inRange`检测两种不同的颜色?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM