|
|
| import gradio as gr |
| import torch |
| from torchvision import transforms |
| from PIL import Image |
| import torch.nn.functional as F |
| from ultralytics import YOLO |
| import cv2 |
| import numpy as np |
|
|
| |
| model = YOLO("nabird_det_ep3.pt") |
|
|
| def detect_objects(image: Image.Image): |
|
|
| image_np = np.array(image) |
| image_np = cv2.cvtColor(image_np, cv2.COLOR_RGB2BGR) |
|
|
| results = model.predict(image_np, save=False) |
| |
| for result in results: |
| for box in result.boxes: |
| |
| xyxy = box.xyxy[0].tolist() |
| conf = box.conf[0].item() |
| cls = int(box.cls[0].item()) |
| class_name = model.names[cls] |
|
|
| |
| x1, y1, x2, y2 = map(int, xyxy) |
|
|
| |
| cv2.rectangle(image_np, (x1, y1), (x2, y2), color=(0, 255, 0), thickness=2) |
|
|
| |
| label = f"{class_name} {conf:.2f}" |
| cv2.putText(image_np, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) |
|
|
| |
| image_with_boxes = cv2.cvtColor(image_np, cv2.COLOR_BGR2RGB) |
| return Image.fromarray(image_with_boxes) |
|
|
| example_image_paths = ["PC060715.jpg", "PC061030.jpg", "PC060806.jpg"] |
|
|
|
|
| app = gr.Interface( |
| fn=detect_objects, |
| inputs=gr.Image(type="pil"), |
| outputs=gr.Image(type="pil"), |
| examples=example_image_paths, |
| title="YOLO Object Detection", |
| description="Upload an image to detect objects using YOLO." |
| ) |
|
|
| app.launch() |
|
|