import gradio as gr from ultralytics import YOLO import cv2 from PIL import Image import numpy as np # Load YOLOv8 model MODEL_PATH = "Best_Model1.pt" model = YOLO(MODEL_PATH) def detect_flash(image: Image.Image): # Convert PIL image to OpenCV format image_cv = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR) # Run detection results = model(image_cv) detections = results[0].boxes.data.tolist() num_detections = len(detections) message = "" if num_detections > 0: message += f"Flash(es) Detected: {num_detections}\n" for i, det in enumerate(detections): x1, y1, x2, y2, conf, cls = det message += f" Flash {i+1}: Confidence={conf:.2f}, Position=[{int(x1)},{int(y1)},{int(x2)},{int(y2)}]\n" else: message = "No Flash Detected." # Plot result res_plotted = results[0].plot() res_rgb = cv2.cvtColor(res_plotted, cv2.COLOR_BGR2RGB) output_image = Image.fromarray(res_rgb) return output_image, message def clear_all(): return None, None, "" # Gradio interface with gr.Blocks() as demo: gr.Markdown("Flash Detection with YOLOv8") gr.Markdown("Upload an image to detect flash.") with gr.Row(): img_input = gr.Image(type="pil", label="Upload Image") output_img = gr.Image(type="pil", label="Detected Image") output_text = gr.Textbox(label="Detection Info", lines=6) with gr.Row(): detect_btn = gr.Button("Detect Flash") clear_btn = gr.Button("Clear") detect_btn.click(fn=detect_flash, inputs=img_input, outputs=[output_img, output_text]) clear_btn.click(fn=clear_all, inputs=[], outputs=[img_input, output_img, output_text]) demo.launch()