lokesh341 commited on
Commit
0e27a33
·
verified ·
1 Parent(s): bb5ad16

Update services/plantation/plant_count.py

Browse files
Files changed (1) hide show
  1. services/plantation/plant_count.py +38 -60
services/plantation/plant_count.py CHANGED
@@ -1,67 +1,45 @@
1
  import cv2
2
  import numpy as np
3
- import logging
4
- from typing import List, Dict, Tuple
5
 
6
- # Setup logging
7
- logging.basicConfig(
8
- filename="app.log",
9
- level=logging.INFO,
10
- format="%(asctime)s - %(levelname)s - %(message)s"
11
- )
12
-
13
- def process_plants(frame: np.ndarray) -> Tuple[List[Dict], np.ndarray]:
14
  """
15
- Process a frame to count plants/trees using color-based segmentation.
16
  Args:
17
- frame: Input frame (BGR numpy array)
18
  Returns:
19
- Tuple: (List of detection dictionaries, annotated frame)
20
  """
21
- try:
22
- # Convert frame to HSV for better color segmentation
23
- hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
24
-
25
- # Define range for green color (trees/plants)
26
- lower_green = np.array([35, 40, 40])
27
- upper_green = np.array([85, 255, 255])
28
- mask = cv2.inRange(hsv, lower_green, upper_green)
29
-
30
- # Morphological operations to reduce noise
31
- kernel = np.ones((5, 5), np.uint8)
32
- mask = cv2.erode(mask, kernel, iterations=1)
33
- mask = cv2.dilate(mask, kernel, iterations=1)
34
-
35
- # Find contours of green regions (trees)
36
- contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
37
-
38
- detections = []
39
- for idx, contour in enumerate(contours):
40
- # Filter small contours (noise)
41
- area = cv2.contourArea(contour)
42
- if area < 300: # Minimum area threshold
43
- continue
44
-
45
- # Get bounding box
46
- x, y, w, h = cv2.boundingRect(contour)
47
- x_min, y_min, x_max, y_max = x, y, x + w, y + h
48
-
49
- # Add detection
50
- detections.append({
51
- "type": "plant",
52
- "label": f"Plant {idx + 1}",
53
- "box": [x_min, y_min, x_max, y_max],
54
- "confidence": 0.9 # Simulated confidence
55
- })
56
-
57
- # Draw bounding box and label on frame
58
- cv2.rectangle(frame, (x_min, y_min), (x_max, y_max), (0, 255, 0), 2)
59
- cv2.putText(frame, f"Plant {idx + 1}", (x_min, y_min - 10),
60
- cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
61
-
62
- logging.info(f"Detected {len(detections)} plants in frame.")
63
- return detections, frame
64
-
65
- except Exception as e:
66
- logging.error(f"Error in plant counting: {str(e)}")
67
- return [], frame
 
1
  import cv2
2
  import numpy as np
3
+ from typing import List, Tuple, Dict, Any
 
4
 
5
+ def process_plants(frame: np.ndarray) -> Tuple[List[Dict[str, Any]], np.ndarray]:
 
 
 
 
 
 
 
6
  """
7
+ Detect and count plants in the frame using color segmentation.
8
  Args:
9
+ frame: Input frame as a numpy array.
10
  Returns:
11
+ Tuple of (list of detections, annotated frame).
12
  """
13
+ # Convert to HSV color space for plant detection
14
+ hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
15
+
16
+ # Define range for green color (plants)
17
+ lower_green = np.array([35, 50, 50])
18
+ upper_green = np.array([85, 255, 255])
19
+ mask = cv2.inRange(hsv, lower_green, upper_green)
20
+
21
+ # Morphological operations to clean up the mask
22
+ kernel = np.ones((5, 5), np.uint8)
23
+ mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
24
+
25
+ # Find contours of plants
26
+ contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
27
+
28
+ detections = []
29
+ for i, contour in enumerate(contours):
30
+ area = cv2.contourArea(contour)
31
+ if area < 200: # Ignore small contours
32
+ continue
33
+
34
+ x, y, w, h = cv2.boundingRect(contour)
35
+ x_min, y_min, x_max, y_max = x, y, x + w, y + h
36
+
37
+ # Label as a plant
38
+ label = f"Plant {i+1}"
39
+ detections.append({
40
+ "box": [x_min, y_min, x_max, y_max],
41
+ "label": label,
42
+ "type": "plant"
43
+ })
44
+
45
+ return detections, frame