Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from ultralytics import YOLO
|
3 |
+
import cv2
|
4 |
+
from PIL import Image
|
5 |
+
import numpy as np
|
6 |
+
|
7 |
+
# Load model
|
8 |
+
MODEL_PATH = "Best_Model1.pt"
|
9 |
+
model = YOLO(MODEL_PATH)
|
10 |
+
|
11 |
+
def detect_flash_gradio(image: Image.Image):
|
12 |
+
# Convert PIL image to OpenCV format
|
13 |
+
image_cv = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
|
14 |
+
|
15 |
+
# Run detection
|
16 |
+
results = model(image_cv)
|
17 |
+
|
18 |
+
# Extract detection info
|
19 |
+
detections = results[0].boxes.data.tolist()
|
20 |
+
num_detections = len(detections)
|
21 |
+
|
22 |
+
message = ""
|
23 |
+
if num_detections > 0:
|
24 |
+
message += f"Flash(es) Detected: {num_detections}\n"
|
25 |
+
for i, det in enumerate(detections):
|
26 |
+
x1, y1, x2, y2, conf, cls = det
|
27 |
+
message += f" Flash {i+1}: Confidence={conf:.2f}, Position=[{int(x1)},{int(y1)},{int(x2)},{int(y2)}]\n"
|
28 |
+
else:
|
29 |
+
message = "No Flash Detected."
|
30 |
+
|
31 |
+
# Plot result
|
32 |
+
res_plotted = results[0].plot()
|
33 |
+
res_rgb = cv2.cvtColor(res_plotted, cv2.COLOR_BGR2RGB)
|
34 |
+
output_image = Image.fromarray(res_rgb)
|
35 |
+
|
36 |
+
return output_image, message
|
37 |
+
|
38 |
+
# Interface with tabs: Upload or Webcam
|
39 |
+
with gr.Blocks() as demo:
|
40 |
+
gr.Markdown("Flash Detection")
|
41 |
+
gr.Markdown("Upload an image or use your webcam to detect flash.")
|
42 |
+
|
43 |
+
with gr.Tab("Upload Image"):
|
44 |
+
upload_input = gr.Image(type="pil", label="Upload Image")
|
45 |
+
upload_btn = gr.Button("Detect Flash")
|
46 |
+
upload_output_img = gr.Image(type="pil", label="Detected Image")
|
47 |
+
upload_output_text = gr.Textbox(label="Detection Info")
|
48 |
+
|
49 |
+
with gr.Tab("Use Webcam"):
|
50 |
+
webcam_input = gr.Image(source="webcam", type="pil", label="Capture from Webcam")
|
51 |
+
webcam_btn = gr.Button("Detect Flash")
|
52 |
+
webcam_output_img = gr.Image(type="pil", label="Detected Image")
|
53 |
+
webcam_output_text = gr.Textbox(label="Detection Info")
|
54 |
+
|
55 |
+
upload_btn.click(fn=detect_flash_gradio, inputs=upload_input, outputs=[upload_output_img, upload_output_text])
|
56 |
+
webcam_btn.click(fn=detect_flash_gradio, inputs=webcam_input, outputs=[webcam_output_img, webcam_output_text])
|
57 |
+
|
58 |
+
demo.launch()
|