import gradio as gr import torch from PIL import Image from torchvision.transforms import functional as F from transformers import DetrImageProcessor, DetrForObjectDetection import cv2 import numpy as np # Load the pretrained DETR model processor = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50", revision="no_timm") model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50", revision="no_timm") # Define the object detection function def detect_objects(frame): # Convert the frame to PIL image image = Image.fromarray(frame) # Preprocess the image inputs = processor(images=image, return_tensors="pt") # Perform object detection outputs = model(**inputs) # Convert outputs to COCO API format target_sizes = torch.tensor([image.size[::-1]]) results = processor.post_process_object_detection(outputs, target_sizes=target_sizes, threshold=0.9)[0] # Draw bounding boxes on the frame for score, label, box in zip(results["scores"], results["labels"], results["boxes"]): box = [round(i, 2) for i in box.tolist()] frame = cv2.rectangle(frame, (int(box[0]), int(box[1])), (int(box[2]), int(box[3])), (0, 255, 0), 2) frame = cv2.putText(frame, f'{model.config.id2label[label.item()]}: {round(score.item(), 3)}', (int(box[0]), int(box[1]) - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2, cv2.LINE_AA) return frame # Define the Gradio interface iface = gr.Interface( fn=detect_objects, inputs=gr.Video(), outputs="numpy_image", live=True, ) # Launch the Gradio app iface.launch()