Tracking Object Using OpenCV

In this coding sample we will use the powerful library OpenCV (Open Computer Vision) to track a red ball. This will be the ground base for my next videos / tutorials that we will build on top of this code (but more for that later). In case you need help with how to install openCV on your raspberry pi (small hint where this is going) you can watch my video on my channel: How To Install OpenCV on Raspberry Pi

How to track objects

Tracking an object requires to know Min/Max of the HSV (Hue,Saturation and Value) of the image, that way we can generate the threshold (or binary) Image. Knowing the binary image, we will be able to find the contours as well as the hierarchy of the contours.

Steps to start tracking


Track-bars to set HSV Values
Track-bars to send HSV values to Binary Image

Sliding the Min/Max of HSV will effect the binary image. The goal is to have the binary image all black except what you would like to track.

HSV Image

HSV Image
HSV Of the Original Image

This image is just for show, how the HSV is compare to the Original image.

Binary / Threshold Image

Binary / Threshold Image
The Binary / Threshold Image as the Sliders are moved

As you move the sliders / track-bars the binary image will reflect these changes. You goal here that the image will be all black except what you would like to track

Original Image With Tracking

Original Image with Tracking
Original Image With Circle on What we are tracking

This is the original Image with the tracking circle around the object (at this case it is just a red book on the shelf.)

There are many options to run the code, but the main ones are:

  1. InitTrackbars - This function will take the name of the trackbar window, and will initialize the trackbars (including setting the Min/Max Values for the Binary Window)
  2. tracker.SetUseDilate(true/false) - if you want to use Dilate while the program is calculating the tracking object
  3. tracker.SetUseErode(true/false) - if you want to use Erode while the program is calculating the tracking object
Note: - if Dilate and Erode are set to false the program will not run the Morph function and you will see more noise in the binary / threshold image. To download the project (which is currently for Windows using VS 2012) you can download the file here