We make use of Motion Detection technology in our daily life. This feature is used in CCTV Cameras to detect any kind of motion in the video frame. In this blog, we are going to make a motion detection script using OpenCV in Python.

Steps for Motion Detection OpenCV Python

  1. Capturing Real-time video from a camera or Reading recorded video.
  2. Read two frames from the video source.
  3. Find Out the Difference between the next frame and the previous frame.
  4. Apply Image manipulations like Blurring, Thresholding, finding out contours, etc.
  5. Finding Area of Contours to detect Motion.
  6. Drawing Rectangle on the Motion Detected Areas.
  7. Showing the video in the window.
Motion Detection – Source | Divyanshu Shekhar Youtube

If you feel any kind of difficulty in these steps have a look at the OpenCV tutorial on Image Manipulation.

Let us Code it now.

Motion Detection OpenCV Python Algorithm

Capturing Video

Capture Video, in which you have to detect movement using OpenCV in Python.

Download the same video from the above link – Official OpenCV GitHub page.

cap = cv.VideoCapture(“./img/vtest.avi”)

Read two frames

ret, frame1 =

ret, frame2 =

In Order to Detect motion in a frame we also need to have the previous frame with us, so we can say there is any kind of movement in the next frame or not.

Finding the Difference between frames

diff = cv.absdiff(frame1, frame2)

absdiff() function is used to find the absolute difference between frame1 and frame2. As the Difference can’t be negative in this case, so absolute difference is taken.

The difference between the two frames is stored in diff variable and the next process will be held on the difference frame.

Image Manipulations for Motion Detection OpenCV Python

Now it is time for image manipulation techniques on the different frames.

First of all the “difference” frame is converted from colored to grayscale image using cvtColor() function in OpenCV.

diff_gray = cv.cvtColor(diff, cv.COLOR_BGR2GRAY)

The diff_gray grayscaled image is then blurred using Gaussian Blur, using a 5×5 Kernel.

The blurring method removes noise from an image and thus good for edge detection.

blur = cv.GaussianBlur(diff_gray, (5, 5), 0)

The Blurred image is then thresholded using the cv.THRESH_BINARY. Basically the image now contains either 255 or 0 in the matrix.

This threshold function takes a grayscale image and also takes the min and max threshold values.

cv.THRESH_BINARY – returns 0 if the color value of that pixel is below the min threshold value, and returns max threshold value if the pixel is greater than the min threshold value. And thus the image contains only low or high value.

_, thresh = cv.threshold(blur, 20, 255, cv.THRESH_BINARY)

The thresholded image is then dilated. Dilation means Adding pixels to the boundaries of objects in an image. The total number of iterations is 3 in this case, which means the same function will be repeated 3 continuous times.

dilated = cv.dilate(thresh, None, iterations=3)

Finding Contours in OpenCV

The dilated image is then used for finding out contours. findCotours() use cv.RETR_TREE and cv.CHAIN_APPROX_SIMPLE technique for finding out contours in the dilated image.

findContours() returns a list of contours.

contours, _ = cv.findContours( dilated, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)

contours variable is a list of all the contours that were found using findContours() function.

        for contour in contours:
            (x, y, w, h) = cv.boundingRect(contour)
            if cv.contourArea(contour) < 900:
            cv.rectangle(frame1, (x, y), (x+w, y+h), (0, 255, 0), 2)
            cv.putText(frame1, "Status: {}".format('Movement'), (10, 20), cv.FONT_HERSHEY_SIMPLEX,
                       1, (255, 0, 0), 3)

Then we have to iterate over each contour in contours.

(x, y, w, h) = cv.boundingRect(contour)

boundingRect() function returns the coordinates and width and height of the bounding rectangle.

cv.contourArea(contour) takes contour as an argument and returns the area bound by the contour.

If the area of the contour is above 900 (in this case). Then a rectangle is drawn covering that object, showing that the object moved when compared to the last frame, and the area covered by the motion was above 900.

Text is also put on the video frame “Status: Movement” when there is motion detected in the video frame.

Motion Detection OpenCV Python GitHub

Find out the full source code of motion detection on GitHub.

About Author
0 0 votes
Article Rating
Notify of
1 Comment
Newest Most Voted
Inline Feedbacks
View all comments
Vijay Singh
Vijay Singh
1 month ago

how can i save video only when motion is detected

Scroll to Top