Red Object Detection
This Python script captures images from a Raspberry Pi camera using PiCamera2 and analyzes them in real-time to detect the presence of red objects. It uses the HSV color space for more robust color detection.
Libaries
picamera2: Interface for the Raspberry Pi Camera Module.
cv2 (OpenCV): Image processing and computer vision tasks.
numpy: Efficient array operations, used here for masks and color thresholds.
time: Adds delays and manages timing.
Initialization
Initializes the camera and configures it for still image capture.
Waits for one second to ensure the camera is ready.
Main Loop
The loop runs continuously until the program is interrupted by the user (CTRL+C).
Image Capture and Color Conversion
Captures a frame from the camera.
Converts the image to HSV (Hue, Saturation, Value) color space, which is better suited for color segmentation than RGB.
Red Color Range Definition
Red spans two ranges in HSV: near 0° and near 180° hue values.
Two ranges are defined to cover the full red spectrum.
Mask Creation and Combination
Creates binary masks for each red range.
Combines the two masks into a single one that highlights all red areas.
Red Object Detection
Finds contours in the mask to identify red regions.
Loops through all contours and calculates their area using cv2.contourArea().
If any contour has an area greater than MIN_CONTOUR_AREA, a red object is considered detected. (MIN_CONTOUR_AREA is a configurable threshold value defined earlier in the code to control the sensitivity of red object detection.)
Output
Prints the detection result every second.
Adds a delay with time.sleep(1) to reduce processing load and output spam.
Graceful Exit
Handles manual termination (CTRL+C) with a user-friendly message.
Ensures the camera is properly stopped, whether the loop ends normally or due to an error/interruption.