|
import cv2 |
|
import numpy as np |
|
from PIL import Image, ImageDraw |
|
import gradio as gr |
|
|
|
def detect_cracks(image: Image.Image) -> Image.Image: |
|
try: |
|
|
|
cv_image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR) |
|
|
|
|
|
gray = cv2.cvtColor(cv_image, cv2.COLOR_BGR2GRAY) |
|
|
|
|
|
blurred = cv2.GaussianBlur(gray, (5, 5), 0) |
|
|
|
|
|
thresh = cv2.adaptiveThreshold( |
|
blurred, 255, |
|
cv2.ADAPTIVE_THRESH_GAUSSIAN_C, |
|
cv2.THRESH_BINARY_INV, |
|
11, 2 |
|
) |
|
|
|
|
|
kernel = np.ones((3, 3), np.uint8) |
|
morph = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel, iterations=2) |
|
|
|
|
|
edges = cv2.Canny(morph, 50, 150) |
|
|
|
|
|
contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) |
|
|
|
|
|
annotated = image.copy() |
|
draw = ImageDraw.Draw(annotated) |
|
|
|
|
|
for cnt in contours: |
|
|
|
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 |
|
|
|
|
|
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() |
|
|