File size: 2,428 Bytes
c436e12
 
5cf1972
c436e12
5cf1972
c436e12
5cf1972
c436e12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5cf1972
c436e12
 
5cf1972
c436e12
5cf1972
c436e12
 
 
 
 
 
 
 
5cf1972
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import cv2
import numpy as np
from PIL import Image, ImageDraw
import gradio as gr

def detect_cracks(image: Image.Image) -> Image.Image:
    try:
        # Convert PIL image to an OpenCV image (BGR format)
        cv_image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
        
        # Convert to grayscale for processing
        gray = cv2.cvtColor(cv_image, cv2.COLOR_BGR2GRAY)
        
        # Apply Gaussian blur to reduce noise and enhance edges
        blurred = cv2.GaussianBlur(gray, (5, 5), 0)
        
        # Use adaptive thresholding to highlight potential crack areas
        thresh = cv2.adaptiveThreshold(
            blurred, 255,
            cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
            cv2.THRESH_BINARY_INV,
            11, 2
        )
        
        # Apply morphological closing to bridge gaps in detected lines
        kernel = np.ones((3, 3), np.uint8)
        morph = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel, iterations=2)
        
        # Detect edges with Canny edge detector
        edges = cv2.Canny(morph, 50, 150)
        
        # Find contours based on the detected edges
        contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        
        # Convert original image to PIL for drawing
        annotated = image.copy()
        draw = ImageDraw.Draw(annotated)
        
        # Draw bounding boxes around contours that are large enough to be meaningful cracks
        for cnt in contours:
            # Filter out noise with a minimum arc length threshold (adjustable)
            if cv2.arcLength(cnt, True) > 100:
                x, y, w, h = cv2.boundingRect(cnt)
                draw.rectangle([x, y, x + w, y + h], outline="red", width=2)
        
        return annotated
    except Exception as e:
        print("Error during crack detection:", e)
        return image  # Fallback: return the original image if any error occurs

# Create a Gradio interface for the Space
iface = gr.Interface(
    fn=detect_cracks,
    inputs=gr.Image(type="pil", label="Upload a Floor/Wall Image"),
    outputs=gr.Image(label="Detected Cracks"),
    title="Home Inspection: Crack Detection",
    description=(
        "Upload an image of a floor or wall to detect cracks and other defects. "
        "This demo uses traditional computer vision techniques to highlight potential issues."
    )
)

if __name__ == "__main__":
    iface.launch()