Spaces:
Runtime error
Runtime error
| import cv2 | |
| import numpy as np | |
| def detect_cracks_and_holes(frame): | |
| 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, 30, 100) # Lower thresholds to detect more cracks | |
| # Morphological operations to enhance cracks and holes | |
| kernel = np.ones((3, 3), np.uint8) | |
| dilated = cv2.dilate(edges, kernel, iterations=2) | |
| eroded = cv2.erode(dilated, kernel, iterations=1) | |
| # Find contours | |
| contours, _ = cv2.findContours(eroded, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) | |
| items = [] | |
| for contour in contours: | |
| # Filter small contours (noise) | |
| area = cv2.contourArea(contour) | |
| if area < 30: # Reduced threshold to catch smaller cracks | |
| continue | |
| # Get bounding box | |
| x, y, w, h = cv2.boundingRect(contour) | |
| area = w * h | |
| # Calculate aspect ratio and circularity | |
| aspect_ratio = float(w) / h if h > 0 else 0 | |
| perimeter = cv2.arcLength(contour, True) | |
| circularity = 4 * np.pi * area / (perimeter * perimeter) if perimeter > 0 else 0 | |
| # Classify as crack or hole | |
| if 0.05 < aspect_ratio < 20 and circularity < 0.4: # Adjusted for more crack detection | |
| item_type = 'crack' | |
| # Check if it's an underlying crack (longer and thinner) | |
| if aspect_ratio > 8: | |
| severity = 'Underlying' | |
| elif area > 4000: | |
| severity = 'Severe' | |
| elif area > 800: | |
| severity = 'Moderate' | |
| else: | |
| severity = 'Minor' | |
| elif circularity > 0.6: # Circular shapes are holes | |
| item_type = 'hole' | |
| if area > 4000: | |
| severity = 'Severe' | |
| elif area > 800: | |
| severity = 'Moderate' | |
| else: | |
| severity = 'Minor' | |
| else: | |
| continue # Skip objects that don't match crack or hole criteria | |
| items.append({ | |
| 'type': item_type, | |
| 'box': [x, y, x + w, y + h], | |
| 'severity': severity, | |
| 'confidence': 0.95 # Simulated confidence | |
| }) | |
| return items | |
| except Exception as e: | |
| print(f"Error in detection: {str(e)}") | |
| return [] |