feuerblitz7 commited on
Commit
7c0ff97
·
1 Parent(s): e19e5d8

Initial commit

Browse files
Files changed (3) hide show
  1. README.md +1 -1
  2. app.py +223 -0
  3. requirements.txt +107 -0
README.md CHANGED
@@ -1,5 +1,5 @@
1
  ---
2
- title: Microvision Model
3
  emoji: 🌍
4
  colorFrom: red
5
  colorTo: red
 
1
  ---
2
+ title: MicroVision Model
3
  emoji: 🌍
4
  colorFrom: red
5
  colorTo: red
app.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ import numpy as np
4
+ from PIL import Image
5
+
6
+ from huggingface_hub import hf_hub_download
7
+ import os
8
+
9
+ import supervision as sv
10
+
11
+ from ultralytics import YOLO
12
+
13
+ from detectron2.engine import DefaultPredictor
14
+ from detectron2.config import get_cfg
15
+ from detectron2.data.datasets import register_coco_instances
16
+ from detectron2 import model_zoo
17
+
18
+ try:
19
+ from rfdetr import RFDETRLarge
20
+ except ImportError:
21
+ RFDETR = None
22
+
23
+ # TODO: Check why small caps for YOLO11 model!
24
+
25
+ class_names = {0: "Pedestrian", 1: "Bicycle", 2: "Cyclist", 3: "E-Scooter", 4: "E-Scooterist"}
26
+
27
+ PATH_CFG_FASTER_RCNN = "COCO-Detection/faster_rcnn_X_101_32x8d_FPN_3x.yaml"
28
+
29
+ def hex_to_rgb(hex_str):
30
+ hex_str = hex_str.lstrip('#')
31
+ return tuple(int(hex_str[i:i+2], 16) for i in (0, 2, 4))
32
+
33
+ tab10_hex = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd']
34
+ rgb_colors = [hex_to_rgb(h) for h in tab10_hex]
35
+
36
+ bgr_colors = [sv.Color(r=b, g=g, b=r) for r, g, b in rgb_colors]
37
+
38
+ colors = sv.ColorPalette(colors=bgr_colors)
39
+
40
+ models = {
41
+ "YOLO11x": None,
42
+ "Faster R-CNN": None,
43
+ "RF-DETR": None
44
+ }
45
+
46
+ # You only need to set this if the models are PRIVATE
47
+ # HF_TOKEN = os.getenv("HF_TOKEN")
48
+
49
+ def get_model_path(repo_id, filename):
50
+ """Downloads model from HF Hub and returns local path."""
51
+ return hf_hub_download(
52
+ repo_id=repo_id,
53
+ filename=filename,
54
+ # token=HF_TOKEN # Use this only if the repo is private
55
+ )
56
+
57
+ def load_yolo():
58
+ if models["YOLO11x"] is None:
59
+ model_path = get_model_path("microlab-chalmers/microvision_yolo11", "microvision_yolo11.pt")
60
+ models["YOLO11x"] = YOLO(model_path)
61
+ return models["YOLO11x"]
62
+
63
+ def load_detectron2_frcnn():
64
+ if models["Faster R-CNN"] is None:
65
+ model_path = get_model_path("microlab-chalmers/microvision-fasterrcnn", "microvision_fasterrcnn.pth")
66
+ cfg = get_cfg()
67
+ cfg.merge_from_file(model_zoo.get_config_file(PATH_CFG_FASTER_RCNN))
68
+ cfg.MODEL.WEIGHTS = model_path
69
+ cfg.MODEL.ROI_HEADS.BATCH_SIZE_PER_IMAGE = 1280
70
+ cfg.MODEL.ROI_HEADS.NUM_CLASSES = 5
71
+ cfg.MODEL.DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
72
+ models["Faster R-CNN"] = DefaultPredictor(cfg)
73
+ return models["Faster R-CNN"]
74
+
75
+ def load_rf_detr():
76
+ if models["RF-DETR"] is None and RFDETRLarge is not None:
77
+ model_path = get_model_path("microlab-chalmers/microvision-rfdetr", "microvision_rfdetr.pth")
78
+ models["RF-DETR"] = RFDETRLarge(
79
+ pretrain_weights=model_path
80
+ )
81
+ models["RF-DETR"].optimize_for_inference(compile=False)
82
+ return models["RF-DETR"]
83
+
84
+ def predict(image, model_choice, conf_threshold): # TODO: iou_threshold, nms_threshold
85
+ if image is None:
86
+ return None
87
+
88
+ # Convert PIL to NumPy (RGB) for Supervision workflow
89
+ image_np = np.array(image)
90
+ # image_np = np.array(image.convert("RGB"))
91
+
92
+ # Get image dimensions (height, width)
93
+ height, width, _ = image_np.shape
94
+
95
+ # Define a base reference size (e.g., design looks perfect at 1280px wide)
96
+ reference_width = 1280.0
97
+ scale_factor = width / reference_width
98
+
99
+ # Calculate proportional text properties (clamping to reasonable minimums)
100
+ dynamic_text_scale = max(0.3, 0.6 * scale_factor)
101
+ dynamic_text_thickness = max(1, int(2 * scale_factor))
102
+ dynamic_box_thickness = max(1, int(3 * scale_factor))
103
+
104
+ # Dynamically create annotators matching this image's resolution scale
105
+ box_annotator = sv.BoxAnnotator(
106
+ color=colors,
107
+ thickness=dynamic_box_thickness
108
+ )
109
+ label_annotator = sv.LabelAnnotator(
110
+ color=colors,
111
+ text_scale=dynamic_text_scale,
112
+ text_thickness=dynamic_text_thickness,
113
+ text_padding=max(2, int(6 * scale_factor))
114
+ )
115
+
116
+ # Convert to BGR array for engines like Detectron2
117
+ image_bgr = image_np[:, :, ::-1]
118
+
119
+ detections = None
120
+ labels_list = []
121
+
122
+ if model_choice == "YOLO11x":
123
+ yolo_model = load_yolo()
124
+ results = yolo_model.predict(source=image, conf=conf_threshold)[0]
125
+
126
+ # Parse results using supervision
127
+ detections = sv.Detections.from_ultralytics(results)
128
+
129
+ # Build labels array
130
+ labels_list = [
131
+ f"{results.names[class_id]} {confidence:.2f}"
132
+ for class_id, confidence in zip(detections.class_id, detections.confidence)
133
+ ]
134
+
135
+ elif model_choice == "Faster R-CNN":
136
+ predictor = load_detectron2_frcnn()
137
+ predictor.cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = conf_threshold
138
+
139
+ # Detectron2 expects BGR image formats
140
+ outputs = predictor(image_bgr)
141
+
142
+ # Parse natively into supervision
143
+ detections = sv.Detections.from_detectron2(outputs)
144
+
145
+ # Apply confidence threshold filter (Gradio slider) BEFORE NMS
146
+ mask = detections.confidence >= conf_threshold
147
+ detections = detections[mask]
148
+
149
+ # Apply NMS after confidence filtering
150
+ detections = detections.with_nms(threshold=0.5, class_agnostic=True)
151
+ try:
152
+ print("[DEBUG] sv.Detections count after NMS:", len(detections))
153
+ except Exception:
154
+ pass
155
+
156
+ # Create labels list with class names and confidence scores
157
+ labels_list = [
158
+ f"{class_names[class_id] if class_id < len(class_names) else 'Object'} {confidence:.2f}"
159
+ for class_id, confidence in zip(detections.class_id, detections.confidence)
160
+ ]
161
+
162
+ elif model_choice == "RF-DETR":
163
+ rf_model = load_rf_detr()
164
+ if rf_model is None:
165
+ raise gr.Error("RF-DETR package or model weights are missing.")
166
+
167
+ # Custom architectures usually output custom dictionaries
168
+ results = rf_model.predict(image, conf=conf_threshold)
169
+
170
+ # Check if RF-DETR returns a complete annotated PIL Image directly
171
+ if isinstance(results, Image.Image):
172
+ return results
173
+ if isinstance(results, np.ndarray):
174
+ return Image.fromarray(results)
175
+
176
+ detections = results
177
+ detections.class_id = detections.class_id-1 # Adjust class IDs to be 0-indexed
178
+
179
+ # Handle empty arrays smoothly if no models match the threshold criteria
180
+ if detections.class_id is not None and len(detections.class_id) > 0:
181
+ labels_list = [
182
+ f"{class_names[class_id] if class_id < len(class_names) else 'Object'} {conf:.2f}"
183
+ for class_id, conf in zip(detections.class_id, detections.confidence)
184
+ ]
185
+ else:
186
+ labels_list = []
187
+
188
+ # Unified rendering
189
+ if detections is not None:
190
+ # Box annotations
191
+ annotated_image = box_annotator.annotate(scene=image_np.copy(), detections=detections)
192
+ # Label annotations
193
+ annotated_image = label_annotator.annotate(scene=annotated_image, detections=detections, labels=labels_list)
194
+ return Image.fromarray(annotated_image)
195
+
196
+ return image
197
+
198
+ with gr.Blocks(title="MicroVision") as demo:
199
+ gr.Markdown("#MicroVision Object Detection Hub")
200
+ gr.Markdown("Try out the different detection models trained on the MicroVision dataset (YOLO11x, Faster R-CNN, RF-DETR).")
201
+
202
+ with gr.Row():
203
+ with gr.Column():
204
+ input_img = gr.Image(type="pil", label="Input Image")
205
+ model_dropdown = gr.Dropdown(
206
+ choices=["YOLO11x", "Faster R-CNN", "RF-DETR"],
207
+ value="YOLO11x",
208
+ label="Select Detection Architecture"
209
+ )
210
+ slider = gr.Slider(minimum=0.1, maximum=1.0, value=0.5, step=0.05, label="Confidence threshold")
211
+ submit_btn = gr.Button("Detect objects", variant="primary")
212
+
213
+ with gr.Column():
214
+ output_img = gr.Image(type="pil", label="Annotated Output")
215
+
216
+ submit_btn.click(
217
+ fn=predict,
218
+ inputs=[input_img, model_dropdown, slider],
219
+ outputs=output_img
220
+ )
221
+
222
+ if __name__ == "__main__":
223
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ absl-py==2.4.0
2
+ accelerate==1.13.0
3
+ annotated-doc==0.0.4
4
+ annotated-types==0.7.0
5
+ antlr4-python3-runtime==4.9.3
6
+ anyio==4.13.0
7
+ black==26.5.1
8
+ brotli==1.2.0
9
+ certifi==2026.5.20
10
+ charset-normalizer==3.4.7
11
+ click==8.4.0
12
+ cloudpickle==3.1.2
13
+ colorama==0.4.6
14
+ contourpy==1.3.3
15
+ cycler==0.12.1
16
+ defusedxml==0.7.1
17
+ detectron2 @ git+https://github.com/facebookresearch/detectron2.git@e0ec4e189d438848521aee7926f9900e114229f5
18
+ fastapi==0.136.1
19
+ filelock==3.29.0
20
+ fonttools==4.63.0
21
+ fsspec==2026.4.0
22
+ fvcore==0.1.5.post20221221
23
+ gradio==6.14.0
24
+ gradio-client==2.5.0
25
+ groovy==0.1.2
26
+ grpcio==1.80.0
27
+ h11==0.16.0
28
+ hf-gradio==0.4.1
29
+ hf-xet==1.5.0
30
+ httpcore==1.0.9
31
+ httpx==0.28.1
32
+ huggingface-hub==1.16.0
33
+ hydra-core==1.3.2
34
+ idna==3.15
35
+ iopath==0.1.9
36
+ jinja2==3.1.6
37
+ kiwisolver==1.5.0
38
+ markdown==3.10.2
39
+ markdown-it-py==4.2.0
40
+ markupsafe==3.0.3
41
+ matplotlib==3.10.9
42
+ mdurl==0.1.2
43
+ mpmath==1.3.0
44
+ mypy-extensions==1.1.0
45
+ networkx==3.6.1
46
+ numpy==2.4.6
47
+ omegaconf==2.3.0
48
+ opencv-python==4.13.0.92
49
+ orjson==3.11.9
50
+ packaging==26.2
51
+ pandas==3.0.3
52
+ pathspec==1.1.1
53
+ peft==0.19.1
54
+ pillow==12.2.0
55
+ platformdirs==4.9.6
56
+ polars==1.40.1
57
+ polars-runtime-32==1.40.1
58
+ portalocker==3.2.0
59
+ protobuf==7.35.0
60
+ psutil==7.2.2
61
+ pycocotools==2.0.11
62
+ pydantic==2.13.4
63
+ pydantic-core==2.46.4
64
+ pydeprecate==0.5.0
65
+ pydub==0.25.1
66
+ pygments==2.20.0
67
+ pyparsing==3.3.2
68
+ python-dateutil==2.9.0.post0
69
+ python-multipart==0.0.29
70
+ pytokens==0.4.1
71
+ pytz==2026.2
72
+ pywin32==311
73
+ pyyaml==6.0.3
74
+ regex==2026.5.9
75
+ requests==2.34.2
76
+ rfdetr==1.6.5.post2
77
+ rich==15.0.0
78
+ safehttpx==0.1.7
79
+ safetensors==0.7.0
80
+ scipy==1.17.1
81
+ semantic-version==2.10.0
82
+ setuptools==81.0.0
83
+ shellingham==1.5.4
84
+ six==1.17.0
85
+ starlette==1.0.0
86
+ supervision==0.27.0.post2
87
+ sympy==1.14.0
88
+ tabulate==0.10.0
89
+ tensorboard==2.20.0
90
+ tensorboard-data-server==0.7.2
91
+ termcolor==3.3.0
92
+ tokenizers==0.22.2
93
+ tomlkit==0.14.0
94
+ torch==2.12.0
95
+ torchvision==0.27.0
96
+ tqdm==4.67.3
97
+ transformers==5.9.0
98
+ typer==0.25.1
99
+ typing-extensions==4.15.0
100
+ typing-inspection==0.4.2
101
+ tzdata==2026.2
102
+ ultralytics==8.4.52
103
+ ultralytics-thop==2.0.19
104
+ urllib3==2.7.0
105
+ uvicorn==0.47.0
106
+ werkzeug==3.1.8
107
+ yacs==0.1.8