import cv2 as cv
#step1.查找对应hsv的值:以红色为例
red = np.uint8([[[0,0,255]]])
hsv_red = cv.cvtColor(red, cv.COLOR_BGR2HSV)
print(hsv_red)
#step2.利用调色板找合适的范围
def nothing(x):
pass
img = cv.imread("multicolor.jpg")
hsv = cv.cvtColor(img, cv.COLOR_BGR2HSV)
cv.imshow("source", img)
# cv.namedWindow("test", cv.WINDOW_NORMAL)
cv.namedWindow("mask_blue",cv.WINDOW_NORMAL)
#find lower_blue parameters
cv.createTrackbar("H_lower", "mask_blue", 170, 180, nothing)
cv.createTrackbar("S_lower", "mask_blue", 100, 255, nothing)
cv.createTrackbar("V_lower", 'mask_blue', 100, 255, nothing)
#find upper_blue parameters
cv.createTrackbar("H_upper", "mask_blue", 10, 180, nothing)
cv.createTrackbar("S_upper", "mask_blue", 255, 255, nothing)
cv.createTrackbar("V_upper", 'mask_blue', 255, 255, nothing)
while (1):
if cv.waitKey(1) == 27:
break
h_lower = cv.getTrackbarPos("H_lower", "mask_blue")
s_lower = cv.getTrackbarPos("S_lower", "mask_blue")
v_lower = cv.getTrackbarPos("V_lower", "mask_blue")
h_upper = cv.getTrackbarPos("H_upper", "mask_blue")
s_upper = cv.getTrackbarPos("S_upper", "mask_blue")
v_upper = cv.getTrackbarPos("V_upper", "mask_blue")
lower_blue = np.array([h_lower, s_lower, v_lower])
upper_blue = np.array([h_upper, s_upper, v_upper])
mask_red1 = cv.inRange(hsv, lower_blue, upper_blue)
lower_red = np.array([170, 50, 0])
upper_red = np.array([180, 255,255])
mask_red2 = cv.inRange(hsv, lower_red, upper_red)
mask = mask_red1 + mask_red2
cv.imshow("mask_blue", mask_red1)
cv.imshow("mask_red", mask_red2)
cv.imshow("mask", mask)
#step3.利用找到的值做mask,可以得到结果:有点偏差,不修改了,思路就是这样
#merge all the masks
img = cv.imread("multicolor.jpg")
hsv = cv.cvtColor(img, cv.COLOR_BGR2HSV)
lower_blue= np.array([100, 50, 50])
upper_blue = np.array([140, 255,255])
mask_blue = cv.inRange(hsv, lower_blue, upper_blue)
lower_green= np.array([10, 110, 0])
upper_green = np.array([80, 255,255])
mask_green = cv.inRange(hsv, lower_green, upper_green)
lower_red1 = np.array([0, 10, 10])
upper_red1 = np.array([10, 255,255])
mask_red1 = cv.inRange(hsv, lower_red1, upper_red1)
lower_red2 = np.array([170, 50, 0])
upper_red2 = np.array([180, 255,255])
mask_red2 = cv.inRange(hsv, lower_red2, upper_red2)
mask_red = mask_red1 + mask_red2
mask = mask_blue + mask_red + mask_green
res = cv.bitwise_and(img, img, mask = mask)
cv.imshow('source', img)
cv.imshow('test', res)
cv.waitKey(0)
cv.destroyAllWindows()
?
?
|