ZENLLC commited on
Commit
c436e12
·
verified ·
1 Parent(s): ccbc1c4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -32
app.py CHANGED
@@ -1,41 +1,63 @@
1
- import gradio as gr
2
- import torch
3
- from transformers import DetrImageProcessor, DetrForObjectDetection
4
  from PIL import Image, ImageDraw
 
5
 
6
- # Load the pre-trained DETR model and processor
7
- processor = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50")
8
- model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50")
9
-
10
- def detect_objects(image: Image.Image) -> Image.Image:
11
  try:
12
- # Preprocess the image
13
- inputs = processor(images=image, return_tensors="pt")
14
- outputs = model(**inputs)
15
-
16
- # Convert outputs to bounding boxes and labels
17
- target_sizes = torch.tensor([image.size[::-1]])
18
- results = processor.post_process_object_detection(outputs, target_sizes=target_sizes, threshold=0.9)[0]
19
-
20
- # Draw bounding boxes on the image
21
- draw = ImageDraw.Draw(image)
22
- for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
23
- box = [round(i, 2) for i in box.tolist()]
24
- label_text = f"{model.config.id2label[label.item()]}: {round(score.item(), 3)}"
25
- draw.rectangle(box, outline="red", width=3)
26
- draw.text((box[0], box[1]), label_text, fill="red")
27
- return image
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  except Exception as e:
29
- print("Error during detection:", e)
30
- return image # In a robust production system, consider returning a message or a default image
31
 
32
- # Create a Gradio interface
33
  iface = gr.Interface(
34
- fn=detect_objects,
35
- inputs=gr.Image(type="pil", label="Upload an Image"),
36
- outputs=gr.Image(label="Detection Result"),
37
- title="Robust Object Detection with DETR",
38
- description="Upload an image to detect objects using a pre-trained DETR model from Hugging Face Hub."
 
 
 
39
  )
40
 
41
  if __name__ == "__main__":
 
1
+ import cv2
2
+ import numpy as np
 
3
  from PIL import Image, ImageDraw
4
+ import gradio as gr
5
 
6
+ def detect_cracks(image: Image.Image) -> Image.Image:
 
 
 
 
7
  try:
8
+ # Convert PIL image to an OpenCV image (BGR format)
9
+ cv_image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
10
+
11
+ # Convert to grayscale for processing
12
+ gray = cv2.cvtColor(cv_image, cv2.COLOR_BGR2GRAY)
13
+
14
+ # Apply Gaussian blur to reduce noise and enhance edges
15
+ blurred = cv2.GaussianBlur(gray, (5, 5), 0)
16
+
17
+ # Use adaptive thresholding to highlight potential crack areas
18
+ thresh = cv2.adaptiveThreshold(
19
+ blurred, 255,
20
+ cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
21
+ cv2.THRESH_BINARY_INV,
22
+ 11, 2
23
+ )
24
+
25
+ # Apply morphological closing to bridge gaps in detected lines
26
+ kernel = np.ones((3, 3), np.uint8)
27
+ morph = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel, iterations=2)
28
+
29
+ # Detect edges with Canny edge detector
30
+ edges = cv2.Canny(morph, 50, 150)
31
+
32
+ # Find contours based on the detected edges
33
+ contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
34
+
35
+ # Convert original image to PIL for drawing
36
+ annotated = image.copy()
37
+ draw = ImageDraw.Draw(annotated)
38
+
39
+ # Draw bounding boxes around contours that are large enough to be meaningful cracks
40
+ for cnt in contours:
41
+ # Filter out noise with a minimum arc length threshold (adjustable)
42
+ if cv2.arcLength(cnt, True) > 100:
43
+ x, y, w, h = cv2.boundingRect(cnt)
44
+ draw.rectangle([x, y, x + w, y + h], outline="red", width=2)
45
+
46
+ return annotated
47
  except Exception as e:
48
+ print("Error during crack detection:", e)
49
+ return image # Fallback: return the original image if any error occurs
50
 
51
+ # Create a Gradio interface for the Space
52
  iface = gr.Interface(
53
+ fn=detect_cracks,
54
+ inputs=gr.Image(type="pil", label="Upload a Floor/Wall Image"),
55
+ outputs=gr.Image(label="Detected Cracks"),
56
+ title="Home Inspection: Crack Detection",
57
+ description=(
58
+ "Upload an image of a floor or wall to detect cracks and other defects. "
59
+ "This demo uses traditional computer vision techniques to highlight potential issues."
60
+ )
61
  )
62
 
63
  if __name__ == "__main__":