|
import cv2 |
|
import numpy as np |
|
from PIL import Image, ImageDraw, ImageFont |
|
import gradio as gr |
|
|
|
def detect_cracks(image: Image.Image): |
|
try: |
|
|
|
rgb_image = np.array(image) |
|
|
|
annotated = image.copy() |
|
draw = ImageDraw.Draw(annotated) |
|
|
|
|
|
gray = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2GRAY) |
|
|
|
|
|
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) |
|
|
|
detections = [] |
|
|
|
for cnt in contours: |
|
|
|
if cv2.arcLength(cnt, True) > 100: |
|
x, y, w, h = cv2.boundingRect(cnt) |
|
|
|
|
|
roi = rgb_image[y:y+h, x:x+w] |
|
if roi.size == 0: |
|
continue |
|
|
|
roi_gray = cv2.cvtColor(roi, cv2.COLOR_RGB2GRAY) |
|
mean_intensity = np.mean(roi_gray) |
|
|
|
|
|
|
|
if mean_intensity < 80: |
|
material = "Concrete" |
|
elif mean_intensity < 150: |
|
material = "Tile" |
|
else: |
|
material = "Wood" |
|
|
|
label = f"Crack ({material})" |
|
detections.append(f"Detected crack at ({x}, {y}, {w}, {h}) on {material} (mean intensity: {mean_intensity:.1f})") |
|
|
|
|
|
draw.rectangle([x, y, x+w, y+h], outline="red", width=2) |
|
|
|
draw.text((x, y-10), label, fill="red") |
|
|
|
|
|
if detections: |
|
summary = "\n".join(detections) |
|
else: |
|
summary = "No significant cracks detected." |
|
|
|
return annotated, summary |
|
|
|
except Exception as e: |
|
print("Error during detection:", e) |
|
return image, f"Error: {e}" |
|
|
|
|
|
iface = gr.Interface( |
|
fn=detect_cracks, |
|
inputs=gr.Image(type="pil", label="Upload an Image (Floor/Wall)"), |
|
outputs=[gr.Image(label="Annotated Image"), gr.Textbox(label="Detection Summary")], |
|
title="Home Inspection: Granular Crack & Material Detector", |
|
description=( |
|
"Upload an image of a floor or wall to detect cracks and infer the underlying material " |
|
"(Concrete, Tile, or Wood) using classical computer vision techniques. " |
|
"This demo returns both an annotated image and a textual summary." |
|
) |
|
) |
|
|
|
if __name__ == "__main__": |
|
iface.launch() |
|
|