Simple OpenCV project - detecting and tracking a tennis ball

kehphin picture kehphin · Jun 18, 2012 · Viewed 24.1k times · Source

I have a project where I need to use OpenCV to detect an object (Tennis Ball) on a webcam, and for bonus credit, track it when I roll it across the table.

I haven't had much luck finding info on this, since I'm using OpenCV 2.4, C++, and a lot of information is in the older OpenCV version. I've read a lot of about different ways to do it, but I just don't know how to implement it into my code.

Any help would be appreciated, especially on how to integrate a detection/tracking function into my code

Here is my code so far, I think the image detection/tracking code should go after I apply the filters:

//Includes & Namespaces
#include "cv.h"
#include "highgui.h"
#include <iostream>
using namespace cv;
using namespace std;


//Main Function
int main(int, char**)
{
    VideoCapture vid(0); //Capture from Webcam
    if(!vid.isOpened()) //Error Check for Webcam
    {
        cout << "Could not open camera" << endl;
        return -1;
    }

    Mat pic; //Create Matrix to store image
    namedWindow("video",1); //Open Window

    for(;;) //Infinite loop
    {
        Mat frame; //Create Matrix for a single frame
        vid >> frame; //Transfer from webcam to matrix

        //Filters
        cvtColor(frame, pic, CV_BGR2HSV);
        GaussianBlur(pic, pic, Size(7,7), 1.5, 1.5);

        /*Image Detection Here */           

        imshow("Picture", pic); //Show image

        if(waitKey(30) >= 0)
        break;
    }
    return 0;
}

Answer

ArtemStorozhuk picture ArtemStorozhuk · Jun 18, 2012

Did you try to google your question? There are many info about that.

Simple idea is next: detect your object using color thresholding (it seems that it's yellow or white color) and circle detection. After ball is deteccted you need to just track it using (for example) Lucas-Kanade method.

Here are some guides/manuals:

  1. Tracking colored objects OpenCV
  2. Motion Analysis and Object Tracking
  3. Learning OpenCV
  4. Look at OpenCV's folder samples. There'are many very useful examples. In your situation the best example is samples/cpp/lkdemo.cpp.