O'Reilly logo

Computer Vision with Python 3 by Saurabh Kapur

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Color tracking

In this section, we will try to understand how to track a color in a video using OpenCV. The following is the code for tracking yellow color in a video:

import cv2import numpy as npdef detect(img):         lower_range = np.array([40,150,150], dtype = "uint8")         upper_range = np.array([70,255,255], dtype = "uint8")         img = cv2.inRange(img,lower_range,upper_range)         cv2.imshow("Range",img)         m=cv2.moments(img)         if (m["m00"] != 0):                  x = int(m["m10"]/m["m00"])                  y = int(m["m01"]/m["m00"])         else:                  x = 0                  y = 0         return (x, y)cam = cv2.VideoCapture(0)last_x = 0last_y = 0while (cam.isOpened()):         ret, frame = cam.read()         cur_x, cur_y = detect(frame)         cv2.line(frame,(cur_x,cur_y),(last_x,last_y),(0,0,200),5);         last_x = cur_x         last_y = cur_y         cv2.imshow('frame',frame) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required