opencv | detect people | python write video | Search

This code imports necessary libraries for computer vision tasks and defines three functions: percent_motion to calculate the percentage of white pixels in a thresholded image, image_grayscale to convert an image to grayscale, and diff_images to compute the absolute difference between two frames. The functions are exported as part of the module namespace for use in other scripts.

Run example

npm run import -- "motion detection"

motion detection


import cv2
import numpy as np

def percent_motion(thresh):
  white_pixels = np.count_nonzero(thresh == 255)
  total_pixels = thresh.size

  # Calculate percentage
  white_percentage = (white_pixels / total_pixels) * 100
  return white_percentage

def image_grayscale(image):
  gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  return gray_image

def diff_images(prev_frame, frame):
  # Compute absolute difference between current and previous frame
  diff = cv2.absdiff(prev_frame, frame)

  # Threshold the difference image
  _, thresh = cv2.threshold(diff, 30, 255, cv2.THRESH_BINARY)
  # Update previous frame
  # prev_frame = frame.copy()
  return thresh

__all__ = {
  "percent_motion": percent_motion,
  "image_grayscale": image_grayscale,
  "diff_images": diff_images
}

What the code could have been:

import cv2
import numpy as np

Code Breakdown

Importing Libraries

import cv2
import numpy as np

The code starts by importing the necessary libraries:

Functions

1. percent_motion(thresh) - Calculate Motion Percentage

Calculates the percentage of white pixels in a thresholded image.

def percent_motion(thresh):
  white_pixels = np.count_nonzero(thresh == 255)
  total_pixels = thresh.size

  # Calculate percentage
  white_percentage = (white_pixels / total_pixels) * 100
  return white_percentage

2. image_grayscale(image) - Convert Image to Grayscale

Converts a BGR image to grayscale using OpenCV's cvtColor function.

def image_grayscale(image):
  gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  return gray_image

3. diff_images(prev_frame, frame) - Compute Difference Between Frames

Computes the absolute difference between two frames, thresholds it, and returns the thresholded image.

def diff_images(prev_frame, frame):
  # Compute absolute difference between current and previous frame
  diff = cv2.absdiff(prev_frame, frame)

  # Threshold the difference image
  _, thresh = cv2.threshold(diff, 30, 255, cv2.THRESH_BINARY)
  # Update previous frame
  # prev_frame = frame.copy()
  return thresh

Module Exports

__all__ = {
  "percent_motion": percent_motion,
  "image_grayscale": image_grayscale,
  "diff_images": diff_images
}

Exports the above functions as part of the module namespace.