Color Detection
Color Detection
You are used to stackImages function from the previous chapter.
Don't think too much about 'empty' function.
import cv2
import numpy as np
def empty(a):
pass
path = "Resources/lambo.png"
cv2.namedWindow("TrackBars")
cv2.resizeWindow("TrackBar", 640, 240)
cv2.createTrackbar("Hue Min", "TrackBars", 4, 179, empty)
cv2.createTrackbar("Hue Max", "TrackBars", 22, 179, empty)
cv2.createTrackbar("Sat Min", "TrackBars", 130, 255, empty)
cv2.createTrackbar("Sat Max", "TrackBars", 255, 255, empty)
cv2.createTrackbar("Val Min", "TrackBars", 141, 255, empty)
cv2.createTrackbar("Val Max", "TrackBars", 255, 255, empty)
while True:
img = cv2.imread(path)
imgHsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h_min = cv2.getTrackbarPos("Hue Min", "TrackBars")
h_max = cv2.getTrackbarPos("Hue Max", "TrackBars")
s_min = cv2.getTrackbarPos("Sat Min", "TrackBars")
s_max = cv2.getTrackbarPos("Sat Max", "TrackBars")
v_min = cv2.getTrackbarPos("Val Min", "TrackBars")
v_max = cv2.getTrackbarPos("Val Max", "TrackBars")
lower = np.array([h_min, s_min, v_min])
upper = np.array([h_max, s_max, v_max])
mask = cv2.inRange(imgHsv, lower, upper)
imgResult = cv2.bitwise_and(img, img, mask=mask)
Images = [[img, imgHsv], [mask, imgResult]]
imgStack = stackImages(0.5, Images)
cv2.imshow("Result", imgStack)
cv2.waitKey(1)
Last updated