Alessio Grancini
commited on
Update app.py
Browse files
app.py
CHANGED
@@ -1,11 +1,11 @@
|
|
|
|
1 |
import cv2
|
2 |
import gradio as gr
|
3 |
import numpy as np
|
4 |
import os
|
|
|
5 |
import utils
|
6 |
import plotly.graph_objects as go
|
7 |
-
import spaces
|
8 |
-
import torch
|
9 |
|
10 |
from image_segmenter import ImageSegmenter
|
11 |
from monocular_depth_estimator import MonocularDepthEstimator
|
@@ -14,155 +14,85 @@ from point_cloud_generator import display_pcd
|
|
14 |
# params
|
15 |
CANCEL_PROCESSING = False
|
16 |
|
17 |
-
|
18 |
-
|
19 |
-
depth_estimator = None
|
20 |
-
|
21 |
-
def initialize_models():
|
22 |
-
"""Loads models onto GPU if available, otherwise falls back to CPU."""
|
23 |
-
global img_seg, depth_estimator
|
24 |
-
device = "cuda" if torch.cuda.is_available() else "cpu"
|
25 |
-
|
26 |
-
if img_seg is None:
|
27 |
-
print(f"🔹 Loading ImageSegmenter model on {device}...")
|
28 |
-
img_seg = ImageSegmenter(model_type="yolov8s-seg", device=device)
|
29 |
-
|
30 |
-
if depth_estimator is None:
|
31 |
-
print(f"🔹 Loading Depth Estimator model on {device}...")
|
32 |
-
depth_estimator = MonocularDepthEstimator(model_type="midas_v21_small_256", device=device)
|
33 |
-
|
34 |
-
|
35 |
-
def safe_gpu_decorator(func):
|
36 |
-
"""Custom decorator to handle GPU operations safely"""
|
37 |
-
def wrapper(*args, **kwargs):
|
38 |
-
try:
|
39 |
-
return func(*args, **kwargs)
|
40 |
-
except RuntimeError as e:
|
41 |
-
if "cudaGetDeviceCount" in str(e):
|
42 |
-
print("GPU initialization failed, falling back to CPU")
|
43 |
-
# Set environment variable to force CPU
|
44 |
-
os.environ['CUDA_VISIBLE_DEVICES'] = ''
|
45 |
-
return func(*args, **kwargs)
|
46 |
-
raise
|
47 |
-
return wrapper
|
48 |
-
|
49 |
-
@safe_gpu_decorator
|
50 |
-
def process_image(image):
|
51 |
-
try:
|
52 |
-
print("🚀 Starting image processing...")
|
53 |
-
initialize_models()
|
54 |
-
|
55 |
-
if torch.cuda.is_available():
|
56 |
-
print("✅ Using GPU for processing")
|
57 |
-
torch.set_default_tensor_type(torch.cuda.FloatTensor)
|
58 |
-
else:
|
59 |
-
print("⚠️ Using CPU for processing")
|
60 |
-
|
61 |
-
# Process image
|
62 |
-
image = utils.resize(image)
|
63 |
-
image_segmentation, objects_data = img_seg.predict(image)
|
64 |
-
depthmap, depth_colormap = depth_estimator.make_prediction(image)
|
65 |
-
dist_image = utils.draw_depth_info(image, depthmap, objects_data)
|
66 |
-
objs_pcd = utils.generate_obj_pcd(depthmap, objects_data)
|
67 |
-
plot_fig = display_pcd(objs_pcd)
|
68 |
-
|
69 |
-
return image_segmentation, depth_colormap, dist_image, plot_fig
|
70 |
-
|
71 |
-
except RuntimeError as e:
|
72 |
-
print(f"🚨 RuntimeError in process_image: {e}")
|
73 |
-
|
74 |
-
if "cuda" in str(e).lower():
|
75 |
-
print("⚠️ CUDA error detected. Switching to CPU mode.")
|
76 |
-
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
|
77 |
-
|
78 |
-
import traceback
|
79 |
-
print(traceback.format_exc())
|
80 |
-
raise
|
81 |
-
|
82 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
83 |
|
84 |
-
@safe_gpu_decorator
|
85 |
def test_process_img(image):
|
86 |
-
initialize_models()
|
87 |
image = utils.resize(image)
|
88 |
image_segmentation, objects_data = img_seg.predict(image)
|
89 |
depthmap, depth_colormap = depth_estimator.make_prediction(image)
|
90 |
return image_segmentation, objects_data, depthmap, depth_colormap
|
91 |
|
92 |
-
@safe_gpu_decorator
|
93 |
def process_video(vid_path=None):
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
vid_cap.release()
|
108 |
-
return None
|
109 |
-
except Exception as e:
|
110 |
-
print(f"Error in process_video: {str(e)}")
|
111 |
-
import traceback
|
112 |
-
print(traceback.format_exc())
|
113 |
-
raise
|
114 |
|
115 |
def update_segmentation_options(options):
|
116 |
-
initialize_models()
|
117 |
img_seg.is_show_bounding_boxes = True if 'Show Boundary Box' in options else False
|
118 |
img_seg.is_show_segmentation = True if 'Show Segmentation Region' in options else False
|
119 |
img_seg.is_show_segmentation_boundary = True if 'Show Segmentation Boundary' in options else False
|
120 |
|
121 |
def update_confidence_threshold(thres_val):
|
122 |
-
initialize_models()
|
123 |
img_seg.confidence_threshold = thres_val/100
|
124 |
|
125 |
-
@safe_gpu_decorator
|
126 |
def model_selector(model_type):
|
127 |
-
global img_seg, depth_estimator
|
128 |
-
device = "cuda" if torch.cuda.is_available() else "cpu"
|
129 |
-
|
130 |
-
model_dict = {
|
131 |
-
"Small - Better performance and less accuracy": ("midas_v21_small_256", "yolov8s-seg"),
|
132 |
-
"Medium - Balanced performance and accuracy": ("dpt_hybrid_384", "yolov8m-seg"),
|
133 |
-
"Large - Slow performance and high accuracy": ("dpt_large_384", "yolov8l-seg"),
|
134 |
-
}
|
135 |
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
|
|
|
|
142 |
|
|
|
|
|
143 |
|
144 |
def cancel():
|
145 |
-
global CANCEL_PROCESSING
|
146 |
CANCEL_PROCESSING = True
|
147 |
|
148 |
if __name__ == "__main__":
|
149 |
-
# Ensure CUDA is properly initialized
|
150 |
-
try:
|
151 |
-
if torch.cuda.is_available():
|
152 |
-
print(f"✅ CUDA is available: {torch.cuda.get_device_name(0)}")
|
153 |
-
device = torch.device("cuda")
|
154 |
-
torch.cuda.empty_cache() # Clear GPU cache
|
155 |
-
else:
|
156 |
-
print("❌ No CUDA available. Falling back to CPU.")
|
157 |
-
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
|
158 |
-
device = torch.device("cpu")
|
159 |
-
except RuntimeError as e:
|
160 |
-
print(f"🚨 CUDA initialization failed: {e}. Switching to CPU mode.")
|
161 |
-
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
|
162 |
-
device = torch.device("cpu")
|
163 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
164 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
165 |
with gr.Blocks() as my_app:
|
|
|
166 |
# title
|
167 |
gr.Markdown("<h1><center>Simultaneous Segmentation and Depth Estimation</center></h1>")
|
168 |
gr.Markdown("<h3><center>Created by Vaishanth</center></h3>")
|
@@ -192,6 +122,7 @@ if __name__ == "__main__":
|
|
192 |
dist_img_output = gr.Image(height=300, label="Distance")
|
193 |
pcd_img_output = gr.Plot(label="Point Cloud")
|
194 |
|
|
|
195 |
gr.Examples(
|
196 |
examples=[os.path.join(os.path.dirname(__file__), "assets/images/baggage_claim.jpg"),
|
197 |
os.path.join(os.path.dirname(__file__), "assets/images/kitchen_2.png"),
|
@@ -229,13 +160,17 @@ if __name__ == "__main__":
|
|
229 |
with gr.Row():
|
230 |
dist_vid_output = gr.Image(height=300, label="Distance")
|
231 |
|
|
|
232 |
gr.Examples(
|
233 |
examples=[os.path.join(os.path.dirname(__file__), "assets/videos/input_video.mp4"),
|
234 |
os.path.join(os.path.dirname(__file__), "assets/videos/driving.mp4"),
|
235 |
os.path.join(os.path.dirname(__file__), "assets/videos/overpass.mp4"),
|
236 |
os.path.join(os.path.dirname(__file__), "assets/videos/walking.mp4")],
|
237 |
inputs=vid_input,
|
|
|
|
|
238 |
)
|
|
|
239 |
|
240 |
# image tab logic
|
241 |
submit_btn_img.click(process_image, inputs=img_input, outputs=[segmentation_img_output, depth_img_output, dist_img_output, pcd_img_output])
|
@@ -250,4 +185,5 @@ if __name__ == "__main__":
|
|
250 |
options_checkbox_vid.change(update_segmentation_options, options_checkbox_vid, [])
|
251 |
conf_thres_vid.change(update_confidence_threshold, conf_thres_vid, [])
|
252 |
|
253 |
-
|
|
|
|
1 |
+
from ultralytics import YOLO
|
2 |
import cv2
|
3 |
import gradio as gr
|
4 |
import numpy as np
|
5 |
import os
|
6 |
+
import torch
|
7 |
import utils
|
8 |
import plotly.graph_objects as go
|
|
|
|
|
9 |
|
10 |
from image_segmenter import ImageSegmenter
|
11 |
from monocular_depth_estimator import MonocularDepthEstimator
|
|
|
14 |
# params
|
15 |
CANCEL_PROCESSING = False
|
16 |
|
17 |
+
img_seg = ImageSegmenter(model_type="yolov8s-seg")
|
18 |
+
depth_estimator = MonocularDepthEstimator(model_type="midas_v21_small_256")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
19 |
|
20 |
+
def process_image(image):
|
21 |
+
image = utils.resize(image)
|
22 |
+
image_segmentation, objects_data = img_seg.predict(image)
|
23 |
+
depthmap, depth_colormap = depth_estimator.make_prediction(image)
|
24 |
+
dist_image = utils.draw_depth_info(image, depthmap, objects_data)
|
25 |
+
objs_pcd = utils.generate_obj_pcd(depthmap, objects_data)
|
26 |
+
plot_fig = display_pcd(objs_pcd)
|
27 |
+
return image_segmentation, depth_colormap, dist_image, plot_fig
|
28 |
|
|
|
29 |
def test_process_img(image):
|
|
|
30 |
image = utils.resize(image)
|
31 |
image_segmentation, objects_data = img_seg.predict(image)
|
32 |
depthmap, depth_colormap = depth_estimator.make_prediction(image)
|
33 |
return image_segmentation, objects_data, depthmap, depth_colormap
|
34 |
|
|
|
35 |
def process_video(vid_path=None):
|
36 |
+
vid_cap = cv2.VideoCapture(vid_path)
|
37 |
+
while vid_cap.isOpened():
|
38 |
+
ret, frame = vid_cap.read()
|
39 |
+
if ret:
|
40 |
+
print("making predictions ....")
|
41 |
+
frame = utils.resize(frame)
|
42 |
+
image_segmentation, objects_data = img_seg.predict(frame)
|
43 |
+
depthmap, depth_colormap = depth_estimator.make_prediction(frame)
|
44 |
+
dist_image = utils.draw_depth_info(frame, depthmap, objects_data)
|
45 |
+
yield cv2.cvtColor(image_segmentation, cv2.COLOR_BGR2RGB), depth_colormap, cv2.cvtColor(dist_image, cv2.COLOR_BGR2RGB)
|
46 |
+
|
47 |
+
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
48 |
|
49 |
def update_segmentation_options(options):
|
|
|
50 |
img_seg.is_show_bounding_boxes = True if 'Show Boundary Box' in options else False
|
51 |
img_seg.is_show_segmentation = True if 'Show Segmentation Region' in options else False
|
52 |
img_seg.is_show_segmentation_boundary = True if 'Show Segmentation Boundary' in options else False
|
53 |
|
54 |
def update_confidence_threshold(thres_val):
|
|
|
55 |
img_seg.confidence_threshold = thres_val/100
|
56 |
|
|
|
57 |
def model_selector(model_type):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
58 |
|
59 |
+
if "Small - Better performance and less accuracy" == model_type:
|
60 |
+
midas_model, yolo_model = "midas_v21_small_256", "yolov8s-seg"
|
61 |
+
elif "Medium - Balanced performance and accuracy" == model_type:
|
62 |
+
midas_model, yolo_model = "dpt_hybrid_384", "yolov8m-seg"
|
63 |
+
elif "Large - Slow performance and high accuracy" == model_type:
|
64 |
+
midas_model, yolo_model = "dpt_large_384", "yolov8l-seg"
|
65 |
+
else:
|
66 |
+
midas_model, yolo_model = "midas_v21_small_256", "yolov8s-seg"
|
67 |
|
68 |
+
img_seg = ImageSegmenter(model_type=yolo_model)
|
69 |
+
depth_estimator = MonocularDepthEstimator(model_type=midas_model)
|
70 |
|
71 |
def cancel():
|
|
|
72 |
CANCEL_PROCESSING = True
|
73 |
|
74 |
if __name__ == "__main__":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
75 |
|
76 |
+
# testing
|
77 |
+
# img_1 = cv2.imread("assets/images/bus.jpg")
|
78 |
+
# img_1 = utils.resize(img_1)
|
79 |
+
|
80 |
+
# image_segmentation, objects_data, depthmap, depth_colormap = test_process_img(img_1)
|
81 |
+
# final_image = utils.draw_depth_info(image_segmentation, depthmap, objects_data)
|
82 |
+
# objs_pcd = utils.generate_obj_pcd(depthmap, objects_data)
|
83 |
+
# # print(objs_pcd[0][0])
|
84 |
+
# display_pcd(objs_pcd, use_matplotlib=True)
|
85 |
|
86 |
+
# cv2.imshow("Segmentation", image_segmentation)
|
87 |
+
# cv2.imshow("Depth", depthmap*objects_data[2][3])
|
88 |
+
# cv2.imshow("Final", final_image)
|
89 |
+
|
90 |
+
# cv2.waitKey(0)
|
91 |
+
# cv2.destroyAllWindows()
|
92 |
+
|
93 |
+
# gradio gui app
|
94 |
with gr.Blocks() as my_app:
|
95 |
+
|
96 |
# title
|
97 |
gr.Markdown("<h1><center>Simultaneous Segmentation and Depth Estimation</center></h1>")
|
98 |
gr.Markdown("<h3><center>Created by Vaishanth</center></h3>")
|
|
|
122 |
dist_img_output = gr.Image(height=300, label="Distance")
|
123 |
pcd_img_output = gr.Plot(label="Point Cloud")
|
124 |
|
125 |
+
gr.Markdown("## Sample Images")
|
126 |
gr.Examples(
|
127 |
examples=[os.path.join(os.path.dirname(__file__), "assets/images/baggage_claim.jpg"),
|
128 |
os.path.join(os.path.dirname(__file__), "assets/images/kitchen_2.png"),
|
|
|
160 |
with gr.Row():
|
161 |
dist_vid_output = gr.Image(height=300, label="Distance")
|
162 |
|
163 |
+
gr.Markdown("## Sample Videos")
|
164 |
gr.Examples(
|
165 |
examples=[os.path.join(os.path.dirname(__file__), "assets/videos/input_video.mp4"),
|
166 |
os.path.join(os.path.dirname(__file__), "assets/videos/driving.mp4"),
|
167 |
os.path.join(os.path.dirname(__file__), "assets/videos/overpass.mp4"),
|
168 |
os.path.join(os.path.dirname(__file__), "assets/videos/walking.mp4")],
|
169 |
inputs=vid_input,
|
170 |
+
# outputs=vid_output,
|
171 |
+
# fn=vid_segmenation,
|
172 |
)
|
173 |
+
|
174 |
|
175 |
# image tab logic
|
176 |
submit_btn_img.click(process_image, inputs=img_input, outputs=[segmentation_img_output, depth_img_output, dist_img_output, pcd_img_output])
|
|
|
185 |
options_checkbox_vid.change(update_segmentation_options, options_checkbox_vid, [])
|
186 |
conf_thres_vid.change(update_confidence_threshold, conf_thres_vid, [])
|
187 |
|
188 |
+
|
189 |
+
my_app.queue(concurrency_count=5, max_size=20).launch()
|