Views / app.py
ZENLLC's picture
Update app.py
c436e12 verified
raw
history blame
2.43 kB
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()