import gradio as gr import torch import numpy as np from PIL import Image from huggingface_hub import hf_hub_download import os import supervision as sv from ultralytics import YOLO from detectron2.engine import DefaultPredictor from detectron2.config import get_cfg from detectron2.data.datasets import register_coco_instances from detectron2 import model_zoo try: from rfdetr import RFDETRLarge except ImportError: RFDETR = None # TODO: Check why small caps for YOLO11 model! class_names = {0: "Pedestrian", 1: "Bicycle", 2: "Cyclist", 3: "E-scooter", 4: "E-scooterist"} PATH_CFG_FASTER_RCNN = "COCO-Detection/faster_rcnn_X_101_32x8d_FPN_3x.yaml" def hex_to_rgb(hex_str): hex_str = hex_str.lstrip('#') return tuple(int(hex_str[i:i+2], 16) for i in (0, 2, 4)) tab10_hex = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd'] rgb_colors = [hex_to_rgb(h) for h in tab10_hex] bgr_colors = [sv.Color(r=b, g=g, b=r) for r, g, b in rgb_colors] colors = sv.ColorPalette(colors=bgr_colors) models = { "YOLO11x": None, "Faster R-CNN": None, "RF-DETR": None } def get_model_path(repo_id, filename): """Downloads model from HF Hub and returns local path.""" return hf_hub_download( repo_id=repo_id, filename=filename ) def load_yolo(): if models["YOLO11x"] is None: model_path = get_model_path("microlab-chalmers/microvision-yolo11", "microvision_yolo11.pt") models["YOLO11x"] = YOLO(model_path) return models["YOLO11x"] def load_detectron2_frcnn(): if models["Faster R-CNN"] is None: model_path = get_model_path("microlab-chalmers/microvision-fasterrcnn", "microvision_fasterrcnn.pth") cfg = get_cfg() cfg.merge_from_file(model_zoo.get_config_file(PATH_CFG_FASTER_RCNN)) cfg.MODEL.WEIGHTS = model_path cfg.MODEL.ROI_HEADS.BATCH_SIZE_PER_IMAGE = 1280 cfg.MODEL.ROI_HEADS.NUM_CLASSES = 5 cfg.MODEL.DEVICE = "cuda" if torch.cuda.is_available() else "cpu" models["Faster R-CNN"] = DefaultPredictor(cfg) return models["Faster R-CNN"] def load_rf_detr(): if models["RF-DETR"] is None and RFDETRLarge is not None: model_path = get_model_path("microlab-chalmers/microvision-rfdetr", "microvision_rfdetr.pth") models["RF-DETR"] = RFDETRLarge( pretrain_weights=model_path, device="cpu" ) models["RF-DETR"].optimize_for_inference(compile=False) return models["RF-DETR"] def predict(image, model_choice, conf_threshold): # TODO: iou_threshold, nms_threshold if image is None: return None # Convert PIL to NumPy (RGB) for Supervision workflow image_np = np.array(image) # image_np = np.array(image.convert("RGB")) # Get image dimensions (height, width) height, width, _ = image_np.shape # Define a base reference size (e.g., design looks perfect at 1280px wide) reference_width = 1280.0 scale_factor = width / reference_width # Calculate proportional text properties (clamping to reasonable minimums) dynamic_text_scale = max(0.3, 0.6 * scale_factor) dynamic_text_thickness = max(1, int(2 * scale_factor)) dynamic_box_thickness = max(1, int(3 * scale_factor)) # Dynamically create annotators matching this image's resolution scale box_annotator = sv.BoxAnnotator( color=colors, thickness=dynamic_box_thickness ) label_annotator = sv.LabelAnnotator( color=colors, text_scale=dynamic_text_scale, text_thickness=dynamic_text_thickness, text_padding=max(2, int(6 * scale_factor)) ) # Convert to BGR array for engines like Detectron2 image_bgr = image_np[:, :, ::-1] detections = None labels_list = [] if model_choice == "YOLO11x": yolo_model = load_yolo() results = yolo_model.predict(source=image, conf=conf_threshold)[0] # Parse results using supervision detections = sv.Detections.from_ultralytics(results) # Build labels array labels_list = [ f"{results.names[class_id]} {confidence:.2f}" for class_id, confidence in zip(detections.class_id, detections.confidence) ] elif model_choice == "Faster R-CNN": predictor = load_detectron2_frcnn() predictor.cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = conf_threshold # Detectron2 expects BGR image formats outputs = predictor(image_bgr) # Parse natively into supervision detections = sv.Detections.from_detectron2(outputs) # Apply confidence threshold filter (Gradio slider) BEFORE NMS mask = detections.confidence >= conf_threshold detections = detections[mask] # Apply NMS after confidence filtering detections = detections.with_nms(threshold=0.5, class_agnostic=True) try: print("[DEBUG] sv.Detections count after NMS:", len(detections)) except Exception: pass # Create labels list with class names and confidence scores labels_list = [ f"{class_names[class_id] if class_id < len(class_names) else 'Object'} {confidence:.2f}" for class_id, confidence in zip(detections.class_id, detections.confidence) ] elif model_choice == "RF-DETR": rf_model = load_rf_detr() if rf_model is None: raise gr.Error("RF-DETR package or model weights are missing.") # Custom architectures usually output custom dictionaries results = rf_model.predict(image, conf=conf_threshold) # Check if RF-DETR returns a complete annotated PIL Image directly if isinstance(results, Image.Image): return results if isinstance(results, np.ndarray): return Image.fromarray(results) detections = results detections.class_id = detections.class_id-1 # Adjust class IDs to be 0-indexed # Handle empty arrays smoothly if no models match the threshold criteria if detections.class_id is not None and len(detections.class_id) > 0: labels_list = [ f"{class_names[class_id] if class_id < len(class_names) else 'Object'} {conf:.2f}" for class_id, conf in zip(detections.class_id, detections.confidence) ] else: labels_list = [] # Unified rendering if detections is not None: # Box annotations annotated_image = box_annotator.annotate(scene=image_np.copy(), detections=detections) # Label annotations annotated_image = label_annotator.annotate(scene=annotated_image, detections=detections, labels=labels_list) return Image.fromarray(annotated_image) return image with gr.Blocks(title="MicroVision") as demo: gr.Markdown("# MicroVision Object Detection Hub") gr.Markdown("Try out the different detection models trained on the MicroVision dataset (YOLO11x, Faster R-CNN, RF-DETR).") with gr.Row(): with gr.Column(): input_img = gr.Image(type="pil", label="Input Image") model_dropdown = gr.Dropdown( choices=["YOLO11x", "Faster R-CNN", "RF-DETR"], value="YOLO11x", label="Select Detection Architecture" ) slider = gr.Slider(minimum=0.1, maximum=1.0, value=0.5, step=0.05, label="Confidence threshold") submit_btn = gr.Button("Detect objects", variant="primary") with gr.Column(): output_img = gr.Image(type="pil", label="Annotated Output") submit_btn.click( fn=predict, inputs=[input_img, model_dropdown, slider], outputs=output_img ) if __name__ == "__main__": demo.launch(server_name="0.0.0.0", server_port=7860)