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:
import cv2: Imports the OpenCV library for working with images and videos.import time: Imports the time module for adding delays.import imutils: Imports the imutils library for image processing utilities.cam = cv2.VideoCapture(0): Initializes the webcam (camera) with ID 0. You can change the ID to use a different camera if available.time.sleep(1): Adds a delay of 1 second to allow the camera to initialize properly.firstFrame=None: Initializes the variablefirstFrameto store the first frame captured by the camera.area = 500: Sets the minimum area (in pixels) for a contour to be considered as a moving object.while True:: Starts an infinite loop to continuously capture frames from the camera and process them._,img = cam.read(): Reads a frame from the camera and stores it in the variableimg.text = "Normal": Initializes the variabletextwith the value “Normal”.img = imutils.resize(img, width=500): Resizes the captured frame to a width of 500 pixels using theimutils.resizefunction.grayImg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY): Converts the resized frame from color to grayscale using thecv2.cvtColorfunction.gaussianImg = cv2.GaussianBlur(grayImg, (21, 21), 0): Applies Gaussian blur to the grayscale frame to smoothen it using thecv2.GaussianBlurfunction.if firstFrame is None:: Checks iffirstFrameis None, indicating that it’s the first iteration of the loop.firstFrame = gaussianImg: If it’s the first iteration, setsfirstFrameto the current frame (after Gaussian blur) to capture the background.imgDiff = cv2.absdiff(firstFrame, gaussianImg): Calculates the absolute difference betweenfirstFrameand the current frame to detect moving objects usingcv2.absdiff.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 usingcv2.threshold.threshImg = cv2.dilate(threshImg, None, iterations=2): Dilates the thresholded image to fill in gaps and make the detected contours more visible usingcv2.dilate.cnts = cv2.findContours(threshImg.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE): Finds contours in the thresholded image usingcv2.findContours.cnts = imutils.grab_contours(cnts): Grabs the contours returned bycv2.findContoursusingimutils.grab_contours.for c in cnts:: Iterates over each contour found in the image.if cv2.contourArea(c) < area:: Checks if the area of the contour is less than the specifiedarea.(x, y, w, h) = cv2.boundingRect(c): Calculates the bounding rectangle for the contour usingcv2.boundingRect.cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2): Draws a green rectangle around the detected moving object usingcv2.rectangle.text = "Moving Object detected": Updates thetextvariable to indicate that a moving object has been detected.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) usingcv2.putText.cv2.imshow("cameraFeed",img): Displays the processed frame in a window named “cameraFeed” usingcv2.imshow.key = cv2.waitKey(1) & 0xFF: Waits for a key press for 1 millisecond and stores the key value inkey.if key == ord("q"):: Checks if the pressed key is ‘q’ (ASCII value 113) to exit the loop.break: Breaks out of the loop if the ‘q’ key is pressed.cam.release(): Releases the camera resource.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.





Leave a Reply