Spaces:
Runtime error
Runtime error
import cv2 | |
import numpy as np | |
from typing import List, Tuple, Dict, Any | |
def process_plants(frame: np.ndarray) -> Tuple[List[Dict[str, Any]], np.ndarray]: | |
""" | |
Detect and count plants in the frame using color segmentation. | |
Args: | |
frame: Input frame as a numpy array. | |
Returns: | |
Tuple of (list of detections, annotated frame). | |
""" | |
# Convert to HSV color space for plant detection | |
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) | |
# Define range for green color (plants) | |
lower_green = np.array([35, 50, 50]) | |
upper_green = np.array([85, 255, 255]) | |
mask = cv2.inRange(hsv, lower_green, upper_green) | |
# Morphological operations to clean up the mask | |
kernel = np.ones((5, 5), np.uint8) | |
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel) | |
# Find contours of plants | |
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) | |
detections = [] | |
for i, contour in enumerate(contours): | |
area = cv2.contourArea(contour) | |
if area < 200: # Ignore small contours | |
continue | |
x, y, w, h = cv2.boundingRect(contour) | |
x_min, y_min, x_max, y_max = x, y, x + w, y + h | |
# Label as a plant | |
label = f"Plant {i+1}" | |
detections.append({ | |
"box": [x_min, y_min, x_max, y_max], | |
"label": label, | |
"type": "plant" | |
}) | |
return detections, frame |