python中opencv中inrange用法_如何在Python-OpenCV中使用`cv2.inRange`检测两种不同的颜色?...

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:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值