Thursday, April 27, 2023

Motion Detection using OpenCV using python

 import cv2


# Set up video capture device

cap = cv2.VideoCapture(0)


# Initialize variables

previous_frame = None


while True:

    # Capture current frame

    ret, current_frame = cap.read()


    # Convert to grayscale

    current_frame_gray = cv2.cvtColor(current_frame, cv2.COLOR_BGR2GRAY)


    # Check if previous frame exists

    if previous_frame is not None:

        # Compute absolute difference between current and previous frame

        frame_diff = cv2.absdiff(current_frame_gray, previous_frame)


        # Apply thresholding to remove noise

        thresh = cv2.threshold(frame_diff, 25, 255, cv2.THRESH_BINARY)[1]


        # Find contours of objects in thresholded image

        contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)


        # Draw bounding box around each contour

        for contour in contours:

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

            cv2.rectangle(current_frame, (x, y), (x + w, y + h), (0, 0, 255), 2)


    # Update previous frame

    previous_frame = current_frame_gray


    # Display current frame

    cv2.imshow("Motion Detection", current_frame)


    # Exit on 'q' key press

    if cv2.waitKey(1) & 0xFF == ord('q'):

        break


# Release video capture device and destroy all windows

cap.release()

cv2.destroyAllWindows()

In this code, we capture frames from the default video capture device using cv2.VideoCapture(0). We then convert the current frame to grayscale using cv2.cvtColor(), and compute the absolute difference between the current and previous frames using cv2.absdiff(). We apply thresholding to the difference image to remove noise using cv2.threshold(), and find the contours of objects in the thresholded image using cv2.findContours(). Finally, we draw bounding boxes around each contour using cv2.rectangle().

To run this code, save it in a Python file (e.g., motion_detection.py) and run it using the command python motion_detection.py in a terminal or command prompt. Make sure you have OpenCV installed before running the code.

No comments:

Post a Comment

ASP.NET Core

 Certainly! Here are 10 advanced .NET Core interview questions covering various topics: 1. **ASP.NET Core Middleware Pipeline**: Explain the...