lokesh341 commited on
Commit
b69a1f8
·
1 Parent(s): db53206

Create plant_health.py

Browse files
Files changed (1) hide show
  1. services/plantation/plant_health.py +62 -0
services/plantation/plant_health.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # services/plantation/plant_health.py
2
+ import cv2
3
+ import numpy as np
4
+ import os
5
+
6
+ def compute_vari(frame):
7
+ """
8
+ Compute VARI (Visible Atmospherically Resistant Index) to assess plant health.
9
+ Args:
10
+ frame: Input frame (numpy array)
11
+ Returns:
12
+ dict: Detection results with numbered labels for unhealthy areas
13
+ numpy array: Annotated frame
14
+ """
15
+ # Convert to RGB
16
+ frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
17
+ r, g, b = cv2.split(frame_rgb)
18
+
19
+ # Compute VARI: (Green - Red) / (Green + Red - Blue)
20
+ denominator = (g.astype(float) + r.astype(float) - b.astype(float))
21
+ denominator[denominator == 0] = 1e-10 # Avoid division by zero
22
+ vari = (g.astype(float) - r.astype(float)) / denominator
23
+
24
+ # Threshold to find unhealthy areas (VARI < 0 indicates poor health)
25
+ unhealthy_mask = vari < 0
26
+ contours, _ = cv2.findContours(unhealthy_mask.astype(np.uint8),
27
+ cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
28
+
29
+ detections = []
30
+ line_counter = 1 # Initialize counter for numbered labels
31
+
32
+ # Process unhealthy areas
33
+ for contour in contours:
34
+ area = cv2.contourArea(contour)
35
+ if area < 50: # Filter small areas
36
+ continue
37
+ x, y, w, h = cv2.boundingRect(contour)
38
+ x_min, y_min, x_max, y_max = x, y, x + w, y + h
39
+
40
+ # Add numbered label
41
+ detection_label = f"Line {line_counter} - Unhealthy Vegetation"
42
+ detections.append({
43
+ "label": detection_label,
44
+ "coordinates": [x_min, y_min, x_max, y_max]
45
+ })
46
+
47
+ # Draw bounding box and label
48
+ color = (255, 0, 0) # Red for unhealthy areas
49
+ cv2.rectangle(frame, (x_min, y_min), (x_max, y_max), color, 2)
50
+ cv2.putText(frame, detection_label, (x_min, y_min - 10),
51
+ cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
52
+
53
+ line_counter += 1
54
+
55
+ return {"detections": detections, "frame": frame}
56
+
57
+ def process_plant_health(frame):
58
+ """
59
+ Wrapper function for integration with app.py.
60
+ """
61
+ result = compute_vari(frame)
62
+ return result["detections"], result["frame"]