|
a |
|
b/UNet_CNN_AddUNet.ipynb |
|
|
1 |
{ |
|
|
2 |
"cells": [ |
|
|
3 |
{ |
|
|
4 |
"cell_type": "markdown", |
|
|
5 |
"metadata": { |
|
|
6 |
"id": "nDXW7A7pwZ7a" |
|
|
7 |
}, |
|
|
8 |
"source": [ |
|
|
9 |
"# UNET SEGMENTATION (SUJAL)" |
|
|
10 |
] |
|
|
11 |
}, |
|
|
12 |
{ |
|
|
13 |
"cell_type": "code", |
|
|
14 |
"execution_count": null, |
|
|
15 |
"metadata": { |
|
|
16 |
"id": "M5oF6qqZwZ70" |
|
|
17 |
}, |
|
|
18 |
"outputs": [], |
|
|
19 |
"source": [ |
|
|
20 |
"## Imports\n", |
|
|
21 |
"import os\n", |
|
|
22 |
"import sys\n", |
|
|
23 |
"import random\n", |
|
|
24 |
"\n", |
|
|
25 |
"import numpy as np\n", |
|
|
26 |
"import cv2\n", |
|
|
27 |
"import matplotlib.pyplot as plt\n", |
|
|
28 |
"\n", |
|
|
29 |
"import tensorflow as tf\n", |
|
|
30 |
"from tensorflow import keras\n", |
|
|
31 |
"\n", |
|
|
32 |
"## Seeding\n", |
|
|
33 |
"seed = 42\n", |
|
|
34 |
"random.seed = seed\n", |
|
|
35 |
"np.random.seed = seed\n", |
|
|
36 |
"tf.seed = seed" |
|
|
37 |
] |
|
|
38 |
}, |
|
|
39 |
{ |
|
|
40 |
"cell_type": "markdown", |
|
|
41 |
"metadata": { |
|
|
42 |
"id": "70jPovBLwZ7-" |
|
|
43 |
}, |
|
|
44 |
"source": [ |
|
|
45 |
"## Data " |
|
|
46 |
] |
|
|
47 |
}, |
|
|
48 |
{ |
|
|
49 |
"cell_type": "code", |
|
|
50 |
"execution_count": null, |
|
|
51 |
"metadata": { |
|
|
52 |
"id": "SvRbQp8LwZ8B" |
|
|
53 |
}, |
|
|
54 |
"outputs": [], |
|
|
55 |
"source": [ |
|
|
56 |
" class DataGen(keras.utils.Sequence):\n", |
|
|
57 |
" def __init__(self, ids, path, batch_size=8, image_size=128):\n", |
|
|
58 |
" self.ids = ids\n", |
|
|
59 |
" self.path = path\n", |
|
|
60 |
" self.batch_size = batch_size\n", |
|
|
61 |
" self.image_size = image_size\n", |
|
|
62 |
" self.on_epoch_end()\n", |
|
|
63 |
"\n", |
|
|
64 |
" def __load__(self, id_name):\n", |
|
|
65 |
" # Construct image path\n", |
|
|
66 |
" image_path = os.path.join(self.path, \"images\", id_name)\n", |
|
|
67 |
"\n", |
|
|
68 |
" # Construct mask path\n", |
|
|
69 |
" mask_path = os.path.join(self.path, \"masks\", id_name)\n", |
|
|
70 |
"\n", |
|
|
71 |
" # Read and validate image\n", |
|
|
72 |
" image = cv2.imread(image_path, 1)\n", |
|
|
73 |
" if image is None:\n", |
|
|
74 |
" print(f\"Warning: Failed to load image: {image_path}\")\n", |
|
|
75 |
" return None, None\n", |
|
|
76 |
"\n", |
|
|
77 |
" image = cv2.resize(image, (self.image_size, self.image_size))\n", |
|
|
78 |
"\n", |
|
|
79 |
" # Read and validate mask\n", |
|
|
80 |
" mask = cv2.imread(mask_path, 0) # mask often is a single-channel image\n", |
|
|
81 |
" if mask is None:\n", |
|
|
82 |
" print(f\"Warning: Failed to load mask: {mask_path}\")\n", |
|
|
83 |
" return None, None\n", |
|
|
84 |
"\n", |
|
|
85 |
" mask = cv2.resize(mask, (self.image_size, self.image_size))\n", |
|
|
86 |
" mask = np.expand_dims(mask, axis=-1)\n", |
|
|
87 |
"\n", |
|
|
88 |
" # Normalize\n", |
|
|
89 |
" image = image / 255.0\n", |
|
|
90 |
" mask = mask / 255.0\n", |
|
|
91 |
"\n", |
|
|
92 |
" return image, mask\n", |
|
|
93 |
"\n", |
|
|
94 |
" def __getitem__(self, index):\n", |
|
|
95 |
" if (index + 1) * self.batch_size > len(self.ids):\n", |
|
|
96 |
" self.batch_size = len(self.ids) - index * self.batch_size\n", |
|
|
97 |
"\n", |
|
|
98 |
" files_batch = self.ids[index * self.batch_size: (index + 1) * self.batch_size]\n", |
|
|
99 |
"\n", |
|
|
100 |
" image = []\n", |
|
|
101 |
" mask = []\n", |
|
|
102 |
"\n", |
|
|
103 |
" for id_name in files_batch:\n", |
|
|
104 |
" _img, _mask = self.__load__(id_name)\n", |
|
|
105 |
" if _img is not None and _mask is not None: # Only add valid samples\n", |
|
|
106 |
" image.append(_img)\n", |
|
|
107 |
" mask.append(_mask)\n", |
|
|
108 |
"\n", |
|
|
109 |
" if len(image) == 0: # Handle case where all files in the batch fail\n", |
|
|
110 |
" raise ValueError(\"No valid images or masks found in the current batch.\")\n", |
|
|
111 |
"\n", |
|
|
112 |
" image = np.array(image)\n", |
|
|
113 |
" mask = np.array(mask)\n", |
|
|
114 |
"\n", |
|
|
115 |
" return image, mask\n", |
|
|
116 |
"\n", |
|
|
117 |
" def on_epoch_end(self):\n", |
|
|
118 |
" pass\n", |
|
|
119 |
"\n", |
|
|
120 |
" def __len__(self):\n", |
|
|
121 |
" return int(np.ceil(len(self.ids) / float(self.batch_size)))" |
|
|
122 |
] |
|
|
123 |
}, |
|
|
124 |
{ |
|
|
125 |
"cell_type": "markdown", |
|
|
126 |
"metadata": { |
|
|
127 |
"id": "rUG6cDK1wZ8I" |
|
|
128 |
}, |
|
|
129 |
"source": [ |
|
|
130 |
"## Hyperparameters" |
|
|
131 |
] |
|
|
132 |
}, |
|
|
133 |
{ |
|
|
134 |
"cell_type": "code", |
|
|
135 |
"execution_count": null, |
|
|
136 |
"metadata": { |
|
|
137 |
"id": "2QwbWknPwZ8M" |
|
|
138 |
}, |
|
|
139 |
"outputs": [], |
|
|
140 |
"source": [ |
|
|
141 |
"image_size = 128\n", |
|
|
142 |
"train_path = \"/Users/sandhyakilari/Desktop/Fall Semester 2024/Computer Vision/Segmentation Project\"\n", |
|
|
143 |
"epochs = 30\n", |
|
|
144 |
"batch_size = 8\n", |
|
|
145 |
"\n", |
|
|
146 |
"## Training Ids\n", |
|
|
147 |
"train_ids = os.listdir(os.path.join(train_path, \"images\"))\n", |
|
|
148 |
"\n", |
|
|
149 |
"\n", |
|
|
150 |
"## Validation Data Size\n", |
|
|
151 |
"val_data_size = 10\n", |
|
|
152 |
"\n", |
|
|
153 |
"valid_ids = train_ids[:val_data_size]\n", |
|
|
154 |
"train_ids = train_ids[val_data_size:]" |
|
|
155 |
] |
|
|
156 |
}, |
|
|
157 |
{ |
|
|
158 |
"cell_type": "code", |
|
|
159 |
"execution_count": null, |
|
|
160 |
"metadata": { |
|
|
161 |
"colab": { |
|
|
162 |
"base_uri": "https://localhost:8080/" |
|
|
163 |
}, |
|
|
164 |
"id": "6_cMh29vwZ8R", |
|
|
165 |
"outputId": "534e3fce-2174-4f8d-99d3-c19550f24f70" |
|
|
166 |
}, |
|
|
167 |
"outputs": [], |
|
|
168 |
"source": [ |
|
|
169 |
"gen = DataGen(train_ids, train_path, batch_size=batch_size, image_size=image_size)\n", |
|
|
170 |
"x, y = gen.__getitem__(0)\n", |
|
|
171 |
"print(x.shape, y.shape)" |
|
|
172 |
] |
|
|
173 |
}, |
|
|
174 |
{ |
|
|
175 |
"cell_type": "code", |
|
|
176 |
"execution_count": null, |
|
|
177 |
"metadata": { |
|
|
178 |
"colab": { |
|
|
179 |
"base_uri": "https://localhost:8080/", |
|
|
180 |
"height": 309 |
|
|
181 |
}, |
|
|
182 |
"id": "NCG2jWo9wZ8c", |
|
|
183 |
"outputId": "f158147f-b3b7-4c7f-e0a0-13219d136aa7", |
|
|
184 |
"scrolled": false |
|
|
185 |
}, |
|
|
186 |
"outputs": [], |
|
|
187 |
"source": [ |
|
|
188 |
"r = random.randint(0, len(x)-1)\n", |
|
|
189 |
"\n", |
|
|
190 |
"fig = plt.figure()\n", |
|
|
191 |
"fig.subplots_adjust(hspace=0.4, wspace=0.4)\n", |
|
|
192 |
"ax = fig.add_subplot(1, 2, 1)\n", |
|
|
193 |
"ax.imshow(x[r])\n", |
|
|
194 |
"ax = fig.add_subplot(1, 2, 2)\n", |
|
|
195 |
"ax.imshow(np.reshape(y[r], (image_size, image_size)), cmap=\"gray\")" |
|
|
196 |
] |
|
|
197 |
}, |
|
|
198 |
{ |
|
|
199 |
"cell_type": "markdown", |
|
|
200 |
"metadata": { |
|
|
201 |
"id": "1xJMvRqswZ8o" |
|
|
202 |
}, |
|
|
203 |
"source": [ |
|
|
204 |
"## Different Convolutional Blocks" |
|
|
205 |
] |
|
|
206 |
}, |
|
|
207 |
{ |
|
|
208 |
"cell_type": "code", |
|
|
209 |
"execution_count": null, |
|
|
210 |
"metadata": { |
|
|
211 |
"id": "xtA9Rr75wZ8p" |
|
|
212 |
}, |
|
|
213 |
"outputs": [], |
|
|
214 |
"source": [ |
|
|
215 |
"def down_block(x, filters, kernel_size=(3, 3), padding=\"same\", strides=1):\n", |
|
|
216 |
" c = keras.layers.Conv2D(filters, kernel_size, padding=padding, strides=strides, activation=\"relu\")(x)\n", |
|
|
217 |
" c = keras.layers.Conv2D(filters, kernel_size, padding=padding, strides=strides, activation=\"relu\")(c)\n", |
|
|
218 |
" p = keras.layers.MaxPool2D((2, 2), (2, 2))(c)\n", |
|
|
219 |
" return c, p\n", |
|
|
220 |
"\n", |
|
|
221 |
"def up_block(x, skip, filters, kernel_size=(3, 3), padding=\"same\", strides=1):\n", |
|
|
222 |
" us = keras.layers.UpSampling2D((2, 2))(x)\n", |
|
|
223 |
" concat = keras.layers.Concatenate()([us, skip])\n", |
|
|
224 |
" c = keras.layers.Conv2D(filters, kernel_size, padding=padding, strides=strides, activation=\"relu\")(concat)\n", |
|
|
225 |
" c = keras.layers.Conv2D(filters, kernel_size, padding=padding, strides=strides, activation=\"relu\")(c)\n", |
|
|
226 |
" return c\n", |
|
|
227 |
"\n", |
|
|
228 |
"def bottleneck(x, filters, kernel_size=(3, 3), padding=\"same\", strides=1):\n", |
|
|
229 |
" c = keras.layers.Conv2D(filters, kernel_size, padding=padding, strides=strides, activation=\"relu\")(x)\n", |
|
|
230 |
" c = keras.layers.Conv2D(filters, kernel_size, padding=padding, strides=strides, activation=\"relu\")(c)\n", |
|
|
231 |
" return c" |
|
|
232 |
] |
|
|
233 |
}, |
|
|
234 |
{ |
|
|
235 |
"cell_type": "markdown", |
|
|
236 |
"metadata": { |
|
|
237 |
"id": "QMdNQ_HVwZ82" |
|
|
238 |
}, |
|
|
239 |
"source": [ |
|
|
240 |
"## UNet Model" |
|
|
241 |
] |
|
|
242 |
}, |
|
|
243 |
{ |
|
|
244 |
"cell_type": "code", |
|
|
245 |
"execution_count": null, |
|
|
246 |
"metadata": { |
|
|
247 |
"id": "YAa1RbB8wZ89" |
|
|
248 |
}, |
|
|
249 |
"outputs": [], |
|
|
250 |
"source": [ |
|
|
251 |
"def UNet():\n", |
|
|
252 |
" f = [16, 32, 64, 128, 256]\n", |
|
|
253 |
" inputs = keras.layers.Input((image_size, image_size, 3))\n", |
|
|
254 |
"\n", |
|
|
255 |
" p0 = inputs\n", |
|
|
256 |
" c1, p1 = down_block(p0, f[0]) # 128 --> 64\n", |
|
|
257 |
" c2, p2 = down_block(p1, f[1]) # 64 --> 32\n", |
|
|
258 |
" c3, p3 = down_block(p2, f[2]) # 32 --> 16\n", |
|
|
259 |
" c4, p4 = down_block(p3, f[3]) # 16 --> 8\n", |
|
|
260 |
"\n", |
|
|
261 |
" bn = bottleneck(p4, f[4])\n", |
|
|
262 |
"\n", |
|
|
263 |
" u1 = up_block(bn, c4, f[3]) # 8 --> 16\n", |
|
|
264 |
" u2 = up_block(u1, c3, f[2]) # 16 --> 32\n", |
|
|
265 |
" u3 = up_block(u2, c2, f[1]) # 32 --> 64\n", |
|
|
266 |
" u4 = up_block(u3, c1, f[0]) # 64 --> 128\n", |
|
|
267 |
"\n", |
|
|
268 |
" outputs = keras.layers.Conv2D(1, (1, 1), padding=\"same\", activation=\"sigmoid\")(u4)\n", |
|
|
269 |
" model = keras.models.Model(inputs, outputs)\n", |
|
|
270 |
" return model" |
|
|
271 |
] |
|
|
272 |
}, |
|
|
273 |
{ |
|
|
274 |
"cell_type": "code", |
|
|
275 |
"execution_count": null, |
|
|
276 |
"metadata": { |
|
|
277 |
"colab": { |
|
|
278 |
"base_uri": "https://localhost:8080/", |
|
|
279 |
"height": 1000 |
|
|
280 |
}, |
|
|
281 |
"id": "ntBPY06awZ9E", |
|
|
282 |
"outputId": "bc8241cf-1ca4-46a5-ddf1-afcb43ddc395", |
|
|
283 |
"scrolled": true |
|
|
284 |
}, |
|
|
285 |
"outputs": [], |
|
|
286 |
"source": [ |
|
|
287 |
"model = UNet()\n", |
|
|
288 |
"model.compile(optimizer=\"adam\", loss=\"binary_crossentropy\", metrics=[\"acc\"])\n", |
|
|
289 |
"model.summary()" |
|
|
290 |
] |
|
|
291 |
}, |
|
|
292 |
{ |
|
|
293 |
"cell_type": "markdown", |
|
|
294 |
"metadata": { |
|
|
295 |
"id": "Nmkxq4-BwZ9Q" |
|
|
296 |
}, |
|
|
297 |
"source": [ |
|
|
298 |
"## Training the model" |
|
|
299 |
] |
|
|
300 |
}, |
|
|
301 |
{ |
|
|
302 |
"cell_type": "code", |
|
|
303 |
"execution_count": null, |
|
|
304 |
"metadata": { |
|
|
305 |
"colab": { |
|
|
306 |
"base_uri": "https://localhost:8080/" |
|
|
307 |
}, |
|
|
308 |
"id": "6I34e4tcwZ9T", |
|
|
309 |
"outputId": "427bd73a-0c95-4b03-ce95-6584de960233", |
|
|
310 |
"scrolled": false |
|
|
311 |
}, |
|
|
312 |
"outputs": [], |
|
|
313 |
"source": [ |
|
|
314 |
"train_gen = DataGen(train_ids, train_path, image_size=image_size, batch_size=batch_size)\n", |
|
|
315 |
"valid_gen = DataGen(valid_ids, train_path, image_size=image_size, batch_size=batch_size)\n", |
|
|
316 |
"\n", |
|
|
317 |
"train_steps = len(train_ids)//batch_size\n", |
|
|
318 |
"valid_steps = len(valid_ids)//batch_size\n", |
|
|
319 |
"\n", |
|
|
320 |
"history = model.fit(train_gen, validation_data=valid_gen, steps_per_epoch=train_steps,\n", |
|
|
321 |
" validation_steps=valid_steps, epochs=epochs)\n", |
|
|
322 |
"\n", |
|
|
323 |
"# Save the weights\n", |
|
|
324 |
"model.save_weights(\"UNetW.weights.h5\")\n", |
|
|
325 |
"\n", |
|
|
326 |
"# Plot training & validation accuracy and loss\n", |
|
|
327 |
"acc = history.history['acc']\n", |
|
|
328 |
"val_acc = history.history['val_acc']\n", |
|
|
329 |
"loss = history.history['loss']\n", |
|
|
330 |
"val_loss = history.history['val_loss']\n", |
|
|
331 |
"num_epochs = min(len(acc), len(val_acc))\n", |
|
|
332 |
"epochs_range = range(1, num_epochs + 1)\n", |
|
|
333 |
"\n", |
|
|
334 |
"plt.figure(figsize=(16, 6))\n", |
|
|
335 |
"\n", |
|
|
336 |
"# Accuracy plot\n", |
|
|
337 |
"plt.subplot(1, 2, 1)\n", |
|
|
338 |
"plt.plot(epochs_range, acc[:num_epochs], label='Training Accuracy')\n", |
|
|
339 |
"plt.plot(epochs_range, val_acc[:num_epochs], label='Validation Accuracy')\n", |
|
|
340 |
"plt.title('Training & Validation Accuracy')\n", |
|
|
341 |
"plt.xlabel('Epoch')\n", |
|
|
342 |
"plt.ylabel('Accuracy')\n", |
|
|
343 |
"plt.legend()\n", |
|
|
344 |
"\n", |
|
|
345 |
"# Loss plot\n", |
|
|
346 |
"plt.subplot(1, 2, 2)\n", |
|
|
347 |
"plt.plot(epochs_range, loss[:num_epochs], label='Training Loss')\n", |
|
|
348 |
"plt.plot(epochs_range, val_loss[:num_epochs], label='Validation Loss')\n", |
|
|
349 |
"plt.title('Training & Validation Loss')\n", |
|
|
350 |
"plt.xlabel('Epoch')\n", |
|
|
351 |
"plt.ylabel('Loss')\n", |
|
|
352 |
"plt.legend()\n", |
|
|
353 |
"\n", |
|
|
354 |
"plt.show()" |
|
|
355 |
] |
|
|
356 |
}, |
|
|
357 |
{ |
|
|
358 |
"cell_type": "markdown", |
|
|
359 |
"metadata": { |
|
|
360 |
"id": "iDUykT_awZ9h" |
|
|
361 |
}, |
|
|
362 |
"source": [ |
|
|
363 |
"## Testing the model" |
|
|
364 |
] |
|
|
365 |
}, |
|
|
366 |
{ |
|
|
367 |
"cell_type": "code", |
|
|
368 |
"execution_count": null, |
|
|
369 |
"metadata": { |
|
|
370 |
"colab": { |
|
|
371 |
"base_uri": "https://localhost:8080/" |
|
|
372 |
}, |
|
|
373 |
"id": "i_oY4H3LwZ9l", |
|
|
374 |
"outputId": "371b3f40-25d0-416c-fd0f-e3eb6b0df943" |
|
|
375 |
}, |
|
|
376 |
"outputs": [], |
|
|
377 |
"source": [ |
|
|
378 |
"## Save the Weights\n", |
|
|
379 |
"model.save_weights(\"UNetW.weights.h5\")\n", |
|
|
380 |
"\n", |
|
|
381 |
"## Dataset for prediction\n", |
|
|
382 |
"x, y = valid_gen.__getitem__(2)\n", |
|
|
383 |
"result = model.predict(x)\n", |
|
|
384 |
"\n", |
|
|
385 |
"result = result > 0.5" |
|
|
386 |
] |
|
|
387 |
}, |
|
|
388 |
{ |
|
|
389 |
"cell_type": "code", |
|
|
390 |
"execution_count": null, |
|
|
391 |
"metadata": { |
|
|
392 |
"id": "DLdgSxZKpQcQ" |
|
|
393 |
}, |
|
|
394 |
"outputs": [], |
|
|
395 |
"source": [ |
|
|
396 |
"\n", |
|
|
397 |
"# Load the weights\n", |
|
|
398 |
"model.load_weights(\"UNetW.weights.h5\")\n", |
|
|
399 |
"\n", |
|
|
400 |
"# Now you can use the model for predictions or further training\n", |
|
|
401 |
"x, y = valid_gen.__getitem__(2)\n", |
|
|
402 |
"result = model.predict(x)\n", |
|
|
403 |
"result = result > 0.5" |
|
|
404 |
] |
|
|
405 |
}, |
|
|
406 |
{ |
|
|
407 |
"cell_type": "code", |
|
|
408 |
"execution_count": null, |
|
|
409 |
"metadata": { |
|
|
410 |
"colab": { |
|
|
411 |
"base_uri": "https://localhost:8080/", |
|
|
412 |
"height": 309 |
|
|
413 |
}, |
|
|
414 |
"id": "uSdH42qVwZ9q", |
|
|
415 |
"outputId": "95c65b4e-5f31-4a9e-88a1-d416166ec239" |
|
|
416 |
}, |
|
|
417 |
"outputs": [], |
|
|
418 |
"source": [ |
|
|
419 |
"fig = plt.figure()\n", |
|
|
420 |
"fig.subplots_adjust(hspace=0.4, wspace=0.4)\n", |
|
|
421 |
"\n", |
|
|
422 |
"ax = fig.add_subplot(1, 2, 1)\n", |
|
|
423 |
"ax.imshow(np.reshape(y[0]*255, (image_size, image_size)), cmap=\"gray\")\n", |
|
|
424 |
"\n", |
|
|
425 |
"ax = fig.add_subplot(1, 2, 2)\n", |
|
|
426 |
"ax.imshow(np.reshape(result[0]*255, (image_size, image_size)), cmap=\"gray\")" |
|
|
427 |
] |
|
|
428 |
}, |
|
|
429 |
{ |
|
|
430 |
"cell_type": "code", |
|
|
431 |
"execution_count": null, |
|
|
432 |
"metadata": { |
|
|
433 |
"colab": { |
|
|
434 |
"base_uri": "https://localhost:8080/", |
|
|
435 |
"height": 309 |
|
|
436 |
}, |
|
|
437 |
"id": "1OKwJGbVwZ-A", |
|
|
438 |
"outputId": "8ef32166-359f-4023-f3a4-f12aeb895db0" |
|
|
439 |
}, |
|
|
440 |
"outputs": [], |
|
|
441 |
"source": [ |
|
|
442 |
"fig = plt.figure()\n", |
|
|
443 |
"fig.subplots_adjust(hspace=0.4, wspace=0.4)\n", |
|
|
444 |
"\n", |
|
|
445 |
"ax = fig.add_subplot(1, 2, 1)\n", |
|
|
446 |
"ax.imshow(np.reshape(y[1]*255, (image_size, image_size)), cmap=\"gray\")\n", |
|
|
447 |
"\n", |
|
|
448 |
"ax = fig.add_subplot(1, 2, 2)\n", |
|
|
449 |
"ax.imshow(np.reshape(result[1]*255, (image_size, image_size)), cmap=\"gray\")" |
|
|
450 |
] |
|
|
451 |
}, |
|
|
452 |
{ |
|
|
453 |
"cell_type": "markdown", |
|
|
454 |
"metadata": {}, |
|
|
455 |
"source": [ |
|
|
456 |
"# CNN Model (Madhurya)" |
|
|
457 |
] |
|
|
458 |
}, |
|
|
459 |
{ |
|
|
460 |
"cell_type": "code", |
|
|
461 |
"execution_count": null, |
|
|
462 |
"metadata": { |
|
|
463 |
"colab": { |
|
|
464 |
"base_uri": "https://localhost:8080/", |
|
|
465 |
"height": 1000 |
|
|
466 |
}, |
|
|
467 |
"id": "xBk2k9vzKRD5", |
|
|
468 |
"outputId": "e9880f4e-a1a6-4c3b-aac7-bacca57154e5" |
|
|
469 |
}, |
|
|
470 |
"outputs": [], |
|
|
471 |
"source": [ |
|
|
472 |
"import os\n", |
|
|
473 |
"import cv2\n", |
|
|
474 |
"import numpy as np\n", |
|
|
475 |
"import matplotlib.pyplot as plt\n", |
|
|
476 |
"\n", |
|
|
477 |
"import keras\n", |
|
|
478 |
"from keras.models import Sequential\n", |
|
|
479 |
"from keras.layers import Dense, Activation, Flatten, Reshape\n", |
|
|
480 |
"from keras.layers import Conv2D, MaxPooling2D, AveragePooling2D\n", |
|
|
481 |
"from keras import regularizers\n", |
|
|
482 |
"\n", |
|
|
483 |
"# Set your data directory\n", |
|
|
484 |
"data_dir = '/Users/sandhyakilari/Desktop/Fall Semester 2024/Computer Vision/Segmentation Project'\n", |
|
|
485 |
"image_dir = os.path.join(data_dir, \"images\")\n", |
|
|
486 |
"mask_dir = os.path.join(data_dir, \"masks\")\n", |
|
|
487 |
"\n", |
|
|
488 |
"# List files\n", |
|
|
489 |
"image_names = sorted(os.listdir(image_dir))\n", |
|
|
490 |
"mask_names = sorted(os.listdir(mask_dir))\n", |
|
|
491 |
"\n", |
|
|
492 |
"image_names = [name for name in image_names if name in mask_names]\n", |
|
|
493 |
"\n", |
|
|
494 |
"# Make sure that image_names and mask_names correspond one-to-one\n", |
|
|
495 |
"# If they differ, ensure file naming consistency before running.\n", |
|
|
496 |
"assert len(image_names) == len(mask_names), \"Number of images and masks do not match.\"\n", |
|
|
497 |
"\n", |
|
|
498 |
"# Desired shapes\n", |
|
|
499 |
"input_image_shape = (64, 64) # For the CNN input\n", |
|
|
500 |
"mask_shape = (32, 32) # For the CNN output\n", |
|
|
501 |
"\n", |
|
|
502 |
"X = []\n", |
|
|
503 |
"Y = []\n", |
|
|
504 |
"\n", |
|
|
505 |
"for img_name, msk_name in zip(image_names, mask_names):\n", |
|
|
506 |
" img_path = os.path.join(image_dir, img_name)\n", |
|
|
507 |
" msk_path = os.path.join(mask_dir, msk_name)\n", |
|
|
508 |
"\n", |
|
|
509 |
" # Read images in grayscale\n", |
|
|
510 |
" img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)\n", |
|
|
511 |
" msk = cv2.imread(msk_path, cv2.IMREAD_GRAYSCALE)\n", |
|
|
512 |
"\n", |
|
|
513 |
" # Resize to desired shapes\n", |
|
|
514 |
" img = cv2.resize(img, input_image_shape)\n", |
|
|
515 |
" msk = cv2.resize(msk, mask_shape)\n", |
|
|
516 |
"\n", |
|
|
517 |
" # Normalize (if you want to normalize)\n", |
|
|
518 |
" img = img.astype(np.float32) / 255.0\n", |
|
|
519 |
" msk = msk.astype(np.float32) / 255.0\n", |
|
|
520 |
"\n", |
|
|
521 |
" # Add channel dimension\n", |
|
|
522 |
" img = np.expand_dims(img, axis=-1) # (64,64,1)\n", |
|
|
523 |
" msk = np.expand_dims(msk, axis=-1) # (32,32,1)\n", |
|
|
524 |
"\n", |
|
|
525 |
" X.append(img)\n", |
|
|
526 |
" Y.append(msk)\n", |
|
|
527 |
"\n", |
|
|
528 |
"X = np.array(X)\n", |
|
|
529 |
"Y = np.array(Y)\n", |
|
|
530 |
"\n", |
|
|
531 |
"print('Dataset shape :', X.shape, Y.shape) # X: (N,64,64,1), Y: (N,32,32,1)\n", |
|
|
532 |
"\n", |
|
|
533 |
"# Create the CNN model\n", |
|
|
534 |
"def create_model(input_shape=(64, 64, 1)):\n", |
|
|
535 |
" \"\"\"\n", |
|
|
536 |
" Simple convnet model: one convolution, one average pooling and one fully connected layer\n", |
|
|
537 |
" ending with a reshape to (32,32,1).\n", |
|
|
538 |
" \"\"\"\n", |
|
|
539 |
" model = Sequential()\n", |
|
|
540 |
" # Conv layer\n", |
|
|
541 |
" model.add(Conv2D(100, (11,11), padding='valid', strides=(1, 1), input_shape=input_shape))\n", |
|
|
542 |
" # Average Pooling\n", |
|
|
543 |
" model.add(AveragePooling2D((6,6)))\n", |
|
|
544 |
" # Flatten/Reshape step\n", |
|
|
545 |
" # After Conv+Pool:\n", |
|
|
546 |
" # Input: (64x64x1) -> Conv(11x11): (54x54x100) -> AvgPool(6x6): (9x9x100) = 8100 features\n", |
|
|
547 |
" model.add(Reshape((8100,))) # Flatten to (8100,)\n", |
|
|
548 |
" model.add(Dense(1024, activation='sigmoid', kernel_regularizer=regularizers.l2(0.0001)))\n", |
|
|
549 |
" # Now we have (1024,). We want (32,32,1):\n", |
|
|
550 |
" # 32*32 = 1024, so we reshape to (32,32,1)\n", |
|
|
551 |
" model.add(Reshape((32,32,1)))\n", |
|
|
552 |
" return model\n", |
|
|
553 |
"\n", |
|
|
554 |
"m = create_model()\n", |
|
|
555 |
"m.compile(loss='mean_squared_error', optimizer='adam', metrics=['accuracy'])\n", |
|
|
556 |
"print('Model Summary:')\n", |
|
|
557 |
"m.summary()\n", |
|
|
558 |
"\n", |
|
|
559 |
"# Train the model\n", |
|
|
560 |
"epochs = 20\n", |
|
|
561 |
"batch_size = 16\n", |
|
|
562 |
"history = m.fit(X, Y, batch_size=batch_size, epochs=epochs, validation_split=0.2)\n", |
|
|
563 |
"\n", |
|
|
564 |
"# Plot training and validation loss\n", |
|
|
565 |
"plt.figure(figsize=(10,5))\n", |
|
|
566 |
"plt.plot(history.history['loss'], label='Training Loss')\n", |
|
|
567 |
"plt.plot(history.history['val_loss'], label='Validation Loss', linestyle='--')\n", |
|
|
568 |
"plt.title(\"Learning Curve\")\n", |
|
|
569 |
"plt.xlabel(\"Epochs\")\n", |
|
|
570 |
"plt.ylabel(\"Loss\")\n", |
|
|
571 |
"plt.legend()\n", |
|
|
572 |
"plt.show()\n", |
|
|
573 |
"\n", |
|
|
574 |
"# Save the weights\n", |
|
|
575 |
"m.save_weights(\"UNetW.weights.h5\")\n", |
|
|
576 |
"\n", |
|
|
577 |
"# Example prediction\n", |
|
|
578 |
"y_pred = m.predict(X, batch_size=batch_size)\n", |
|
|
579 |
"print(\"y_pred shape:\", y_pred.shape)\n", |
|
|
580 |
"\n", |
|
|
581 |
"# Visualize a sample\n", |
|
|
582 |
"idx = 0\n", |
|
|
583 |
"fig, ax = plt.subplots(1, 2, figsize=(8,4))\n", |
|
|
584 |
"ax[0].imshow(X[idx].reshape(64,64), cmap='gray')\n", |
|
|
585 |
"ax[0].set_title('Input Image')\n", |
|
|
586 |
"ax[1].imshow(y_pred[idx].reshape(32,32), cmap='gray')\n", |
|
|
587 |
"ax[1].set_title('Predicted Mask')\n", |
|
|
588 |
"plt.show()" |
|
|
589 |
] |
|
|
590 |
}, |
|
|
591 |
{ |
|
|
592 |
"cell_type": "markdown", |
|
|
593 |
"metadata": {}, |
|
|
594 |
"source": [ |
|
|
595 |
"# AttentionUNET (Vishal)" |
|
|
596 |
] |
|
|
597 |
}, |
|
|
598 |
{ |
|
|
599 |
"cell_type": "code", |
|
|
600 |
"execution_count": null, |
|
|
601 |
"metadata": {}, |
|
|
602 |
"outputs": [], |
|
|
603 |
"source": [ |
|
|
604 |
"import tensorflow as tf\n", |
|
|
605 |
"from tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, UpSampling2D, concatenate, Activation, BatchNormalization, Add, Multiply\n", |
|
|
606 |
"from tensorflow.keras.models import Model\n", |
|
|
607 |
"import os\n", |
|
|
608 |
"import numpy as np\n", |
|
|
609 |
"from tensorflow.keras.preprocessing.image import load_img, img_to_array\n", |
|
|
610 |
"\n", |
|
|
611 |
"def attention_block(x, g, inter_channel):\n", |
|
|
612 |
" \"\"\"\n", |
|
|
613 |
" Attention Block: Refines encoder features based on decoder signals.\n", |
|
|
614 |
" x: Input tensor from the encoder (skip connection)\n", |
|
|
615 |
" g: Gating signal from the decoder (upsampled tensor)\n", |
|
|
616 |
" inter_channel: Number of intermediate channels (reduces computation)\n", |
|
|
617 |
" \"\"\"\n", |
|
|
618 |
" # 1x1 Convolution on input tensor\n", |
|
|
619 |
" theta_x = Conv2D(inter_channel, kernel_size=(1, 1), strides=(1, 1), padding='same')(x)\n", |
|
|
620 |
" # 1x1 Convolution on gating tensor\n", |
|
|
621 |
" phi_g = Conv2D(inter_channel, kernel_size=(1, 1), strides=(1, 1), padding='same')(g)\n", |
|
|
622 |
" \n", |
|
|
623 |
" # Add the transformed inputs and apply ReLU\n", |
|
|
624 |
" add_xg = Add()([theta_x, phi_g])\n", |
|
|
625 |
" relu_xg = Activation('relu')(add_xg)\n", |
|
|
626 |
" \n", |
|
|
627 |
" # Another 1x1 Convolution to generate attention coefficients\n", |
|
|
628 |
" psi = Conv2D(1, kernel_size=(1, 1), strides=(1, 1), padding='same')(relu_xg)\n", |
|
|
629 |
" # Sigmoid activation to normalize attention weights\n", |
|
|
630 |
" sigmoid_psi = Activation('sigmoid')(psi)\n", |
|
|
631 |
" \n", |
|
|
632 |
" # Multiply the input tensor with the attention weights\n", |
|
|
633 |
" return Multiply()([x, sigmoid_psi])\n", |
|
|
634 |
"\n", |
|
|
635 |
"def conv_block(x, filters):\n", |
|
|
636 |
" \"\"\"\n", |
|
|
637 |
" Convolutional Block: Apply two 3x3 convolutions followed by BatchNorm and ReLU.\n", |
|
|
638 |
" x: Input tensor\n", |
|
|
639 |
" filters: Number of output filters for the convolutions\n", |
|
|
640 |
" \"\"\"\n", |
|
|
641 |
" x = Conv2D(filters, kernel_size=(3, 3), padding='same')(x)\n", |
|
|
642 |
" x = BatchNormalization()(x)\n", |
|
|
643 |
" x = Activation('relu')(x)\n", |
|
|
644 |
" x = Conv2D(filters, kernel_size=(3, 3), padding='same')(x)\n", |
|
|
645 |
" x = BatchNormalization()(x)\n", |
|
|
646 |
" x = Activation('relu')(x)\n", |
|
|
647 |
" return x\n", |
|
|
648 |
"\n", |
|
|
649 |
"def attention_unet(input_shape, num_classes):\n", |
|
|
650 |
" \"\"\"\n", |
|
|
651 |
" Attention U-Net model architecture.\n", |
|
|
652 |
" input_shape: Shape of input images (H, W, C)\n", |
|
|
653 |
" num_classes: Number of output segmentation classes\n", |
|
|
654 |
" \"\"\"\n", |
|
|
655 |
" # Input layer for the images\n", |
|
|
656 |
" inputs = Input(input_shape)\n", |
|
|
657 |
" \n", |
|
|
658 |
" # Encoder (Downsampling path)\n", |
|
|
659 |
" c1 = conv_block(inputs, 64) # First Conv Block\n", |
|
|
660 |
" p1 = MaxPooling2D((2, 2))(c1) # Downsample by 2\n", |
|
|
661 |
" \n", |
|
|
662 |
" c2 = conv_block(p1, 128) # Second Conv Block\n", |
|
|
663 |
" p2 = MaxPooling2D((2, 2))(c2) # Downsample by 2\n", |
|
|
664 |
" \n", |
|
|
665 |
" c3 = conv_block(p2, 256) # Third Conv Block\n", |
|
|
666 |
" p3 = MaxPooling2D((2, 2))(c3) # Downsample by 2\n", |
|
|
667 |
" \n", |
|
|
668 |
" c4 = conv_block(p3, 512) # Fourth Conv Block\n", |
|
|
669 |
" p4 = MaxPooling2D((2, 2))(c4) # Downsample by 2\n", |
|
|
670 |
" \n", |
|
|
671 |
" # Bottleneck (lowest level of the U-Net)\n", |
|
|
672 |
" c5 = conv_block(p4, 1024)\n", |
|
|
673 |
" \n", |
|
|
674 |
" # Decoder (Upsampling path)\n", |
|
|
675 |
" up6 = UpSampling2D((2, 2))(c5) # Upsample\n", |
|
|
676 |
" att6 = attention_block(c4, up6, 512) # Attention Block\n", |
|
|
677 |
" merge6 = concatenate([up6, att6], axis=-1) # Concatenate features\n", |
|
|
678 |
" c6 = conv_block(merge6, 512) # Conv Block after concatenation\n", |
|
|
679 |
" \n", |
|
|
680 |
" up7 = UpSampling2D((2, 2))(c6)\n", |
|
|
681 |
" att7 = attention_block(c3, up7, 256)\n", |
|
|
682 |
" merge7 = concatenate([up7, att7], axis=-1)\n", |
|
|
683 |
" c7 = conv_block(merge7, 256)\n", |
|
|
684 |
" \n", |
|
|
685 |
" up8 = UpSampling2D((2, 2))(c7)\n", |
|
|
686 |
" att8 = attention_block(c2, up8, 128)\n", |
|
|
687 |
" merge8 = concatenate([up8, att8], axis=-1)\n", |
|
|
688 |
" c8 = conv_block(merge8, 128)\n", |
|
|
689 |
" \n", |
|
|
690 |
" up9 = UpSampling2D((2, 2))(c8)\n", |
|
|
691 |
" att9 = attention_block(c1, up9, 64)\n", |
|
|
692 |
" merge9 = concatenate([up9, att9], axis=-1)\n", |
|
|
693 |
" c9 = conv_block(merge9, 64)\n", |
|
|
694 |
" \n", |
|
|
695 |
" # Output layer for segmentation\n", |
|
|
696 |
" outputs = Conv2D(num_classes, (1, 1), activation='softmax' if num_classes > 1 else 'sigmoid')(c9)\n", |
|
|
697 |
" \n", |
|
|
698 |
" # Define the model\n", |
|
|
699 |
" model = Model(inputs=inputs, outputs=outputs)\n", |
|
|
700 |
" return model\n", |
|
|
701 |
"\n", |
|
|
702 |
"# Function to load and preprocess images and masks\n", |
|
|
703 |
"def load_data(image_dir, mask_dir, image_size):\n", |
|
|
704 |
" \"\"\"\n", |
|
|
705 |
" Load and preprocess images and masks for training.\n", |
|
|
706 |
" image_dir: Path to the directory containing input images\n", |
|
|
707 |
" mask_dir: Path to the directory containing segmentation masks\n", |
|
|
708 |
" image_size: Tuple specifying the size (height, width) to resize the images and masks\n", |
|
|
709 |
" \"\"\"\n", |
|
|
710 |
" images = []\n", |
|
|
711 |
" masks = []\n", |
|
|
712 |
" image_files = sorted(os.listdir(image_dir))\n", |
|
|
713 |
" mask_files = sorted(os.listdir(mask_dir))\n", |
|
|
714 |
" \n", |
|
|
715 |
" for img_file, mask_file in zip(image_files, mask_files):\n", |
|
|
716 |
" try:\n", |
|
|
717 |
" # Load and preprocess images\n", |
|
|
718 |
" img_path = os.path.join(image_dir, img_file)\n", |
|
|
719 |
" mask_path = os.path.join(mask_dir, mask_file)\n", |
|
|
720 |
" \n", |
|
|
721 |
" img = load_img(img_path, target_size=image_size) # Resize image\n", |
|
|
722 |
" mask = load_img(mask_path, target_size=image_size, color_mode='grayscale') # Resize mask\n", |
|
|
723 |
" \n", |
|
|
724 |
" # Convert to numpy arrays and normalize\n", |
|
|
725 |
" img = img_to_array(img) / 255.0\n", |
|
|
726 |
" mask = img_to_array(mask) / 255.0\n", |
|
|
727 |
" mask = np.round(mask) # Ensure masks are binary\n", |
|
|
728 |
" \n", |
|
|
729 |
" images.append(img)\n", |
|
|
730 |
" masks.append(mask)\n", |
|
|
731 |
" except Exception as e:\n", |
|
|
732 |
" print(f\"Error loading {img_file} or {mask_file}: {e}. Skipping...\")\n", |
|
|
733 |
" \n", |
|
|
734 |
" return np.array(images), np.array(masks)\n", |
|
|
735 |
"\n", |
|
|
736 |
"# Example usage\n", |
|
|
737 |
"if __name__ == \"__main__\":\n", |
|
|
738 |
" # Load data\n", |
|
|
739 |
" image_dir = \"./images/\" # Replace with your image directory\n", |
|
|
740 |
" mask_dir = \"./masks/\" # Replace with your mask directory\n", |
|
|
741 |
" image_size = (128, 128) # Resize all images to 128x128\n", |
|
|
742 |
" images, masks = load_data(image_dir, mask_dir, image_size)\n", |
|
|
743 |
" \n", |
|
|
744 |
" # Define the model\n", |
|
|
745 |
" model = attention_unet(input_shape=(128, 128, 3), num_classes=1)\n", |
|
|
746 |
" \n", |
|
|
747 |
" # Compile the model\n", |
|
|
748 |
" model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])\n", |
|
|
749 |
" \n", |
|
|
750 |
" # Train the model\n", |
|
|
751 |
" model.fit(images, masks, batch_size=8, epochs=20, validation_split=0.1)" |
|
|
752 |
] |
|
|
753 |
} |
|
|
754 |
], |
|
|
755 |
"metadata": { |
|
|
756 |
"accelerator": "GPU", |
|
|
757 |
"colab": { |
|
|
758 |
"provenance": [] |
|
|
759 |
}, |
|
|
760 |
"kernelspec": { |
|
|
761 |
"display_name": "base", |
|
|
762 |
"language": "python", |
|
|
763 |
"name": "python3" |
|
|
764 |
}, |
|
|
765 |
"language_info": { |
|
|
766 |
"codemirror_mode": { |
|
|
767 |
"name": "ipython", |
|
|
768 |
"version": 3 |
|
|
769 |
}, |
|
|
770 |
"file_extension": ".py", |
|
|
771 |
"mimetype": "text/x-python", |
|
|
772 |
"name": "python", |
|
|
773 |
"nbconvert_exporter": "python", |
|
|
774 |
"pygments_lexer": "ipython3", |
|
|
775 |
"version": "3.12.2" |
|
|
776 |
} |
|
|
777 |
}, |
|
|
778 |
"nbformat": 4, |
|
|
779 |
"nbformat_minor": 0 |
|
|
780 |
} |