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

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

问题描述

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

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)

这个属于红色:

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条件将它们结合起来,或者使它们自己起作用,但是不起作用,你们能告诉我解决方案吗?

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:Python中的OpenCV

P/s: OpenCV in Python

推荐答案

当您获得两个color的蒙版时,然后使用cv2.bitwise_or获得最终的蒙版.

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:

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

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