Motion Detection and Tracking using OpenCV Python

Gowtham
3 min readSep 23, 2021

--

In this post, we are going to discuss about how to detect and track movements(simply motion detection and tracking) using the OpenCV module.

At first, you need to install the opencv-python module, to install the module just open your command prompt and type,

pip install opencv-python

Then hit enter, it will automatically install the module automatically.

After installing the module, just import the module and write the basic code to read the video.

After that, we have to get the two frames from the video or webcam and find the difference between two frames, which is nothing but if there is a movement that occurs between the frames there might be a difference.

So, here we are trying to get the difference using the cv2.absdiff() function in the OpenCV module and this method takes two parameters which are the two frames.

Then, convert the diff image to grayscale this will make more sense than the RGB image and smoothen the image to get the clear binary image using cv2.GaussianBlur() function in the OpenCV module.

After smoothening the image, convert the image to a binary image to find contours using the cv2.threshold() function in the OpenCV module.

Now, we are ready to detect and track movements by simply following the step given below,

  • find contours using the cv2.findContours() function in the OpenCV module.
  • using the details of the contours, you can outline the contours in different colors by cv2.drawContours() or draw a rectangle around the contours by getting the x, y position, width, and height using cv2.boundingRect() which takes contours as a parameter.

In this case, we are going to draw a rectangle around the contours.

And finally, display the output.

For Full Source Code and output demo, click here.

Thank You For Reading…

--

--