简体   繁体   中英

Creating global variables in a function C++

I am using C++ and openCV to do people tracking. I am trying to make a function that applies the MOG2 background subtraction method. this is the first time I've tried making a function. The function looks like this:

Mat FindMOG2(Mat FrameShown){


    MOG2Pointer->apply(FrameShown, MOG2Mask);

    // find contours
    findContours(MOG2Mask, Contours, Hierachy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));

    //approximate contours to polygons and get bounding rects
    vector<vector<Point> > ContoursPoly(Contours.size());
    vector<Rect> MOGRects(Contours.size());

    for (int i = 0; i < Contours.size(); i++){
        approxPolyDP(Mat(Contours[i]), ContoursPoly[i], 3, true);
        MOGRects[i] = boundingRect(Mat(ContoursPoly[i]));
        }

    //draw bounding rects
    Mat Drawing = Mat::zeros(MOG2Mask.size(), CV_8UC3);

    for (int i = 0; i < Contours.size(); i++){
        vector<Vec4i>(), 0, Point());
        rectangle(Drawing, MOGRects[i].tl(), MOGRects[i].br(), Scalar(0, 255, 0), 2, 8, 0);
        }
    return Drawing;
}

The problem is, I also have to declare these 'global' variables outside the main()

Mat MOG2Mask;
vector<vector<Point> > Contours;
vector<Vec4i> Hierachy;
Ptr<BackgroundSubtractor> MOG2Pointer;

and this inside the main, but outside the while loop that plays the video

MOG2Pointer = createBackgroundSubtractorMOG2();

Basically, I want the function to automatically declare these variables without me having to initialise them. I am new to programming, so if someone could just point me in the right direction or just give me something to research I would be very grateful.

Cheers.

与其在全局范围内声明变量,不如在函数范围内声明它们。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM