File size: 1,407 Bytes
743b059
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
from transformers import DetrImageProcessor, DetrForObjectDetection
from PIL import Image, ImageDraw

# Load pre-trained model and image processor
model_name = "facebook/detr-resnet-50"
model = DetrForObjectDetection.from_pretrained(model_name)
processor = DetrImageProcessor.from_pretrained(model_name)

# Define function for object detection
def detect_objects(image):
    inputs = processor(images=image, return_tensors="pt")
    outputs = model(**inputs)

    # Get predictions
    target_sizes = [image.size[::-1]]  # (height, width)
    results = processor.post_process_object_detection(outputs, target_sizes=target_sizes, threshold=0.9)[0]

    # Draw bounding boxes on the image
    draw = ImageDraw.Draw(image)
    for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
        box = [round(i, 2) for i in box.tolist()]
        draw.rectangle(box, outline="red", width=3)
        label_name = model.config.id2label[label.item()]
        draw.text((box[0], box[1]), f"{label_name} ({score:.2f})", fill="red")

    return image

# Create Gradio interface
interface = gr.Interface(
    fn=detect_objects,
    inputs=gr.Image(type="pil"),
    outputs=gr.Image(type="pil"),
    title="Object Detection App",
    description="Upload an image to detect objects using the DETR model."
)

# Launch the app
if __name__ == "__main__":
    interface.launch()