File size: 4,010 Bytes
a7ebeb6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import tensorflow as tf
import numpy as np
from tensorflow.keras.layers import (
    Conv2D,
    MaxPool2D,
    Dropout,
    Conv2DTranspose,
    concatenate,
)
import matplotlib.pyplot as plt


class EncoderBlock(tf.keras.layers.Layer):
    def __init__(self, filters, rate=None, pooling=True, **kwargs):
        super(EncoderBlock, self).__init__(**kwargs)
        self.filters = filters
        self.rate = rate
        self.pooling = pooling
        self.conv1 = Conv2D(
            self.filters,
            kernel_size=3,
            strides=1,
            padding="same",
            activation="relu",
            kernel_initializer="he_normal",
        )
        self.conv2 = Conv2D(
            self.filters,
            kernel_size=3,
            strides=1,
            padding="same",
            activation="relu",
            kernel_initializer="he_normal",
        )
        if self.pooling:
            self.pool = MaxPool2D(pool_size=(2, 2))
        if self.rate is not None:
            self.drop = Dropout(rate)

    def call(self, inputs):
        x = self.conv1(inputs)
        if self.rate is not None:
            x = self.drop(x)
        x = self.conv2(x)
        if self.pooling:
            y = self.pool(x)
            return y, x
        else:
            return x

    def get_config(self):
        base_config = super().get_config()
        return {
            **base_config,
            "filters": self.filters,
            "rate": self.rate,
            "pooling": self.pooling,
        }


class DecoderBlock(tf.keras.layers.Layer):
    def __init__(self, filters, rate=None, axis=-1, **kwargs):
        super(DecoderBlock, self).__init__(**kwargs)
        self.filters = filters
        self.rate = rate
        self.axis = axis
        self.convT = Conv2DTranspose(
            self.filters, kernel_size=3, strides=2, padding="same"
        )
        self.conv1 = Conv2D(
            self.filters,
            kernel_size=3,
            activation="relu",
            kernel_initializer="he_normal",
            padding="same",
        )
        if rate is not None:
            self.drop = Dropout(self.rate)
        self.conv2 = Conv2D(
            self.filters,
            kernel_size=3,
            activation="relu",
            kernel_initializer="he_normal",
            padding="same",
        )

    def call(self, inputs):
        X, short_X = inputs
        ct = self.convT(X)
        c_ = concatenate([ct, short_X], axis=self.axis)
        x = self.conv1(c_)
        if self.rate is not None:
            x = self.drop(x)
        y = self.conv2(x)
        return y

    def get_config(self):
        base_config = super().get_config()
        return {
            **base_config,
            "filters": self.filters,
            "rate": self.rate,
            "axis": self.axis,
        }


# Load the model with custom layers
unet = tf.keras.models.load_model(
    "final.h5",
    custom_objects={
        "EncoderBlock": EncoderBlock,
        "DecoderBlock": DecoderBlock,
    },
)


def show_image(image, cmap=None, title=None):
    plt.imshow(image, cmap=cmap)
    if title is not None:
        plt.title(title)
    plt.axis("off")


def predict(image):
    real_img = tf.image.resize(image, [128, 128])
    real_img = real_img / 255.0
    real_img = np.expand_dims(real_img, axis=0)
    pred_mask = unet.predict(real_img).reshape(128, 128)
    real_img = real_img[0]

    fig, ax = plt.subplots(1, 2, figsize=(10, 5))

    ax[0].imshow(real_img)
    ax[0].set_title("Original Image")
    ax[0].axis("off")

    ax[1].imshow(pred_mask, cmap="gray")
    ax[1].set_title("Predicted Mask")
    ax[1].axis("off")

    plt.tight_layout()
    plt.show()
    return pred_mask


# Create Gradio interface
iface = gr.Interface(
    fn=predict,
    inputs=gr.Image(type="numpy"),
    outputs=gr.Image(type="numpy"),
    examples=["./images/water_body_11.jpg", "./images/water_body_1011.jpg"],
    title="Water Body Segmentation",
)

iface.launch()