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

查看:24
本文介绍了如何在 Python-OpenCV 中使用 `cv2.inRange` 检测两种不同的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何定义两种不同颜色的下"和上"范围,例如红色和蓝色(因为红色和蓝色在 HSV 颜色中并不相邻)

这个属于红色:

lower_red = np.array([160,20,70])upper_red = np.array([190,255,255])

而这个属于蓝色:

lower_blue = np.array([101,50,38])upper_blue = np.array([110,255,255])

我尝试使用 if 条件组合它们或创建它们自己的函数但不起作用,你们能告诉我解决方案吗?

P/s:Python 中的 OpenCV

解决方案

当你得到两个 color 的掩码,然后使用 cv2.bitwise_or 得到最终的掩码.

导入 cv2## 读img = cv2.imread("向日葵.jpg")##转换为hsvhsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)## 绿色面具 (36,0,0) ~ (70, 255,255)mask1 = cv2.inRange(hsv, (36, 0, 0), (70, 255,255))## 面具 o 黄色 (15,0,0) ~ (36, 255, 255)mask2 = cv2.inRange(hsv, (15,0,0), (36, 255, 255))##最终蒙版和蒙版掩码 = cv2.bitwise_or(mask1, mask2)目标 = cv2.bitwise_and(img,img, mask=mask)cv2.imwrite("target.png", 目标)

<小时>

来源:

找到绿色和黄色(范围不是那么准确):

<小时>

顺便说一句,为了获得更准确的范围,这是我的相关答案中的参考地图:

How can I define "lower" and "upper" range of two different color, such as red and blue (because red and blue are not next to each other in the HSV color)

This one belongs to red:

lower_red = np.array([160,20,70])
upper_red = np.array([190,255,255])

and this one belongs to blue:

lower_blue = np.array([101,50,38])
upper_blue = np.array([110,255,255])

I tried to combine them using if condition or make their own function but not work, can you guys show me the solution?

P/s: OpenCV in Python

解决方案

As you get two masks of colors, then use cv2.bitwise_or to get the final mask.

import cv2

## Read
img = cv2.imread("sunflower.jpg")

## convert to hsv
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

## mask of green (36,0,0) ~ (70, 255,255)
mask1 = cv2.inRange(hsv, (36, 0, 0), (70, 255,255))

## mask o yellow (15,0,0) ~ (36, 255, 255)
mask2 = cv2.inRange(hsv, (15,0,0), (36, 255, 255))

## final mask and masked
mask = cv2.bitwise_or(mask1, mask2)
target = cv2.bitwise_and(img,img, mask=mask)

cv2.imwrite("target.png", target)


Source:

Find green and yellow(the range is not that accurate):


BTW, to get more accurate range, here is a refer map in my related answer:

How to define a threshold value to detect only green colour objects in an image :Opencv

这篇关于如何在 Python-OpenCV 中使用 `cv2.inRange` 检测两种不同的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆