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

Update services/plantation/plant_health.py

Browse files
Files changed (1) hide show
  1. services/plantation/plant_health.py +54 -70
services/plantation/plant_health.py CHANGED
@@ -1,77 +1,61 @@
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_plant_health(frame: np.ndarray) -> Tuple[List[Dict], np.ndarray]:
14
  """
15
- Process a frame to assess plant health based on color.
16
  Args:
17
- frame: Input frame (BGR numpy array)
18
  Returns:
19
- Tuple: (List of detection dictionaries with health status, annotated frame)
20
  """
21
- try:
22
- # Convert frame to HSV
23
- hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
24
-
25
- # Define range for green (healthy) and yellow/brown (unhealthy)
26
- lower_green = np.array([35, 40, 40])
27
- upper_green = np.array([85, 255, 255])
28
- green_mask = cv2.inRange(hsv, lower_green, upper_green)
29
-
30
- # Define range for yellow/brown (unhealthy)
31
- lower_unhealthy = np.array([20, 40, 40])
32
- upper_unhealthy = np.array([35, 255, 255])
33
- unhealthy_mask = cv2.inRange(hsv, lower_unhealthy, upper_unhealthy)
34
-
35
- detections = []
36
- # Process green regions (healthy plants)
37
- contours, _ = cv2.findContours(green_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
38
- for idx, contour in enumerate(contours):
39
- area = cv2.contourArea(contour)
40
- if area < 300:
41
- continue
42
- x, y, w, h = cv2.boundingRect(contour)
43
- x_min, y_min, x_max, y_max = x, y, x + w, y + h
44
- detections.append({
45
- "type": "plant",
46
- "label": f"Plant {idx + 1} - Healthy",
47
- "box": [x_min, y_min, x_max, y_max],
48
- "health": "Healthy"
49
- })
50
- cv2.rectangle(frame, (x_min, y_min), (x_max, y_max), (0, 255, 0), 2)
51
- cv2.putText(frame, "Healthy", (x_min, y_min - 10),
52
- cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
53
-
54
- # Process unhealthy regions
55
- contours, _ = cv2.findContours(unhealthy_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
56
- for idx, contour in enumerate(contours):
57
- area = cv2.contourArea(contour)
58
- if area < 300:
59
- continue
60
- x, y, w, h = cv2.boundingRect(contour)
61
- x_min, y_min, x_max, y_max = x, y, x + w, y + h
62
- detections.append({
63
- "type": "plant",
64
- "label": f"Plant {idx + 1} - Unhealthy",
65
- "box": [x_min, y_min, x_max, y_max],
66
- "health": "Unhealthy"
67
- })
68
- cv2.rectangle(frame, (x_min, y_min), (x_max, y_max), (255, 0, 0), 2)
69
- cv2.putText(frame, "Unhealthy", (x_min, y_min - 10),
70
- cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
71
-
72
- logging.info(f"Assessed health of {len(detections)} plants in frame.")
73
- return detections, frame
74
-
75
- except Exception as e:
76
- logging.error(f"Error in plant health assessment: {str(e)}")
77
- return [], frame
 
1
  import cv2
2
  import numpy as np
3
+ from typing import List, Tuple, Dict, Any
 
4
 
5
+ def process_plant_health(frame: np.ndarray) -> Tuple[List[Dict[str, Any]], np.ndarray]:
 
 
 
 
 
 
 
6
  """
7
+ Assess the health of plants in the frame based on color.
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
14
+ hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
15
+
16
+ # Define range for green (healthy) and yellow/brown (unhealthy)
17
+ lower_green = np.array([35, 50, 50])
18
+ upper_green = np.array([85, 255, 255])
19
+ lower_unhealthy = np.array([20, 50, 50])
20
+ upper_unhealthy = np.array([35, 255, 255])
21
+
22
+ mask_healthy = cv2.inRange(hsv, lower_green, upper_green)
23
+ mask_unhealthy = cv2.inRange(hsv, lower_unhealthy, upper_unhealthy)
24
+
25
+ # Combine masks to find plants
26
+ mask = cv2.bitwise_or(mask_healthy, mask_unhealthy)
27
+ kernel = np.ones((5, 5), np.uint8)
28
+ mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
29
+
30
+ # Find contours of plants
31
+ contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
32
+
33
+ detections = []
34
+ for i, contour in enumerate(contours):
35
+ area = cv2.contourArea(contour)
36
+ if area < 200: # Ignore small contours
37
+ continue
38
+
39
+ x, y, w, h = cv2.boundingRect(contour)
40
+ x_min, y_min, x_max, y_max = x, y, x + w, y + h
41
+
42
+ # Determine health by comparing the area of healthy vs unhealthy pixels
43
+ roi_hsv = hsv[y_min:y_max, x_min:x_max]
44
+ healthy_pixels = cv2.countNonZero(cv2.inRange(roi_hsv, lower_green, upper_green))
45
+ unhealthy_pixels = cv2.countNonZero(cv2.inRange(roi_hsv, lower_unhealthy, upper_unhealthy))
46
+ total_pixels = healthy_pixels + unhealthy_pixels
47
+
48
+ if total_pixels == 0:
49
+ continue
50
+
51
+ health_status = "healthy" if healthy_pixels > unhealthy_pixels else "unhealthy"
52
+ label = f"Plant {i+1} - {health_status.capitalize()}"
53
+
54
+ detections.append({
55
+ "box": [x_min, y_min, x_max, y_max],
56
+ "label": label,
57
+ "type": "plant",
58
+ "health": health_status
59
+ })
60
+
61
+ return detections, frame