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.
npm run import -- "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
}
import cv2
import numpy as np
import cv2
import numpy as np
The code starts by importing the necessary libraries:
cv2
: OpenCV library for computer vision tasks.numpy
(as np
): library for efficient numerical computations.percent_motion(thresh)
- Calculate Motion PercentageCalculates 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
image_grayscale(image)
- Convert Image to GrayscaleConverts 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
diff_images(prev_frame, frame)
- Compute Difference Between FramesComputes 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
__all__ = {
"percent_motion": percent_motion,
"image_grayscale": image_grayscale,
"diff_images": diff_images
}
Exports the above functions as part of the module namespace.