Search code examples
c++opencvcontour

How do I find if the object ball I track crosses a line that I have drawn?


I am using c++ with OpenCV 3.0 to create a basic form of SimulCam.

I am currently stuck on finding a way to check when the object ball has crossed/intersected with a line that I have drawn on the output window.

The ball is being tracked using contours, and ultimately I would like to work out the exact frame number this intersect happens at.

But first, I would like to understand how to perform the check to see when the Object ball has crossed/intersected with the drawn line.

Scene with ball moving towards line

I have the contours for the object, I would like to understand how to perform the check of an intersection.

Code for finding contours and Object Tracking:

findContours(resizedThresh, contourVector, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0));

contourVector.resize(contourVector.size());

line(resizedF_Fast, Point(300, 0), Point(300, 360), Scalar(255), 2, 8);
for (size_t i = 0; i < contourVector.size(); i++) {

     approxPolyDP(Mat(contourVector[i]), contourVector[i], 0.01*arcLength(contourVector[i], true), true);
     double area = contourArea(contourVector[i]);

     if (contourVector[i].size() > 5 && (area > 200)) {
        ++circlesC;
        drawContours(resizedF_Fast, contourVector, i, Scalar(255, 255, 255), 2, CV_AA, hierarchy, abs(1));
        searchForMovement(resizedThresh, resizedF_Fast);
     }
}

I have done some other research, and I have been looking into using lineIterator, but i'm not entirely sure..

Apologies for the potential crude code, novice here. Any help would be greatly appreciated.


Solution

  • I finally worked through this, i'll post the general idea here.

    For each frame, calculate the object contours.

    • each contour will have an x and y coordinate stored

    Used LineIterator (e.g. lineIt) to cycle through all values of a line.

    if (xpos_contour < lineIt.pos().x) {
         // Object is on the left of the line
    }
    else if (xpos_contour > lineIt.pos().x) {
         // Object is to the right of the line
    }
    

    Bear in mind the input video im using filmed top down, so only the x coordinate mattered.