Motion Detector using OpenCV in Python

Anamika Jha
Affine
Published in
5 min readApr 7, 2020

A step-by-step path to a new venture in Python. A lot can happen with Python! :)

HELLO WORLD!!!

This article belongs to all the beginners in Python who would like to explore some cool side of Python using its simple modules. So, hop on and let’s start the voyage! :)

Let’s import some libraries to get started!

Firstly, we import Open CV2 using cv2. OpenCV-Python is a library of Python bindings designed to solve computer vision problems which can be imported using CV2. The datetime module supplies classes for manipulating dates and times. The datetime class of the module datetime is a combination of time and date (Month, day, year, hour, second, microsecond).

Here, we assign static back as None. An empty list with name motion_list containing a maximum of 2 variables are created to record any type of motion detected by the camera. The time list captures the time taken during the motion is first initialized as 0. A panda dataframe called asdf is created which stores two column values namely Start and End which further note the starting time and ending time captured by our motion detector. The variable video initialised instructs the webcam to start the capture.

We create an infinite for loop using while as True to treat stack of images as video. Since a video is nothing but a cluster of multiple frames set at a particular frame rate. Then we further, read the images captured by the variable video as initialised earlier. The variable motion is initialized as 0 marking as no motion. The image is further captured as a grayscale image to capture the motion easily using contrasting black and white colour. The image is also converted to GaussianBlur for further clarity of the motion. The Gaussian blur is a type of image-blurring filter that uses a Gaussian function (which also expresses the normal distribution in statistics) for calculating the transformation to apply to each pixel in the image.

It is a widely used effect in graphics software, typically to reduce image noise and reduce detail. The cv2 module of Python supports GaussianBlur(Look, how powerful Python is!) and grey represents here the source type of image which is greyscale. (21,21) represents the Gaussian Kernel size and can be adjusted according to the requirement. In the first iteration, we assign the value of static_back to our first frame.

Further, the difference between static background and current frame which is GaussianBlur is calculated and stored under the variable name diff_frame.

If the difference between static background and the current frame is more than 45(here, which can be manipulated accordingly), it will result in colour white i.e. pixel value of 255. Further, the contours of the object are identified. The findContours of the cv2 module is used for the same. The cnts variable stores the (x, y) coordinates of the boundary of a shape.
If we pass cv2.CHAIN_APPROX_NONE, all the boundary points are stored. But actually, do we need all the points? For eg, if we have to find the contour of a straight line. We need just two endpoints of that line. This is what cv2.CHAIN_APPROX_SIMPLE does. It removes all redundant points and compresses the contour, thereby saving memory.

The rectangle module of cv2 is used to create a bounding box around the detected object. The rectangle module takes the image which here is stored as the variable frame, the starting point(x,y), the ending point(x+w,y+h), the colour of the rectangle to be created here green is selected so the RGB code will be (R-0, G-255, B-0) and the thickness of the rectangular in px.

The status of the motion is constantly updated in the list motion_list. Further, the start time of the motion and the end time of the motion is constantly updated. The first image shows the image in the greyscale format. The second image shows the difference between the current frame and the static frame(very first frame). The third frame shows the black and white image where if the difference exceeds by 45 as discussed above, the image turns white. The last image shows the colour image in the RGB format.

While running the script if the letter ‘q’ is entered then the program quits and stops the webcam. If any motion is detected, the end time keeps updating until the last movement recorded.

The motion time recorded is constantly updated in the dataframe df. This is further converted to a CSV file with the name ‘Time_of_movements’. The function cv2.destroyAllWindows kills the window that shows the images.

Save the file in .py format. Then run the file by opening the command prompt where the file is located and type python3 filename.py. You should get four windows capturing four different types of frames as discussed above. voilà you are done!!!

This was one of the uses of OpenCV in Python. OpenCV can also be used for Object Detection, Facial Recognition and other Image Processing techniques.

Hope you all liked this article. Do like and share this article with your peers. For any doubts feel free to comment down below.

Happy Pythoning!!!

--

--

Anamika Jha
Affine
Writer for

An AI enthusiast. In love with Data Science, Image Processing and Virtualization technologies.