Skip to content

Instantly share code, notes, and snippets.

@danyashorokh
Created May 31, 2019 09:45
Show Gist options
  • Save danyashorokh/faafc14be14a70b9d439104529698266 to your computer and use it in GitHub Desktop.
Save danyashorokh/faafc14be14a70b9d439104529698266 to your computer and use it in GitHub Desktop.
[Python][CV] Color filtering
import cv2 as cv
import numpy as np
def nothing(x):
pass
# Color trackbars
cv.namedWindow("Trackbars")
cv.createTrackbar("lower_h", "Trackbars", 0, 179, nothing)
cv.createTrackbar("upper_h", "Trackbars", 179, 179, nothing)
cv.createTrackbar("lower_s", "Trackbars", 0, 255, nothing)
cv.createTrackbar("upper_s", "Trackbars", 255, 255, nothing)
cv.createTrackbar("lower_v", "Trackbars", 0, 255, nothing)
cv.createTrackbar("upper_V", "Trackbars", 255, 255, nothing)
# cv.setTrackbarPos("lower_h", "Trackbars", 0)
# cv.setTrackbarPos("upper_h", "Trackbars", 35)
# cv.setTrackbarPos("lower_s", "Trackbars", 10)
# cv.setTrackbarPos("upper_s", "Trackbars", 97)
# cv.setTrackbarPos("lower_v", "Trackbars", 6)
# cv.setTrackbarPos("upper_v", "Trackbars", 61)
file = 'video.mp4'
cap = cv.VideoCapture(file)
while 1:
# get frame from the video
ret, frame = cap.read()
# Stop the program if reached end of video
if not ret:
print("Finished")
cv.waitKey(100)
# Release device
cap.release()
break
hsv = cv.cvtColor(frame, cv.COLOR_BGR2HSV)
l_h = cv.getTrackbarPos("lower_h", "Trackbars")
l_s = cv.getTrackbarPos("lower_s", "Trackbars")
l_v = cv.getTrackbarPos("lower_v", "Trackbars")
u_h = cv.getTrackbarPos("upper_h", "Trackbars")
u_s = cv.getTrackbarPos("upper_s", "Trackbars")
u_v = cv.getTrackbarPos("upper_v", "Trackbars")
lower_blue = np.array([l_h, l_s, l_v])
upper_blue = np.array([u_h, u_s, u_v])
mask_hsv = cv.inRange(hsv, lower_blue, upper_blue)
result = cv.bitwise_and(frame, frame, mask=mask_hsv)
cv.imshow('result', np.hstack([frame, cv.cvtColor(mask_hsv, cv.COLOR_GRAY2BGR)]))
if (cv.waitKey(10) & 0xFF) == 27:
break
cap.release()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment