Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C++

Fast Color Based Object Tracking Using C++ and OpenCV

4.00/5 (1 vote)
29 Sep 2010CPOL2 min read 30.2K  
A very simple example of color based object tracking

In my first post I want to present something very simple to explain and very funny at the same time. This is a very simple example of color based object tracking. As all we know, color based object tracking can be very simple to achieve, but it is not as robust to implement for something very serious. However, it can be applied for some funny robots.

This example is implemented using C++ as all my image processing algorithms. While I was searching for some library for capturing the camera frames – I didn’t want to waste any time on that – I found a new version of the famous OpenCV library and I wanted to give it a try. If you don’t want to use OpenCV for capturing the camera frames, an excellent video grabber library can be found here.

The algorithm is very simple. First, each frame is captured using the cvQueryFrame, then each frame is processed without using any OpenCV function (I rather like to use mine).
Each frame is first smoother in order to blur the image a little bit. After the smoothing, the image is analyzed in order to determine whether each pixel belongs to the color we are interested in. in this case, the red one. All pixels matching this criteria are left untouched, all other pixels are whitened.

Two Red pens are tracked

The next step is to threshold the image, so we will have a white-black image only where the black pixels belong to the object we are following. In order to improve the recognition, the final step is to use morphological operation to remove undesired spots due to image noise.

After the final step was performed, we have identified the objects matching the color we are tracking.
I use again OpenCV in the final step in order to display the object tracked in the original video frame as you can see in the video.
It is a simple way to start working on object recognition/tracking and start improving it as you learn more complex algorithms.

I have used CamStudio http://sourceforge.net/projects/camstudio/ for capturing the video.

The blog can also be followed with

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)