Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,43 +5,45 @@ import cv2
|
|
| 5 |
import os
|
| 6 |
import torch
|
| 7 |
|
| 8 |
-
|
| 9 |
-
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 10 |
model = YOLO("best.pt").to(device)
|
| 11 |
|
| 12 |
-
#
|
| 13 |
def predict_image(image):
|
| 14 |
results = model.predict(image, imgsz=640, conf=0.3, verbose=False)
|
| 15 |
return results[0].plot()
|
| 16 |
|
| 17 |
-
#
|
| 18 |
def predict_video(video_path):
|
| 19 |
cap = cv2.VideoCapture(video_path)
|
| 20 |
fps = cap.get(cv2.CAP_PROP_FPS) or 25
|
| 21 |
-
|
| 22 |
|
| 23 |
-
# ✅ Output file path
|
| 24 |
fd, output_path = tempfile.mkstemp(suffix=".mp4")
|
| 25 |
os.close(fd)
|
|
|
|
| 26 |
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
|
| 27 |
-
out = cv2.VideoWriter(output_path, fourcc, fps, (
|
| 28 |
|
| 29 |
-
# ✅ Fast streaming detection
|
| 30 |
for result in model.track(source=video_path, stream=True, imgsz=640, conf=0.3, verbose=False):
|
| 31 |
if result.orig_img is None:
|
| 32 |
continue
|
| 33 |
-
|
| 34 |
annotated = result.plot()
|
| 35 |
out.write(annotated)
|
| 36 |
|
| 37 |
cap.release()
|
| 38 |
out.release()
|
| 39 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
return output_path
|
| 41 |
|
| 42 |
-
#
|
| 43 |
with gr.Blocks() as demo:
|
| 44 |
-
gr.Markdown("#
|
| 45 |
|
| 46 |
with gr.Tab("Image"):
|
| 47 |
img_input = gr.Image(type="pil")
|
|
|
|
| 5 |
import os
|
| 6 |
import torch
|
| 7 |
|
| 8 |
+
|
|
|
|
| 9 |
model = YOLO("best.pt").to(device)
|
| 10 |
|
| 11 |
+
# Image prediction
|
| 12 |
def predict_image(image):
|
| 13 |
results = model.predict(image, imgsz=640, conf=0.3, verbose=False)
|
| 14 |
return results[0].plot()
|
| 15 |
|
| 16 |
+
# Video prediction
|
| 17 |
def predict_video(video_path):
|
| 18 |
cap = cv2.VideoCapture(video_path)
|
| 19 |
fps = cap.get(cv2.CAP_PROP_FPS) or 25
|
| 20 |
+
width, height = 640, 360
|
| 21 |
|
|
|
|
| 22 |
fd, output_path = tempfile.mkstemp(suffix=".mp4")
|
| 23 |
os.close(fd)
|
| 24 |
+
|
| 25 |
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
|
| 26 |
+
out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
|
| 27 |
|
|
|
|
| 28 |
for result in model.track(source=video_path, stream=True, imgsz=640, conf=0.3, verbose=False):
|
| 29 |
if result.orig_img is None:
|
| 30 |
continue
|
| 31 |
+
frame = cv2.resize(result.orig_img, (width, height))
|
| 32 |
annotated = result.plot()
|
| 33 |
out.write(annotated)
|
| 34 |
|
| 35 |
cap.release()
|
| 36 |
out.release()
|
| 37 |
|
| 38 |
+
# Check if file is valid
|
| 39 |
+
if not os.path.exists(output_path) or os.path.getsize(output_path) == 0:
|
| 40 |
+
raise RuntimeError("Output video file is missing or corrupted.")
|
| 41 |
+
|
| 42 |
return output_path
|
| 43 |
|
| 44 |
+
# Gradio UI
|
| 45 |
with gr.Blocks() as demo:
|
| 46 |
+
gr.Markdown("# YOLOv8 Object Detection\nFast & Accurate for Images and Videos")
|
| 47 |
|
| 48 |
with gr.Tab("Image"):
|
| 49 |
img_input = gr.Image(type="pil")
|