Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657import gradio as grimport cv2from ultralytics import YOLOpothole_count = 0# Load your custom trained modelmodel = YOLO("best.pt")def detect(frame):# If the frame is empty (can happen during stream initialization), return Noneif frame is None:return None, pothole_count+0# ---> THIS IS THE MAGIC FIX <---# Create a writable copy of the read-only array provided by Gradioframe = frame.copy()results = model(frame, conf=0.4)for r in results:if r.boxes is not None:pothole_count += len(r.boxes)for box in r.boxes:# Get coordinates and draw bounding boxx1, y1, x2, y2 = map(int, box.xyxy[0])cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)cv2.putText(frame, f"Potholes: {pothole_count}",(20, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 3)return frame, pothole_count# Use Gradio Blocks for a cleaner, modern interfacewith gr.Blocks() as demo:gr.Markdown("# Live Pothole Detection")gr.Markdown("Using YOLOv8 to detect potholes in real-time.")with gr.Row():with gr.Column():# Input: Modern Gradio 4.x syntax for webcam streaminginput_video = gr.Image(sources=["webcam"], streaming=True, label="Webcam Feed")with gr.Column():# Outputs: The processed video and the live counteroutput_video = gr.Image(label="Processed Feed")live_count = gr.Number(label="Live Pothole Count", value=0, interactive=False)# The .stream() method runs the function continuously as new frames come ininput_video.stream(fn=detect,inputs=[input_video],outputs=[output_video, live_count])if __name__ == "__main__":demo.launch()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374import gradio as grimport cv2from ultralytics import YOLO# Load your custom trained modelmodel = YOLO("best.pt")def detect(frame, seen_ids):# If the frame is empty, return defaultsif frame is None:return None, len(seen_ids), seen_ids# Create a writable copy to avoid the read-only errorframe = frame.copy()# THE MAGIC FIX 1: Use .track() instead of () and set persist=True# This tells YOLO to remember objects from the previous frameresults = model.track(frame, conf=0.4, persist=True)for r in results:# Check if boxes exist AND if the tracker has assigned IDs yetif r.boxes is not None and r.boxes.id is not None:# Extract the unique tracking IDs as a standard Python listtrack_ids = r.boxes.id.int().cpu().tolist()for box, track_id in zip(r.boxes, track_ids):# THE MAGIC FIX 2: Only add to our count if it's a new IDif track_id not in seen_ids:seen_ids.append(track_id)# Draw bounding boxx1, y1, x2, y2 = map(int, box.xyxy[0])cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)# Optional: Write the ID number above the pothole so you can see the tracking workcv2.putText(frame, f"ID: {track_id}", (x1, y1 - 10),cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)# The total count is simply the number of unique IDs we've collectedtotal_count = len(seen_ids)# Display the total count on the video feedcv2.putText(frame, f"Total Potholes: {total_count}",(20, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 3)# Return the image, the live number, and the updated list of IDsreturn frame, total_count, seen_idswith gr.Blocks() as demo:gr.Markdown("# Live Pothole Counter")gr.Markdown("Using YOLOv8 Object Tracking to count unique potholes in real-time.")# Initialize an empty list in Gradio's memory to hold our seen IDsseen_ids_state = gr.State(value=[])with gr.Row():with gr.Column():input_video = gr.Image(sources=["webcam"], streaming=True, label="Webcam Feed")with gr.Column():output_video = gr.Image(label="Processed Feed")live_count = gr.Number(label="Total Unique Potholes", value=0, interactive=False)# Pass the state variable into the stream and expect it back outinput_video.stream(fn=detect,inputs=[input_video, seen_ids_state],outputs=[output_video, live_count, seen_ids_state])if __name__ == "__main__":demo.launch()
app.py+42-25