利用 cv2.inRange來追蹤顏色
截取要偵測顏色的上下限 (用小畫家滴管也可以, 注意是BGR)
import cv2
import numpy as np
# mouse callback function
def pick_color(event,x,y,flags,param):
if event == cv2.EVENT_LBUTTONDOWN:
pixel = image[y,x]
#you might want to adjust the ranges(+-10, etc):
upper = np.array([pixel[0] + 20, pixel[1] + 50, pixel[2] + 50])
lower = np.array([pixel[0] - 20, pixel[1] - 50, pixel[2] - 50])
print(pixel, lower, upper)
image_mask = cv2.inRange(image,lower,upper)
cv2.imshow("mask",image_mask)
image = cv2.imread("./images/flower.png")
cv2.namedWindow('Image')
cv2.setMouseCallback('Image', pick_color)
cv2.imshow("Image",image)
cv2.waitKey(0)
cv2.destroyAllWindows()
再執行顏色追蹤得到結果
import cv2
import numpy as np
image = cv2.imread("./images/flower.png")
lower = np.array([22, 166, 142])
upper = np.array([62, 266, 242])
filtered = cv2.inRange(image, lower, upper)
blurred = cv2.GaussianBlur(filtered, (15, 15), 0)
# find contours in the image
(_, cnts, _) = cv2.findContours(blurred.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
if len(cnts) > 0:
cnt = sorted(cnts, key = cv2.contourArea, reverse = True)[0]
# compute the (rotated) bounding box around then
# contour and then draw it
rect = np.int32(cv2.boxPoints(cv2.minAreaRect(cnt)))
cv2.drawContours(image, [rect], -1, (0, 255, 0), 2)
cv2.imshow("Tracking", image)
cv2.waitKey(0)