File size: 8,435 Bytes
911c613
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
import gradio as gr
import cv2
import numpy as np
import tensorflow as tf
from tensorflow import keras
from keras.models import load_model
from keras.utils.generic_utils import CustomObjectScope

# Import custom modules
from models.deeplab import Deeplabv3, relu6, DepthwiseConv2D, BilinearUpsampling
from utils.learning.metrics import dice_coef, precision, recall
from utils.io.data import normalize

class WoundSegmentationApp:
    def __init__(self):
        self.input_dim_x = 224
        self.input_dim_y = 224
        self.model = None
        self.load_model()
    
    def load_model(self):
        """Load the trained wound segmentation model"""
        try:
            # Load the model with custom objects
            weight_file_name = '2025-08-07_12-30-43.hdf5'  # Use the most recent model
            model_path = f'./training_history/{weight_file_name}'
            
            self.model = load_model(model_path, 
                                  custom_objects={
                                      'recall': recall,
                                      'precision': precision,
                                      'dice_coef': dice_coef,
                                      'relu6': relu6,
                                      'DepthwiseConv2D': DepthwiseConv2D,
                                      'BilinearUpsampling': BilinearUpsampling
                                  })
            print(f"Model loaded successfully from {model_path}")
        except Exception as e:
            print(f"Error loading model: {e}")
            # Fallback to the older model if the newer one fails
            try:
                weight_file_name = '2019-12-19 01%3A53%3A15.480800.hdf5'
                model_path = f'./training_history/{weight_file_name}'
                
                self.model = load_model(model_path, 
                                      custom_objects={
                                          'recall': recall,
                                          'precision': precision,
                                          'dice_coef': dice_coef,
                                          'relu6': relu6,
                                          'DepthwiseConv2D': DepthwiseConv2D,
                                          'BilinearUpsampling': BilinearUpsampling
                                      })
                print(f"Model loaded successfully from {model_path}")
            except Exception as e2:
                print(f"Error loading fallback model: {e2}")
                self.model = None
    
    def preprocess_image(self, image):
        """Preprocess the uploaded image for model input"""
        if image is None:
            return None
        
        # Convert to RGB if needed
        if len(image.shape) == 3 and image.shape[2] == 3:
            # Convert BGR to RGB if needed
            image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        
        # Resize to model input size
        image = cv2.resize(image, (self.input_dim_x, self.input_dim_y))
        
        # Normalize the image
        image = image.astype(np.float32) / 255.0
        
        # Add batch dimension
        image = np.expand_dims(image, axis=0)
        
        return image
    
    def postprocess_prediction(self, prediction):
        """Postprocess the model prediction"""
        # Remove batch dimension
        prediction = prediction[0]
        
        # Apply threshold to get binary mask
        threshold = 0.5
        binary_mask = (prediction > threshold).astype(np.uint8) * 255
        
        # Convert to 3-channel image for visualization
        mask_rgb = cv2.cvtColor(binary_mask, cv2.COLOR_GRAY2RGB)
        
        return mask_rgb
    
    def segment_wound(self, input_image):
        """Main function to segment wound from uploaded image"""
        if self.model is None:
            return None, "Error: Model not loaded. Please check the model files."
        
        if input_image is None:
            return None, "Please upload an image."
        
        try:
            # Preprocess the image
            processed_image = self.preprocess_image(input_image)
            
            if processed_image is None:
                return None, "Error processing image."
            
            # Make prediction
            prediction = self.model.predict(processed_image, verbose=0)
            
            # Postprocess the prediction
            segmented_mask = self.postprocess_prediction(prediction)
            
            # Create overlay image (original image with segmentation overlay)
            original_resized = cv2.resize(input_image, (self.input_dim_x, self.input_dim_y))
            if len(original_resized.shape) == 3:
                original_resized = cv2.cvtColor(original_resized, cv2.COLOR_RGB2BGR)
            
            # Create overlay with red segmentation
            overlay = original_resized.copy()
            mask_red = np.zeros_like(original_resized)
            mask_red[:, :, 2] = segmented_mask[:, :, 0]  # Red channel
            
            # Blend overlay with original image
            alpha = 0.6
            overlay = cv2.addWeighted(overlay, 1-alpha, mask_red, alpha, 0)
            
            return segmented_mask, overlay
            
        except Exception as e:
            return None, f"Error during segmentation: {str(e)}"

def create_gradio_interface():
    """Create and return the Gradio interface"""
    
    # Initialize the app
    app = WoundSegmentationApp()
    
    # Define the interface
    with gr.Blocks(title="Wound Segmentation Tool", theme=gr.themes.Soft()) as interface:
        gr.Markdown(
            """

            # 🩹 Wound Segmentation Tool

            

            Upload an image of a wound to get an automated segmentation mask.

            The model will identify and highlight the wound area in the image.

            

            **Instructions:**

            1. Upload an image of a wound

            2. Click "Segment Wound" to process the image

            3. View the segmentation mask and overlay results

            """
        )
        
        with gr.Row():
            with gr.Column():
                input_image = gr.Image(
                    label="Upload Wound Image",
                    type="numpy",
                    height=400
                )
                
                segment_btn = gr.Button(
                    "🔍 Segment Wound",
                    variant="primary",
                    size="lg"
                )
            
            with gr.Column():
                mask_output = gr.Image(
                    label="Segmentation Mask",
                    height=400
                )
                
                overlay_output = gr.Image(
                    label="Overlay Result",
                    height=400
                )
        
        # Status message
        status_msg = gr.Textbox(
            label="Status",
            interactive=False,
            placeholder="Ready to process images..."
        )
        
        # Example images
        gr.Markdown("### 📸 Example Images")
        gr.Markdown("You can test the tool with wound images from the dataset.")
        
        # Connect the button to the segmentation function
        def process_image(image):
            mask, overlay = app.segment_wound(image)
            if mask is None:
                return None, None, overlay  # overlay contains error message
            return mask, overlay, "Segmentation completed successfully!"
        
        segment_btn.click(
            fn=process_image,
            inputs=[input_image],
            outputs=[mask_output, overlay_output, status_msg]
        )
        
        # Auto-process when image is uploaded
        input_image.change(
            fn=process_image,
            inputs=[input_image],
            outputs=[mask_output, overlay_output, status_msg]
        )
    
    return interface

if __name__ == "__main__":
    # Create and launch the interface
    interface = create_gradio_interface()
    interface.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=True,
        show_error=True
    )