pranaya20 commited on
Commit
8ae2ea0
·
verified ·
1 Parent(s): 52e0735

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -0
app.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from ultralytics import YOLO
3
+ import torch
4
+ import cv2
5
+ import numpy as np
6
+ import wikipedia
7
+ from PIL import Image
8
+
9
+ # Load YOLO model for tree detection
10
+ yolo_model = YOLO("yolov8n.pt")
11
+
12
+ # Load MiDaS depth model
13
+ midas = torch.hub.load("intel-isl/MiDaS", "MiDaS_small")
14
+ midas.to("cpu").eval()
15
+ midas_transforms = torch.hub.load("intel-isl/MiDaS", "transforms").small
16
+
17
+ def estimate_tree_height(image):
18
+ # Convert image to OpenCV format
19
+ image = np.array(image)
20
+ image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
21
+
22
+ # Object Detection (Tree)
23
+ results = yolo_model(image_rgb)
24
+ boxes = results[0].boxes.xyxy.cpu().numpy() # Get bounding boxes
25
+ labels = results[0].boxes.cls.cpu().numpy()
26
+
27
+ tree_boxes = [box for box, label in zip(boxes, labels) if int(label) == 0] # class 0 usually means 'person/tree'
28
+
29
+ if not tree_boxes:
30
+ return "No tree detected", None, None
31
+
32
+ x1, y1, x2, y2 = tree_boxes[0]
33
+ tree_crop = image[int(y1):int(y2), int(x1):int(x2)]
34
+
35
+ # Depth estimation
36
+ input_tensor = midas_transforms(Image.fromarray(image_rgb)).to("cpu")
37
+ with torch.no_grad():
38
+ depth_map = midas(input_tensor.unsqueeze(0))[0]
39
+ depth_resized = torch.nn.functional.interpolate(
40
+ depth_map.unsqueeze(0),
41
+ size=image_rgb.shape[:2],
42
+ mode="bicubic",
43
+ align_corners=False
44
+ ).squeeze().cpu().numpy()
45
+
46
+ avg_depth = np.mean(depth_resized[int(y1):int(y2), int(x1):int(x2)])
47
+ estimated_height_m = avg_depth * 1.8 # arbitrary scaling for demo
48
+
49
+ # Wikipedia summary (simulate species info)
50
+ try:
51
+ summary = wikipedia.summary("tree", sentences=2)
52
+ except Exception:
53
+ summary = "Tree species information not available."
54
+
55
+ return f"Estimated Tree Height: {estimated_height_m:.2f} meters", Image.fromarray(tree_crop), summary
56
+
57
+ # Gradio Interface
58
+ demo = gr.Interface(
59
+ fn=estimate_tree_height,
60
+ inputs=gr.Image(type="pil"),
61
+ outputs=[
62
+ gr.Textbox(label="Tree Height Estimate"),
63
+ gr.Image(label="Detected Tree"),
64
+ gr.Textbox(label="Tree Species Info")
65
+ ],
66
+ title="🌳 Tree Measurement App",
67
+ description="Capture a tree image to estimate its height and get basic species info."
68
+ )
69
+
70
+ demo.launch()