lokesh341 commited on
Commit
e24639e
·
1 Parent(s): 631ee1f

Update services/plantation/missing_patch_check.py

Browse files
services/plantation/missing_patch_check.py CHANGED
@@ -1,46 +1,96 @@
1
  import cv2
2
  import numpy as np
 
3
  import os
4
  import logging
 
5
 
 
6
  logging.basicConfig(
7
  filename="app.log",
8
  level=logging.INFO,
9
  format="%(asctime)s - %(levelname)s - %(message)s"
10
  )
11
 
12
- def process_missing_patches(frame):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  try:
14
- gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
15
- _, plant_mask = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY_INV)
16
- contours, _ = cv2.findContours(plant_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
 
 
 
17
 
18
- detections = []
19
- line_counter = 1
20
 
21
- for contour in contours:
22
- area = cv2.contourArea(contour)
23
- if area < 500:
 
24
  continue
25
- x, y, w, h = cv2.boundingRect(contour)
26
- x_min, y_min, x_max, y_max = x, y, x + w, y + h
 
 
 
 
27
 
28
- detection_label = f"Line {line_counter} - Missing Patch"
29
  detections.append({
30
  "type": "missing_patch",
31
  "label": detection_label,
 
32
  "coordinates": [x_min, y_min, x_max, y_max]
33
  })
34
 
35
- color = (139, 69, 19) # Brown as requested
36
  cv2.rectangle(frame, (x_min, y_min), (x_max, y_max), color, 2)
37
- cv2.putText(frame, detection_label, (x_min, y_min - 10),
38
- cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2)
 
 
 
 
 
 
 
39
 
40
  line_counter += 1
41
 
42
- logging.info(f"Detected {len(detections)} missing patches in plantation.")
43
- return detections, frame
44
- except Exception as e:
45
- logging.error(f"Error detecting missing patches: {str(e)}")
46
- return [], frame
 
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 missing patch 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_missing_patches(frame: np.ndarray) -> Tuple[List[Dict[str, Any]], np.ndarray]:
29
+ """
30
+ Detect missing patches in plantation areas using YOLOv8n.
31
+
32
+ Args:
33
+ frame (np.ndarray): Input frame in BGR format.
34
+
35
+ Returns:
36
+ Tuple[List[Dict[str, Any]], np.ndarray]: A tuple containing:
37
+ - List of detected missing patches.
38
+ - Annotated frame with bounding boxes and labels.
39
+ """
40
+ # Validate input frame
41
+ if not isinstance(frame, np.ndarray) or frame.size == 0:
42
+ logging.error("Invalid input frame provided to missing_patch_check.")
43
+ return [], frame
44
+
45
+ # Check if model is loaded
46
+ if model is None:
47
+ logging.error("YOLO model not loaded. Skipping missing patch detection.")
48
+ return [], frame
49
+
50
  try:
51
+ # Perform YOLO inference
52
+ results = model(frame, verbose=False)
53
+ logging.debug("Completed YOLO inference for missing patch detection.")
54
+ except Exception as e:
55
+ logging.error(f"Error during YOLO inference: {str(e)}")
56
+ return [], frame
57
 
58
+ detections: List[Dict[str, Any]] = []
59
+ line_counter = 1
60
 
61
+ for r in results:
62
+ for box in r.boxes:
63
+ conf = float(box.conf[0])
64
+ if conf < 0.3:
65
  continue
66
+ cls = int(box.cls[0])
67
+ label = model.names[cls]
68
+ if label != "missing_patch":
69
+ continue
70
+ xyxy = box.xyxy[0].cpu().numpy().astype(int)
71
+ x_min, y_min, x_max, y_max = xyxy
72
 
73
+ detection_label = f"Line {line_counter} - Missing Patch (Conf: {conf:.2f})"
74
  detections.append({
75
  "type": "missing_patch",
76
  "label": detection_label,
77
+ "confidence": conf,
78
  "coordinates": [x_min, y_min, x_max, y_max]
79
  })
80
 
81
+ color = (255, 192, 203) # Pink for missing patches
82
  cv2.rectangle(frame, (x_min, y_min), (x_max, y_max), color, 2)
83
+ cv2.putText(
84
+ frame,
85
+ detection_label,
86
+ (x_min, y_min - 10),
87
+ cv2.FONT_HERSHEY_SIMPLEX,
88
+ 0.6,
89
+ color,
90
+ 2
91
+ )
92
 
93
  line_counter += 1
94
 
95
+ logging.info(f"Detected {len(detections)} missing patches in plantation.")
96
+ return detections, frame