为了检测红色,您可以使用HSV颜色阈值脚本来确定下限/上限阈值,然后使用cv2.bitwise_and()
来获得掩模。 使用这个输入图像,
![](https://istack.dev59.com/dd9tg.webp)
我们得到这个结果和掩模
![](https://istack.dev59.com/5RIKx.webp)
代码
import numpy as np
import cv2
image = cv2.imread('1.jpg')
result = image.copy()
image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
lower = np.array([155,25,0])
upper = np.array([179,255,255])
mask = cv2.inRange(image, lower, upper)
result = cv2.bitwise_and(result, result, mask=mask)
cv2.imshow('mask', mask)
cv2.imshow('result', result)
cv2.waitKey()
使用滑块的HSV颜色阈值脚本,请记得更改图像文件路径。
import cv2
import sys
import numpy as np
def nothing(x):
pass
image = cv2.imread('1.jpg')
cv2.namedWindow('image')
cv2.createTrackbar('HMin','image',0,179,nothing)
cv2.createTrackbar('SMin','image',0,255,nothing)
cv2.createTrackbar('VMin','image',0,255,nothing)
cv2.createTrackbar('HMax','image',0,179,nothing)
cv2.createTrackbar('SMax','image',0,255,nothing)
cv2.createTrackbar('VMax','image',0,255,nothing)
cv2.setTrackbarPos('HMax', 'image', 179)
cv2.setTrackbarPos('SMax', 'image', 255)
cv2.setTrackbarPos('VMax', 'image', 255)
hMin = sMin = vMin = hMax = sMax = vMax = 0
phMin = psMin = pvMin = phMax = psMax = pvMax = 0
output = image
wait_time = 33
while(1):
hMin = cv2.getTrackbarPos('HMin','image')
sMin = cv2.getTrackbarPos('SMin','image')
vMin = cv2.getTrackbarPos('VMin','image')
hMax = cv2.getTrackbarPos('HMax','image')
sMax = cv2.getTrackbarPos('SMax','image')
vMax = cv2.getTrackbarPos('VMax','image')
lower = np.array([hMin, sMin, vMin])
upper = np.array([hMax, sMax, vMax])
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv, lower, upper)
output = cv2.bitwise_and(image,image, mask= mask)
if( (phMin != hMin) | (psMin != sMin) | (pvMin != vMin) | (phMax != hMax) | (psMax != sMax) | (pvMax != vMax) ):
print("(hMin = %d , sMin = %d, vMin = %d), (hMax = %d , sMax = %d, vMax = %d)" % (hMin , sMin , vMin, hMax, sMax , vMax))
phMin = hMin
psMin = sMin
pvMin = vMin
phMax = hMax
psMax = sMax
pvMax = vMax
cv2.imshow('image',output)
if cv2.waitKey(wait_time) & 0xFF == ord('q'):
break
cv2.destroyAllWindows()