Ask Your Question
0

Detect cars in video

asked 2016-02-11 05:08:57 -0600

Kampi gravatar image

Hello,

I´m new with OpenCV and I want detect cars in a webcam or a video file. This is my current solution:

while (Camera.read(RawImage))
{
    Camera >> RawImage;
    BackgroundMask(RawImage, Mask);
    cv::threshold(Mask, BinaryMask, 100, 255, cv::THRESH_BINARY);
    Mat NewImage(RawImage.rows, RawImage.cols, CV_8UC3, Scalar(0, 255, 0));
    RawImage.copyTo(NewImage, BinaryMask);

    imshow("Rawimage", RawImage);
    imshow("New Image", NewImage);
    waitKey(30);
}

I get a green Image with the filtered cars in it. Now I want to draw a box around this cars. How can I do it in an easy way?

Thank you for help :)

edit retag flag offensive close merge delete

2 answers

Sort by » oldest newest most voted
3

answered 2016-02-11 06:45:07 -0600

Simply said

  • Use findContours on the binary image. It will return blob locations.
  • Then use boundingRect to get the rectangle surrounding the blob
  • Now loop over all the rectangles AND use the rectangle function to draw them

Good luck!

edit flag offensive delete link more
0

answered 2016-02-15 03:35:19 -0600

Kampi gravatar image

Hello,

thank you for your response. I have to wait a few days to answer you, so please excuse me. I`ve changed my code to this:

    Camera >> RawImage;
    if (RawImage.empty())
    {
        cout << "Video beendet..." << endl;
        destroyAllWindows();
        break;
    }

    RawImage_Copy = RawImage.clone();
    BackgroundMask(RawImage_Copy, Mask);
    Mat Fill = getStructuringElement(MORPH_ELLIPSE, Size(2, 2), Point(1, 1));
    morphologyEx(Mask, Mask, CV_MOP_CLOSE, Fill);

    threshold(Mask, BinaryImage, 128, 255, CV_THRESH_BINARY);

    findContours(BinaryImage.clone(), Kontur, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);

    for (int i = 0; i< Kontur.size(); i++)
    {
        Rect Object = boundingRect(Kontur[i]);
        ROI = RawImage_Copy(Object);
        resize(ROI, ROI, Size(200, 200));
        imshow("ROI", ROI);
    }

    imshow("Rohbild", RawImage);
    imshow("Binary Image", BinaryImage);
    imshow("Mask", Mask);
    waitKey(1);

This solution works pretty good.

image description

The next step is to count the cars passing an imaginary area. My first idea was to define a area and check the x-coordinates of a corner from the bounding rect of each car and check it with my box. If the x-coordinate of the bounding rect is inside my box, the software should increase a counter. But this solution doesn´t work very well. Does OpenCV provide a better solution to realize this idea?

edit flag offensive delete link more

Question Tools

1 follower

Stats

Asked: 2016-02-11 05:07:55 -0600

Seen: 1,012 times

Last updated: Feb 15 '16