python - 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.
解决方案
你一路走好。我添加了一些代码来解决您的问题 - 在一个掩码中组合两个 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()
注意:在结果图像中,如果将单独的蒙版应用于原始图像,我会显示结果。当然,你真的只需要黑色和白色的面具。
推荐阅读
- java - Java:如何避免“方法不适用于参数”错误
- python - 如何从下一页中抓取价格?
- facebook - Facebook 页面访问令牌以显示任何公共 fb 页面提要
- sql-server - 在 SQL Server 中为年份和季度赋值
- r - R 不会运行模型,因为它坚持数据不是 UnmarkedFrame Occu 主题
- visual-studio-2017 - 如何避免在 Visual Studio 2017 15.9.13 中添加此或我的资格问题
- css - 我的本地 python 服务器不知道要运行的静态 css 文件
- python - 如何添加子文件夹
- image - 在 keras 中实现没有 textImagegenerator 的 CTC
- javascript - React 组件样式封装