Komal133 commited on
Commit
d478de2
·
verified ·
1 Parent(s): 5610d63

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +96 -54
app.py CHANGED
@@ -1,61 +1,103 @@
1
- import gradio as gr
2
- import torch
3
- from torchvision import models, transforms
 
4
  from PIL import Image
 
 
5
  import matplotlib.pyplot as plt
6
- import numpy as np
7
- import cv2
8
- import pandas as pd
9
 
10
- # Load a pre-trained model (replace with your specific model for defect detection)
11
- model = models.resnet18(pretrained=True)
12
- model.eval()
13
 
14
- # Image transformation for input image
15
- transform = transforms.Compose([
16
- transforms.Resize((224, 224)),
17
- transforms.ToTensor(),
18
- transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
19
- ])
20
 
21
- # Detect damage in an image (basic functionality, will need a more advanced model for classification)
22
- def detect_damage(image: Image):
23
- # Convert the image to tensor
24
- image_tensor = transform(image).unsqueeze(0)
 
 
 
 
 
 
 
 
25
 
26
- # Run model prediction (replace with a model that detects cracks, rust, etc.)
27
  with torch.no_grad():
28
- output = model(image_tensor)
29
-
30
- # Here we mock a simple classification (replace with real output logic)
31
- predicted_class = torch.argmax(output, dim=1).item()
32
-
33
- # Mocking severity levels for each defect
34
- defect_type = "Crack" if predicted_class == 0 else "Rust"
35
- severity = "High" if predicted_class == 0 else "Low"
36
-
37
- # Create a heatmap overlay to simulate marking faults (use your model's output here)
38
- heatmap = np.random.rand(224, 224)
39
- overlay = cv2.applyColorMap((heatmap * 255).astype(np.uint8), cv2.COLORMAP_JET)
40
- overlayed_image = cv2.addWeighted(np.array(image), 0.7, overlay, 0.3, 0)
41
-
42
- # Generate a fault report
43
- fault_report = pd.DataFrame({
44
- 'Defect Type': [defect_type],
45
- 'Severity': [severity],
46
- 'Suggested Repair': ['Crack filling or surface coating'] if defect_type == 'Crack' else ['Rust removal and coating']
47
- })
48
-
49
- return Image.fromarray(overlayed_image), fault_report
50
-
51
- # Define Gradio interface with image input
52
- iface = gr.Interface(
53
- fn=detect_damage,
54
- inputs=gr.inputs.Image(type="pil", label="Upload Drone Image"),
55
- outputs=[gr.outputs.Image(type="pil", label="Marked Fault Image"),
56
- gr.outputs.Dataframe(label="Fault Report")],
57
- live=True
58
- )
59
-
60
- # Launch the app
61
- iface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import cv2
3
+ import numpy as np
4
+ from flask import Flask, request, jsonify
5
  from PIL import Image
6
+ import torch
7
+ from io import BytesIO
8
  import matplotlib.pyplot as plt
 
 
 
9
 
10
+ # Define the Flask app
11
+ app = Flask(__name__)
 
12
 
13
+ # Load your pre-trained model (e.g., PyTorch model)
14
+ # Example: Load a pretrained defect detection model for crack, corrosion, displacement
15
+ # Assuming you have a model that classifies defects and severity
16
+ model = torch.hub.load('your_model_repo', 'model_name') # Replace with actual model path
 
 
17
 
18
+ # Ensure the model is in evaluation mode
19
+ model.eval()
20
+
21
+ def process_image(image_bytes):
22
+ """Function to process the uploaded image and predict defects."""
23
+ img = Image.open(BytesIO(image_bytes))
24
+ img = np.array(img)
25
+
26
+ # Preprocessing (adjust depending on model requirements)
27
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
28
+ img_resized = cv2.resize(img, (224, 224)) # Resize to the model's expected input size
29
+ img_tensor = torch.from_numpy(img_resized).float().unsqueeze(0).permute(0, 3, 1, 2) / 255 # Convert to tensor
30
 
 
31
  with torch.no_grad():
32
+ # Inference (adjust based on your model's method)
33
+ predictions = model(img_tensor)
34
+
35
+ # Process the model's predictions and classify the defects
36
+ defect_type, severity = process_predictions(predictions) # Implement defect type and severity classification
37
+ return defect_type, severity, img_resized
38
+
39
+ def process_predictions(predictions):
40
+ """Classify defect type and severity based on model output"""
41
+ # This function depends on how your model outputs predictions
42
+ defect_type = 'Crack' # Example, should be based on actual model output
43
+ severity = 'Moderate' # Example, should be based on actual model output
44
+ return defect_type, severity
45
+
46
+ def overlay_defect_area(image, defect_type, severity):
47
+ """Function to overlay defect area on image."""
48
+ # Example: Draw a red bounding box around detected defect area
49
+ if defect_type == 'Crack':
50
+ color = (255, 0, 0) # Red for cracks
51
+ elif defect_type == 'Corrosion':
52
+ color = (0, 255, 0) # Green for corrosion
53
+ elif defect_type == 'Displacement':
54
+ color = (0, 0, 255) # Blue for displacement
55
+ else:
56
+ color = (255, 255, 0) # Default color
57
+
58
+ # Add a bounding box around the detected defect
59
+ # This is a dummy example, replace with actual bounding box coordinates from model
60
+ top_left = (50, 50)
61
+ bottom_right = (150, 150)
62
+ cv2.rectangle(image, top_left, bottom_right, color, 2)
63
+ return image
64
+
65
+ def generate_report(defect_type, severity):
66
+ """Function to generate a fault map and repair suggestion report."""
67
+ report = {
68
+ 'defect_type': defect_type,
69
+ 'severity': severity,
70
+ 'repair_suggestions': 'Repair suggestions based on defect type and severity.',
71
+ }
72
+ return report
73
+
74
+ @app.route('/upload', methods=['POST'])
75
+ def upload_image():
76
+ """API endpoint to upload images and return defect detection results."""
77
+ if 'file' not in request.files:
78
+ return jsonify({'error': 'No file uploaded'}), 400
79
+
80
+ file = request.files['file']
81
+
82
+ if file.filename == '':
83
+ return jsonify({'error': 'No selected file'}), 400
84
+
85
+ # Process the uploaded image
86
+ image_bytes = file.read()
87
+ defect_type, severity, img = process_image(image_bytes)
88
+
89
+ # Overlay defect areas on the image
90
+ img_with_overlay = overlay_defect_area(img, defect_type, severity)
91
+
92
+ # Generate the report
93
+ report = generate_report(defect_type, severity)
94
+
95
+ # Save the image with overlay (optional)
96
+ output_img_path = 'output_image.jpg'
97
+ cv2.imwrite(output_img_path, img_with_overlay)
98
+
99
+ # Return the report
100
+ return jsonify({'report': report, 'output_image': output_img_path})
101
+
102
+ if __name__ == '__main__':
103
+ app.run(debug=True)