Sure! Below is a Python script that uses OpenCV to detect red and green objects in a video stream, processes the detections in parallel using threading, and communicates the results to an Arduino via serial communication. The script follows your specifications:
- Detects red and green objects using binary masking.
- Processes green and red detection in separate threads.
- If both colors are detected, selects the one with the largest area.
- Sends
'l' for green, 'r' for red, and 'n' if no objects are detected to the Arduino.
Prerequisites
Before running the script, ensure you have the following installed:
- Python 3.x
- OpenCV: Install using
pip install opencv-python
- NumPy: Install using
pip install numpy
- PySerial: Install using
pip install pyserial
Script: color_detector.py
import cv2
import numpy as np
import threading
import serial
import time
# Configuration for serial communication
SERIAL_PORT = '/dev/ttyUSB0' # Update this to your Arduino's serial port
BAUD_RATE = 9600
SERIAL_TIMEOUT = 1 # seconds
# Initialize serial communication
try:
ser = serial.Serial(SERIAL_PORT, BAUD_RATE, timeout=SERIAL_TIMEOUT)
time.sleep(2) # Wait for the serial connection to initialize
print(f"Connected to Arduino on {SERIAL_PORT} at {BAUD_RATE} baud.")
except serial.SerialException as e:
print(f"Error connecting to serial port {SERIAL_PORT}: {e}")
ser = None
# Color range definitions in HSV
# You may need to adjust these ranges based on your lighting conditions and camera
GREEN_LOWER = np.array([40, 70, 70])
GREEN_UPPER = np.array([80, 255, 255])
# Red can wrap around the hue spectrum, so we define two ranges
RED_LOWER1 = np.array([0, 70, 50])
RED_UPPER1 = np.array([10, 255, 255])
RED_LOWER2 = np.array([170, 70, 50])
RED_UPPER2 = np.array([180, 255, 255])
# Shared data structure to store detection results
detection_results = {
'green_detected': False,
'green_area': 0,
'red_detected': False,
'red_area': 0
}
# Lock for thread-safe operations
lock = threading.Lock()
def detect_color(frame_hsv, color):
"""
Detects the specified color in the given HSV frame.
Updates the detection_results dictionary with detection status and area.
Args:
frame_hsv (numpy.ndarray): The HSV image.
color (str): 'green' or 'red'.
"""
mask = None
if color == 'green':
mask = cv2.inRange(frame_hsv, GREEN_LOWER, GREEN_UPPER)
elif color == 'red':
# Red has two ranges in HSV
mask1 = cv2.inRange(frame_hsv, RED_LOWER1, RED_UPPER1)
mask2 = cv2.inRange(frame_hsv, RED_LOWER2, RED_UPPER2)
mask = cv2.bitwise_or(mask1, mask2)
else:
return
# Optional: Clean up the mask using morphological operations
kernel = np.ones((5, 5), np.uint8)
mask_clean = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
mask_clean = cv2.morphologyEx(mask_clean, cv2.MORPH_DILATE, kernel)
# Find contours
contours, _ = cv2.findContours(mask_clean, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
max_area = 0
if contours:
# Find the contour with the largest area
max_contour = max(contours, key=cv2.contourArea)
max_area = cv2.contourArea(max_contour)
if max_area > 500: # Threshold area to avoid noise
with lock:
if color == 'green':
detection_results['green_detected'] = True
detection_results['green_area'] = max_area
elif color == 'red':
detection_results['red_detected'] = True
detection_results['red_area'] = max_area
return
# If no valid contour found
with lock:
if color == 'green':
detection_results['green_detected'] = False
detection_results['green_area'] = 0
elif color == 'red':
detection_results['red_detected'] = False
detection_results['red_area'] = 0
def main():
# Initialize video capture (0 for default camera)
cap = cv2.VideoCapture(0)
if not cap.isOpened():
print("Error: Could not open video stream.")
return
try:
while True:
ret, frame = cap.read()
if not ret:
print("Error: Failed to capture frame.")
break
# Resize the frame for faster processing (optional)
frame = cv2.resize(frame, (640, 480))
# Convert the frame to HSV color space
frame_hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
# Reset detection results
with lock:
detection_results['green_detected'] = False
detection_results['green_area'] = 0
detection_results['red_detected'] = False
detection_results['red_area'] = 0
# Create and start threads for green and red detection
threads = []
green_thread = threading.Thread(target=detect_color, args=(frame_hsv, 'green'))
red_thread = threading.Thread(target=detect_color, args=(frame_hsv, 'red'))
threads.append(green_thread)
threads.append(red_thread)
green_thread.start()
red_thread.start()
# Wait for both threads to finish
for t in threads:
t.join()
# Decide which color to send to Arduino
with lock:
green_detected = detection_results['green_detected']
green_area = detection_results['green_area']
red_detected = detection_results['red_detected']
red_area = detection_results['red_area']
if green_detected and red_detected:
if green_area > red_area:
color_to_send = 'l'
else:
color_to_send = 'r'
elif green_detected:
color_to_send = 'l'
elif red_detected:
color_to_send = 'r'
else:
color_to_send = 'n'
# Send the color to Arduino via serial
if ser and ser.is_open:
try:
ser.write(color_to_send.encode())
print(f"Sent '{color_to_send}' to Arduino.")
except serial.SerialException as e:
print(f"Error writing to serial port: {e}")
# Optional: Display the frame with detections
# Draw contours and display text
if green_detected:
cv2.putText(frame, 'Green Detected', (10, 30),
cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
if red_detected:
cv2.putText(frame, 'Red Detected', (10, 70),
cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
cv2.imshow('Color Detection', frame)
# Exit on pressing 'q'
if cv2.waitKey(1) & 0xFF == ord('q'):
break
finally:
# Cleanup
cap.release()
cv2.destroyAllWindows()
if ser and ser.is_open:
ser.close()
print("Serial connection closed.")
if __name__ == "__main__":
main()
Explanation of the Script
-
Imports and Configuration:
- OpenCV (
cv2) for image processing.
- NumPy (
np) for numerical operations.
- Threading for parallel processing.
- PySerial (
serial) for serial communication with Arduino.
- Time for delays during serial initialization.
-
Serial Communication Setup:
- Update the
SERIAL_PORT variable to match your Arduino's serial port (e.g., COM3 on Windows or /dev/ttyUSB0 on Linux).
- Initializes the serial connection and waits for 2 seconds to ensure the connection is established.
-
Color Range Definitions:
- Green: Defined in the HSV color space with lower and upper bounds.
- Red: Since red wraps around the hue spectrum in HSV, two ranges are defined and combined using a bitwise OR operation.
-
Detection Results Handling:
- A shared dictionary
detection_results stores whether green or red objects are detected and their corresponding areas.
- A thread lock ensures that updates to this dictionary are thread-safe.
-
detect_color Function:
- Takes an HSV frame and a color (
'green' or 'red') as input.
- Creates a binary mask for the specified color.
- Cleans the mask using morphological operations to reduce noise.
- Finds contours in the mask and identifies the largest contour.
- Updates the
detection_results with detection status and area if a significant contour is found.
-
Main Processing Loop (main Function):
- Captures video frames from the default camera.
- Converts each frame to the HSV color space.
- Resets detection results before processing a new frame.
- Starts two threads for green and red detection.
- Waits for both detection threads to complete.
- Determines which color to send to the Arduino based on detection results:
- If both colors are detected, sends the one with the larger area.
Usage Instructions
-
Connect Your Arduino:
- Ensure your Arduino is connected to the Raspberry Pi (or your computer) via USB.
- Update the
SERIAL_PORT variable in the script to match the Arduino's serial port.
-
Upload Arduino Sketch:
- Ensure that the Arduino is running a sketch that listens for serial input and processes the received characters
'l', 'r', and 'n' accordingly.
-
Run the Script:
python3 color_detector.py
- A window will display the live video feed with detection annotations.
- Press
'q' to exit the script.
Tips and Troubleshooting
-
Color Range Adjustment:
- Depending on your camera and lighting conditions, you might need to adjust the HSV color ranges (
GREEN_LOWER, GREEN_UPPER, RED_LOWER1, etc.) for optimal detection.
- You can use OpenCV's trackbars to dynamically adjust these values during testing.
-
Serial Port Identification:
- On Linux, serial ports are usually
/dev/ttyUSB0, /dev/ttyACM0, etc.
- On Windows, serial ports are typically
COM3, COM4, etc.
- Use device manager or
ls /dev/tty* on Linux to identify the correct port.
-
Serial Communication Errors:
- Ensure that no other program is accessing the serial port.
- If you encounter permission issues on Linux, you might need to add your user to the
dialout group or run the script with sudo (not generally recommended).
-
Performance Optimization:
- If the video feed is slow, consider resizing the frame to a smaller size or optimizing the detection thresholds.
- Running detections in separate threads can help utilize multiple cores, but Python's Global Interpreter Lock (GIL) may limit performance gains. For CPU-intensive tasks, consider using multiprocessing or other parallelization techniques.
-
Safety Considerations:
- Ensure that the communication between the Raspberry Pi and Arduino is robust to prevent unexpected behavior in connected hardware.
- Implement error handling on both the Python and Arduino sides to manage unexpected inputs or communication failures.
Conclusion
This script provides a foundation for detecting red and green objects in a video stream, processing the detections in parallel, and communicating the results to an Arduino. You can further enhance the script by adding features like calibration routines, logging, or integrating with other systems based on your project requirements.
Feel free to modify and expand upon this script to suit your specific needs!