How to detect vehicle in opencv 3.1? Im using C++

asked 2016-09-18 06:15:49 -0500

teddybur13 gravatar image

updated 2016-09-18 06:16:30 -0500

I used this code but it detects many objects in the video:

using namespace cv; using namespace std;

int main() {

//global variables Mat frame; //current frame Mat back; Mat fore, fMOG2, fKNN; Mat resizeF; Mat fgMaskMOG; //fg mask generated by MOG method String stat= "Unoccupied";

Ptr<backgroundsubtractormog2> pMOG; //MOG Background subtractor pMOG = createBackgroundSubtractorMOG2(); pMOG->setNMixtures(3); pMOG->setDetectShadows(0);

Ptr<backgroundsubtractorknn> pKNN; pKNN = createBackgroundSubtractorKNN(); pKNN->setDetectShadows(0);

//rect //int largest_area=0; //int largest_contour_index =0; vector<vector<point> > contours; vector<vec4i> hierarchy;

VideoCapture stream1(0); //0 is the id of video device.0 if you have only one camera

while(1){ Mat cameraFrame, cont, thresholds; if(!( //get one frame form video break;

    pMOG->apply(frame, fore);
    pKNN->apply(frame, fKNN);

    erode(fore, fore, Mat());
    dilate(fore, fore, Mat());

    //working con
    //findContours(fore, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
    //drawContours(frame, contours, -1, Scalar(0,0,255),2);

    //vector<Vec4i> hierarchy;
    //findContours(frame, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0)); //detect contours

    findContours(fore, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE); //working_on
    vector<vector<Point> > contours_poly(contours.size());
    vector<Rect> bounding_rect(contours.size());

    for(int i =0; i<contours.size(); i++){
        double a= contourArea(contours[i], false);
            bounding_rect[i] = boundingRect(Mat(contours_poly[i]));
    } */

    for(int i=0; i < contours.size(); i++){
        double a= contourArea(contours[i], false);

        //set the area size for which the program detects the object as vehicle
            bounding_rect[i] = boundingRect(Mat(contours_poly[i]));
            rectangle(frame, bounding_rect[i].tl(), bounding_rect[i].br(),Scalar(0,255,0),1,8,0);
            stat = "Occupied";
            stat = "Unoccupied";

    Scalar color(255,255,255);
    //drawContours( frame, contours,largest_contour_index, color, CV_FILLED, 8, hierarchy );
    //drawContours(frame, contours, -1, Scalar(0,0,255),2); //working
    //rectangle(frame, bounding_rect, Scalar(0,255,0),1,8,0);
    putText(frame, "Lot Status: "+stat, Point(10,20), FONT_HERSHEY_SIMPLEX, 0.5,(0,0,255),2,8);

    imshow("Origin", frame);
    imshow("MOG2", fore);
    //imshow("KNN", fKNN);
    //imshow("contour", frame_dupe);

    if (waitKey(30) >= 0)



edit retag flag offensive close merge delete