Object Tracking Using OpenCV

Ramji Balasubramanian
Analytics Vidhya
Published in
3 min readDec 15, 2020

I have been watching cricket for about 10 years and always wondered how a third umpire is tracking the ball for LBW wickets. Yeah, to check LBW, the ball will be tracked using computer vision application and trajectory will be projected based on angle, and other parameters. Today we are going to see how we can track a ball from a video using OpenCV.

Steps followed to track the ball from the chosen video

Step 1: Read the video frame by frame using cv2.VideoCapture()

Step 2: find the threshold/ color for the ball you wanna track (I followed a trail and error method)

Step 3: At every frame, look for the specified color range and make it white and rest all black (binary image conversion)

Step 4: Find the contours and take only the region with larger area.

Step 5: Since this is ball tracking I tried to find the center of the circle and drawn a circle.

Step 6: Draw circle with respect to center captured. That’s it. Doesn't is look simple?

import cv2
import numpy as np
import imutils
import matplotlib.pyplot as plt
cap = cv2.VideoCapture(‘ball_tracking.mp4’)
redLower = np.array([0,10,170], dtype=’uint8')
redUpper = np.array([50,50,255], dtype=’uint8')
c = 0
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))

size = (frame_width, frame_height)
result = cv2.VideoWriter(‘balltracking.mp4’,
cv2.VideoWriter_fourcc(*’MJPG’),
10, size)
while True:
grapped,frame=cap.read()
if grapped == True:

red = cv2.inRange(frame,redLower,redUpper)
red = cv2.GaussianBlur(red,(3,3),0)
cnts = cv2.findContours(red.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
if len(cnts) > 0:
cnt = sorted(cnts,key=cv2.contourArea,reverse=True)[0]
rect = np.int32(cv2.boxPoints(cv2.minAreaRect(cnt)))
cv2.circle(frame, (rect[0][0]+(rect[-1][0] — rect[0][0])//2,rect[1][1]+(rect[-1][-1]-rect[1][1])//2),
25, (0, 255, 0), -1)
cv2.imshow(“Ball Tracking”, frame)
result.write(frame)
if cv2.waitKey() & 0xFF == ord(“q”):
break

else:
break
# cleanup the camera and close any open windows
cap.release()
cv2.destroyAllWindows()
Before Tracking
After Tracking

Challenges

The real challenges will come when we have same color in background image, blurred image, noisy background, etc. That can be solved using preprocessing techniques techniques specific to dataset or deep learnings methods.

Do try on your own to learn more get excited!!!

Here is the Github link for the code and result video. https://github.com/RamjiB/Ball-Tracking

--

--