python opencv rgb转hsv,python-opencv-将像素从bgr转换为hsv

img = cv2.imread('example.jpg')

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)

# join my masks

mask = mask0 + mask1

height = mask.shape[0]

width = mask.shape[1]

# iterate over every pixel

for i in range(height):

for j in range(width):

px = mask[i,j]

print px

# check if pixel is white or black

if (px[2] >= 0 and px[2] <= 40):

In the above example 'px' is a pixel in BGR. I need to convert the value to HSV because I want to check if the pixel is in a certain color range.

I already tried

colorsys.rgb_to_hsv(px[2], px[1], px[0})

which evokes the error: invalid index to scalar variable

Thanks!

解决方案

From the docs:

# Convert BGR to HSV

hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

# define range of blue color in HSV

lower_blue = np.array([110,50,50])

upper_blue = np.array([130,255,255])

# Threshold the HSV image to get only blue colors

mask = cv2.inRange(hsv, lower_blue, upper_blue)

You can just convert your whole img to hsv using the built in method:

hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值