Motion detection + Contours (Python)
Question: What's wrong with my python code. It says syntax error at line 5 "Mat frame",
line 13 "std". This code was originally from C++, I converted it to Python.

    
    
    import numpy as np
    import cv2
    
    def run_main():
        cv2.Mat frame
        cv2.Mat back
        cv2.Mat fore
        cv2.VideoCapture cap(0)
        cv2.BackgroundSubtractorMOG2 bg
        bg.nmixtures = 3
        bg.bShadowDetection = false
    
        std::vector<std::vector<cv::Point> > contours;
    
        cv2.namedWindow("Frame")
        cv2.namedWindow("Background")
    
        while True:
            cap >> frame;
            bg.operator ()(frame,fore)
            bg.getBackgroundImage(back)
            cv2.erode(fore,fore,cv2.Mat())
            cv2.dilate(fore,fore,cv2.Mat())
            cv2.findContours(fore,contours,CV_RETR_EXTERNAL,CV_CHAIN_APPROX_NONE)
            cv2.drawContours(frame,contours,-1,cv2.Scalar(0,0,255),2)
            cv2.imshow("Frame",frame)
            cv2.imshow("Background",back)
            if cv2.waitKey(1) & 0xFF == ord('q')
                break
    
    cap.release()
    cv2.destroyAllWindows()
    
    if __name__ == "__main__":
        run_main()
    


Answer: Your code is no valid Python, it's a syntactic mix between C++ and Python.
Some hints on what needs to be changed:

    
    
    cv2.Mat frame
    cv2.Mat back
    cv2.Mat fore
    cv2.VideoCapture cap(0)
    cv2.BackgroundSubtractorMOG2 bg
    

There is no **Mat** type in OpenCV Python. It uses [numpy
arrays](http://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html)
to handle data. Also, in Python variables are not declared this way.

    
    
    cap = cv2.VideoCapture()
    

is the right way to do it.

The method you're trying to call to create the background subractor does not
exist.

    
    
    cv2.BackgroundSubtractorMOG2 bg
    

has to be

    
    
    bg = cv2.createBackgroundSubtractorMOG2()
    

Also see
[this](http://docs.opencv.org/3.1.0/db/d5c/tutorial_py_bg_subtraction.html#gsc.tab=0)
tutorial.

This line

    
    
    std::vector<std::vector<cv::Point> > contours;
    

is just plain C++.

    
    
        cap >> frame;
    

That's the C++ way to read data. In Python you should do

    
    
    frame = cap.read()
    

