- 偵測顏色
import cv2
import numpy as np
img = cv2.imread('color.jpg')
if img is None:
print("Error: Image not found or unable to load.")
exit()
img = cv2.resize(img, (0, 0), fx=0.5, fy=0.5)
- 為了過濾顏色,需要建立一個trackbar來調整顏色的色相、飽和度、明度(HSV),也因此圖片會需要轉換成hsv(從原本的jpg)。
建立一個TrackBar
cv2.namedWindow('TrackBar')
cv2.resizeWindow('TrackBar', 640, 320)
def empty(v):
pass
cv2.createTrackbar('Hue Min', 'TrackBar', 0, 179, empty)
cv2.createTrackbar('Hue Max', 'TrackBar', 179, 179, empty)
cv2.createTrackbar('Sat Min', 'TrackBar', 0, 255, empty)
cv2.createTrackbar('Sat Max', 'TrackBar', 255, 255, empty)
cv2.createTrackbar('Val Min', 'TrackBar', 0, 255, empty)
cv2.createTrackbar('Val Max', 'TrackBar', 255, 255, empty)
- 從TrackBar中獲取HSV值
cv2.inRange:將符合 HSV 範圍的像素設為白色,不符合的像素設為黑色。
cv2.bitwise_and():僅保留白色區域的像素,其他區域將被掩蓋。
while True:
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h_min = cv2.getTrackbarPos('Hue Min', 'TrackBar')
h_max = cv2.getTrackbarPos('Hue Max', 'TrackBar')
s_min = cv2.getTrackbarPos('Sat Min', 'TrackBar')
s_max = cv2.getTrackbarPos('Sat Max', 'TrackBar')
v_min = cv2.getTrackbarPos('Val Min', 'TrackBar')
v_max = cv2.getTrackbarPos('Val Max', 'TrackBar')
print(h_min, h_max, s_min, s_max, v_min, v_max)
lower = np.array([h_min, s_min, v_min])
upper = np.array([h_max, s_max, v_max])
mask = cv2.inRange(hsv, lower, upper)
result = cv2.bitwise_and(img, img, mask=mask)
cv2.imshow('img', img)
cv2.imshow('hsv', hsv)
cv2.imshow('mask', mask)
cv2.imshow('result', result)
if cv2.waitKey(1) & 0xFF == 27:
break
cv2.destroyAllWindows()