Spaces:
Runtime error
Runtime error
File size: 1,458 Bytes
db53206 0e27a33 146e714 0e27a33 e529cf1 0e27a33 e529cf1 0e27a33 e529cf1 0e27a33 e529cf1 0e27a33 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
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 |