0llheaven's picture
Update app.py
5e73f80 verified
raw
history blame
1.75 kB
import gradio as gr
from transformers import AutoImageProcessor, AutoModelForObjectDetection
import torch
from PIL import Image, ImageDraw
# Load the model and processor
processor = AutoImageProcessor.from_pretrained("0llheaven/Conditional-detr-finetuned")
model = AutoModelForObjectDetection.from_pretrained("0llheaven/Conditional-detr-finetuned")
def detect_objects(image):
# Convert image to RGB if it's grayscale
if image.mode != "RGB":
image = image.convert("RGB")
# Prepare input for the model
inputs = processor(images=image, return_tensors="pt")
outputs = model(**inputs)
# Filter predictions with confidence greater than 0.5
target_sizes = torch.tensor([image.size[::-1]])
results = processor.post_process_object_detection(outputs, target_sizes=target_sizes)
# Draw bounding boxes around detected objects
draw = ImageDraw.Draw(image)
for result in results:
scores = result["scores"]
labels = result["labels"]
boxes = result["boxes"]
for score, label, box in zip(scores, labels, boxes):
box = [round(i, 2) for i in box.tolist()]
label_name = "Pneumonia" if label.item() == 0 else "Other"
draw.rectangle(box, outline="red", width=3)
draw.text((box[0], box[1]), f"{label_name}: {round(score.item(), 3)}", fill="red")
return image
# Create the Gradio interface
interface = gr.Interface(
fn=detect_objects,
inputs=gr.Image(type="pil"),
outputs=gr.Image(type="pil"), # Corrected output type
title="Object Detection with Transformers",
description="Upload an image to detect objects using a fine-tuned Conditional-DETR model."
)
# Launch the interface
interface.launch()