Moving Object Detection with OpenCv & Imutils

Detecting moving objects in a video stream is a key task in many computer vision applications. Using OpenCV and Imutils, we can create a program that analyzes video frames to identify areas where there is motion. This can be useful in surveillance, tracking, and many other fields where detecting motion is important. In this article, we’ll explore how to use these libraries to create a simple motion detection program.

Let’s check out the code below for the same along with the output

you need to first create a file with .py extension and copy the below code and paste it there

import cv2 #image
import time #delay
import imutils #resize

cam = cv2.VideoCapture(0) #cam id
time.sleep(1)

firstFrame=None
area = 500

while True:
    _,img = cam.read() #read frame from camera
    text = "Normal" 
    img = imutils.resize(img, width=500) #resize
    
    grayImg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #color 2 Gray scale image
    
    gaussianImg = cv2.GaussianBlur(grayImg, (21, 21), 0) #smoothened
    
    if firstFrame is None:
            firstFrame = gaussianImg #capturing 1st frame on 1st iteration
            continue

    imgDiff = cv2.absdiff(firstFrame, gaussianImg) #absolute diff b/w 1st nd current frame
    
    threshImg = cv2.threshold(imgDiff, 25, 255, cv2.THRESH_BINARY)[1] #binary
    
    threshImg = cv2.dilate(threshImg, None, iterations=2)
    
    cnts = cv2.findContours(threshImg.copy(), cv2.RETR_EXTERNAL,
            cv2.CHAIN_APPROX_SIMPLE)
    
    cnts = imutils.grab_contours(cnts)
    for c in cnts:
            if cv2.contourArea(c) < area:
                    continue
            (x, y, w, h) = cv2.boundingRect(c)
            cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
            text = "Moving Object detected"
    print(text)
    cv2.putText(img, text, (10, 20),
            cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
    cv2.imshow("cameraFeed",img)
    key = cv2.waitKey(1) & 0xFF
    if key == ord("q"):
        break

cam.release()
cv2.destroyAllWindows()

Output:

Explanation of the above code:

Let’s break down each line of code in detail:

  1. import cv2: Imports the OpenCV library for working with images and videos.
  2. import time: Imports the time module for adding delays.
  3. import imutils: Imports the imutils library for image processing utilities.
  4. cam = cv2.VideoCapture(0): Initializes the webcam (camera) with ID 0. You can change the ID to use a different camera if available.
  5. time.sleep(1): Adds a delay of 1 second to allow the camera to initialize properly.
  6. firstFrame=None: Initializes the variable firstFrame to store the first frame captured by the camera.
  7. area = 500: Sets the minimum area (in pixels) for a contour to be considered as a moving object.
  8. while True:: Starts an infinite loop to continuously capture frames from the camera and process them.
  9. _,img = cam.read(): Reads a frame from the camera and stores it in the variable img.
  10. text = "Normal": Initializes the variable text with the value “Normal”.
  11. img = imutils.resize(img, width=500): Resizes the captured frame to a width of 500 pixels using the imutils.resize function.
  12. grayImg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY): Converts the resized frame from color to grayscale using the cv2.cvtColor function.
  13. gaussianImg = cv2.GaussianBlur(grayImg, (21, 21), 0): Applies Gaussian blur to the grayscale frame to smoothen it using the cv2.GaussianBlur function.
  14. if firstFrame is None:: Checks if firstFrame is None, indicating that it’s the first iteration of the loop.
  15. firstFrame = gaussianImg: If it’s the first iteration, sets firstFrame to the current frame (after Gaussian blur) to capture the background.
  16. imgDiff = cv2.absdiff(firstFrame, gaussianImg): Calculates the absolute difference between firstFrame and the current frame to detect moving objects using cv2.absdiff.
  17. threshImg = cv2.threshold(imgDiff, 25, 255, cv2.THRESH_BINARY)[1]: Applies a binary threshold to the difference image to create a binary image where moving objects are highlighted using cv2.threshold.
  18. threshImg = cv2.dilate(threshImg, None, iterations=2): Dilates the thresholded image to fill in gaps and make the detected contours more visible using cv2.dilate.
  19. cnts = cv2.findContours(threshImg.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE): Finds contours in the thresholded image using cv2.findContours.
  20. cnts = imutils.grab_contours(cnts): Grabs the contours returned by cv2.findContours using imutils.grab_contours.
  21. for c in cnts:: Iterates over each contour found in the image.
  22. if cv2.contourArea(c) < area:: Checks if the area of the contour is less than the specified area.
  23. (x, y, w, h) = cv2.boundingRect(c): Calculates the bounding rectangle for the contour using cv2.boundingRect.
  24. cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2): Draws a green rectangle around the detected moving object using cv2.rectangle.
  25. text = "Moving Object detected": Updates the text variable to indicate that a moving object has been detected.
  26. cv2.putText(img, text, (10, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2): Adds text to the frame to display the status (Normal or Moving Object detected) using cv2.putText.
  27. cv2.imshow("cameraFeed",img): Displays the processed frame in a window named “cameraFeed” using cv2.imshow.
  28. key = cv2.waitKey(1) & 0xFF: Waits for a key press for 1 millisecond and stores the key value in key.
  29. if key == ord("q"):: Checks if the pressed key is ‘q’ (ASCII value 113) to exit the loop.
  30. break: Breaks out of the loop if the ‘q’ key is pressed.
  31. cam.release(): Releases the camera resource.
  32. cv2.destroyAllWindows(): Closes all OpenCV windows.

This code captures video from the webcam, detects moving objects in the video stream, and displays the video with moving objects highlighted in a green rectangle.

In conclusion, OpenCV and Imutils provide powerful tools for detecting moving objects in video streams. By combining these libraries, we can create robust and efficient motion detection systems that can be used in a variety of applications. From security surveillance to automated monitoring, the ability to detect motion opens up a world of possibilities for computer vision and image processing.

Author

Sona Avatar

Written by

One response to “Moving Object Detection with OpenCv & Imutils”

  1. Nice one !

Leave a Reply

Trending

CodeMagnet

Your Magnetic Resource, For Coding Brilliance

Programming Languages

Web Development

Data Science and Visualization

Career Section

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-4205364944170772"
     crossorigin="anonymous"></script>