首页 > 解决方案 > Reading lower and upper threshold arrays when used with inRange

问题描述

I was reading on how to filter colors using OpenCV and came across the following snippet.

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

lower_red = np.array([0,160,50])
upper_red = np.array([255,255,180])


mask = cv2.inRange(hsv, lower_red, upper_red)
res = cv2.bitwise_and(img,img, mask= mask)

What does each value in lower_red mean? Does it denote lower and upper limits of H,S,V sequentially? Should it be read as minimum value of H as 0 and maximum value of H as 255?

I want to filter red color.

标签: pythonopencvimage-processingcomputer-vision

解决方案


你一路走好。我添加了一些代码来解决您的问题 - 在一个掩码中组合两个 HSV 颜色范围。

结果:

在此处输入图像描述

代码:

import numpy as np 
import cv2
# load image
img = cv2.imread("HSV.JPG")
# convert to hsv
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

# Create first mask
lower_red = np.array([0,150,50])
upper_red = np.array([5,255,255])
# Threshold the HSV image to get only green colors
mask = cv2.inRange(hsv, lower_red, upper_red)
# apply mask to original image
res = cv2.bitwise_and(img,img, mask= mask)
#show image
cv2.imshow("Mask1", res)

# Create second mask
lower_red2 = np.array([175,150,50])
upper_red2 = np.array([179,255,255])
# Threshold the HSV image to get only green colors
mask2 = cv2.inRange(hsv, lower_red2, upper_red2)
# apply mask to original image
res2 = cv2.bitwise_and(img,img, mask= mask2)
#show image
cv2.imshow("Mask2", res2)

#combine masks
final_mask = cv2.bitwise_or(mask, mask2)
# apply mask to original image
result = cv2.bitwise_and(img,img, mask= final_mask)
#show image
cv2.imshow("Result", result)
cv2.imshow("Image", img)

cv2.waitKey(0)
cv2.destroyAllWindows()

注意:在结果图像中,如果将单独的蒙版应用于原始图像,我会显示结果。当然,你真的只需要黑色和白色的面具。


推荐阅读