Spaces:
Runtime error
Runtime error
File size: 1,629 Bytes
d10f466 b496423 6c68290 d10f466 bebfcb3 b496423 bf51623 6c68290 bebfcb3 bf51623 b496423 bf51623 bebfcb3 b496423 bf51623 b496423 bebfcb3 b496423 6c68290 bebfcb3 6c68290 bf51623 d10f466 bebfcb3 6c68290 d10f466 bebfcb3 d10f466 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
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()
|