Spaces:
Running
Running
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import cv2
|
| 3 |
+
import time
|
| 4 |
+
import numpy as np
|
| 5 |
+
from sahi import AutoDetectionModel
|
| 6 |
+
from sahi.predict import get_sliced_prediction
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
detection_model = AutoDetectionModel.from_pretrained(
|
| 10 |
+
model_type='ultralytics',
|
| 11 |
+
model_path="/workspace/runs/detect/train2/weights/last.pt", # Replace with your model path
|
| 12 |
+
confidence_threshold=0.01,
|
| 13 |
+
device="cpu" # Change to 'cuda:0' if you have a GPU
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
OUTPUT_PATH = "/workspace/pred_image.jpg"
|
| 17 |
+
TEMP_PNG_PATH = "/workspace/pred_image.png"
|
| 18 |
+
|
| 19 |
+
def run_inference(image):
|
| 20 |
+
input_path = "/workspace/input_image.jpg"
|
| 21 |
+
cv2.imwrite(input_path, cv2.cvtColor(image, cv2.COLOR_RGB2BGR))
|
| 22 |
+
|
| 23 |
+
result = get_sliced_prediction(
|
| 24 |
+
input_path,
|
| 25 |
+
detection_model,
|
| 26 |
+
slice_height=256,
|
| 27 |
+
slice_width=256,
|
| 28 |
+
overlap_height_ratio=0.2,
|
| 29 |
+
overlap_width_ratio=0.2
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
result.export_visuals(export_dir=Path(TEMP_PNG_PATH).parent, file_name=Path(TEMP_PNG_PATH).name)
|
| 33 |
+
|
| 34 |
+
time.sleep(2)
|
| 35 |
+
|
| 36 |
+
if not Path(TEMP_PNG_PATH).exists():
|
| 37 |
+
raise FileNotFoundError(f"SAHI did not save the PNG file at {TEMP_PNG_PATH}")
|
| 38 |
+
|
| 39 |
+
processed_image = cv2.imread(TEMP_PNG_PATH)
|
| 40 |
+
cv2.imwrite(OUTPUT_PATH, processed_image)
|
| 41 |
+
Path(TEMP_PNG_PATH).unlink()
|
| 42 |
+
|
| 43 |
+
return OUTPUT_PATH
|
| 44 |
+
|
| 45 |
+
demo = gr.Interface(
|
| 46 |
+
fn=run_inference,
|
| 47 |
+
inputs=gr.Image(type="numpy"),
|
| 48 |
+
outputs=gr.Image(type="file"),
|
| 49 |
+
title="YOLO11 Object Detection",
|
| 50 |
+
description="Upload a DDR image to run inference using YOLO11"
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
demo.launch()
|