lokesh341 commited on
Commit
e529cf1
·
verified ·
1 Parent(s): 8053086

Update services/plantation/plant_count.py

Browse files
Files changed (1) hide show
  1. services/plantation/plant_count.py +47 -65
services/plantation/plant_count.py CHANGED
@@ -1,85 +1,67 @@
1
  import cv2
2
  import numpy as np
3
- from ultralytics import YOLO
4
- import os
5
  import logging
6
- from typing import Tuple, List, Dict, Any
7
 
8
- # Configure logging
9
  logging.basicConfig(
10
  filename="app.log",
11
  level=logging.INFO,
12
  format="%(asctime)s - %(levelname)s - %(message)s"
13
  )
14
 
15
- # Define base directory and model path
16
- BASE_DIR = os.path.dirname(os.path.abspath(__file__))
17
- MODEL_PATH = os.path.abspath(os.path.join(BASE_DIR, "../../models/yolov8n.pt"))
18
-
19
- # Initialize YOLO model
20
- try:
21
- model = YOLO(MODEL_PATH)
22
- logging.info("Loaded YOLOv8n model for plant detection.")
23
- logging.info(f"Model class names: {model.names}")
24
- except Exception as e:
25
- logging.error(f"Failed to load YOLOv8n model: {str(e)}")
26
- model = None
27
-
28
- def process_plants(frame: np.ndarray) -> Tuple[List[Dict[str, Any]], np.ndarray]:
29
- # Validate input frame
30
- if not isinstance(frame, np.ndarray) or frame.size == 0:
31
- logging.error("Invalid input frame provided to plant_count.")
32
- return [], frame
33
 
34
- # Check if model is loaded
35
- if model is None:
36
- logging.error("YOLO model not loaded. Skipping plant detection.")
37
- return [], frame
38
 
39
- try:
40
- # Perform YOLO inference
41
- results = model(frame, verbose=False)
42
- logging.debug("Completed YOLO inference for plant detection.")
43
- except Exception as e:
44
- logging.error(f"Error during YOLO inference: {str(e)}")
45
- return [], frame
46
 
47
- detections: List[Dict[str, Any]] = []
48
- line_counter = 1
49
 
50
- for r in results:
51
- for box in r.boxes:
52
- conf = float(box.conf[0])
53
- if conf < 0.3:
 
54
  continue
55
- cls = int(box.cls[0])
56
- label = model.names[cls]
57
- if label != "plant":
58
- continue
59
- xyxy = box.xyxy[0].cpu().numpy().astype(int)
60
- x_min, y_min, x_max, y_max = xyxy
61
 
62
- detection_label = f"Line {line_counter} - {label.capitalize()} (Conf: {conf:.2f})"
 
 
 
 
63
  detections.append({
64
- "type": label,
65
- "label": detection_label,
66
- "confidence": conf,
67
- "coordinates": [x_min, y_min, x_max, y_max]
68
  })
69
 
70
- color = (255, 165, 0) # Orange for plants
71
- cv2.rectangle(frame, (x_min, y_min), (x_max, y_max), color, 2)
72
- cv2.putText(
73
- frame,
74
- detection_label,
75
- (x_min, y_min - 10),
76
- cv2.FONT_HERSHEY_SIMPLEX,
77
- 0.6,
78
- color,
79
- 2
80
- )
81
-
82
- line_counter += 1
83
 
84
- logging.info(f"Detected {len(detections)} plants in plantation.")
85
- return detections, frame
 
 
 
 
 
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