road1 / services /pothole_detection_service.py
Yaswanth56's picture
Create pothole_detection_service.py
fbab425 verified
import cv2
import numpy as np
# Define road boundary (ROI) for detection
ROAD_BOUNDARY = (50, 50, 590, 430) # Example: x_min, y_min, x_max, y_max (adjust accordingly)
def detect_potholes(frame):
"""
Detects potholes in the given video frame.
Uses edge detection and contour analysis to detect circular pothole shapes.
"""
try:
# Convert frame to grayscale
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
# Edge detection using Canny
edges = cv2.Canny(blurred, 50, 150)
# Find contours (potential potholes)
contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
potholes = []
for contour in contours:
# Filter small contours (noise)
if cv2.contourArea(contour) < 500:
continue
# Get bounding box
x, y, w, h = cv2.boundingRect(contour)
area = w * h
# Only consider potholes within the road boundary (ROI)
if x >= ROAD_BOUNDARY[0] and y >= ROAD_BOUNDARY[1] and (x + w) <= ROAD_BOUNDARY[2] and (y + h) <= ROAD_BOUNDARY[3]:
# Check if the shape is circular (potholes are generally round)
aspect_ratio = float(w) / h if h > 0 else 0
if 0.9 <= aspect_ratio <= 1.1: # Circular shapes
potholes.append({
'type': 'pothole',
'box': [x, y, x + w, y + h],
'confidence': 0.95 # Simulated confidence
})
return potholes
except Exception as e:
print(f"Error in pothole detection: {str(e)}")
return []