├── LICENSE ├── MLNet_Pytorch.ipynb ├── README.md └── readme-content ├── 1.png ├── 1_gt.png ├── 1_pred.png ├── 2.png ├── 2_gt.png ├── 2_pred.png ├── 3.png ├── 3_gt.png ├── 3_pred.png ├── 4.png ├── 4_gt.png └── 4_pred.png /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /MLNet_Pytorch.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "name": "MLNet_Pytorch.ipynb", 7 | "version": "0.3.2", 8 | "provenance": [], 9 | "collapsed_sections": [], 10 | "toc_visible": true 11 | }, 12 | "kernelspec": { 13 | "name": "python3", 14 | "display_name": "Python 3" 15 | }, 16 | "accelerator": "GPU" 17 | }, 18 | "cells": [ 19 | { 20 | "metadata": { 21 | "id": "MqXah3GAjj0E", 22 | "colab_type": "text" 23 | }, 24 | "cell_type": "markdown", 25 | "source": [ 26 | "# MLNet \n", 27 | "\n", 28 | "#### Implementation of Deep Multi-level Network for Saliency in Pytorch\n", 29 | "\n", 30 | "#### Paper : Marcella Cornia, Lorenzo Baraldi, Giuseppe Serra, Rita Cucchiara. \"A Deep Multi-Level Network for Saliency Prediction.\" In Proceedings of the 23rd International Conference on Pattern Recognition, 2016.\n", 31 | "\n", 32 | "#### Reference Code : [link text](https://github.com/marcellacornia/mlnet)" 33 | ] 34 | }, 35 | { 36 | "metadata": { 37 | "id": "AqzJAUOGocqN", 38 | "colab_type": "text" 39 | }, 40 | "cell_type": "markdown", 41 | "source": [ 42 | "## 0. Downloading Data " 43 | ] 44 | }, 45 | { 46 | "metadata": { 47 | "id": "dk-y5y_vC8OL", 48 | "colab_type": "text" 49 | }, 50 | "cell_type": "markdown", 51 | "source": [ 52 | "### 0.0 Downloading Salicon Dataset which was used in Paper for training and benchmarking.\n", 53 | "\n", 54 | "### linke : http://salicon.net/\n", 55 | "\n", 56 | "\n", 57 | "---\n", 58 | "\n", 59 | "\n", 60 | "\n", 61 | "### Short Information about Dataset:\n", 62 | "\n", 63 | "Dataset contains total of 20,000 Images. Dataset is splited into 3 parts. Train, Validation and Testing containing 10,000 , 5,000 and 5,000 respectively. Saliency Map of Train and Validation is giving. For testing we have to upload result to coda lab which will evalute our prediction maps agianst groud truth and gives score. More information about Dataset and Codalab challenge can be found at http://salicon.net/challenge-2017/.\n", 64 | " \n", 65 | " \n", 66 | " " 67 | ] 68 | }, 69 | { 70 | "metadata": { 71 | "id": "LjYnvpkilL8N", 72 | "colab_type": "code", 73 | "colab": {} 74 | }, 75 | "cell_type": "code", 76 | "source": [ 77 | "# Data Downloading from salicon dataset\n", 78 | "!wget http://lsun.cs.princeton.edu/challenge/2015/eyetracking_salicon/data/image.zip\n", 79 | "# unzipping data\n", 80 | "!unzip image.zip > unzipping.log\n", 81 | "!ls images | head -5\n", 82 | "\n", 83 | "# installing gdown\n", 84 | "# Reference : https://stackoverflow.com/questions/25010369/wget-curl-large-file-from-google-drive\n", 85 | "! pip install gdown\n", 86 | "\n", 87 | "# Dowloading Ground Truth\n", 88 | "! gdown https://drive.google.com/uc?id=0B2hsWbciDVedNWJZMlRxeW1PY1U&export=download\n", 89 | " \n", 90 | "# unzipping maps (ground truth)\n", 91 | "! unzip maps.zip > unzipping_maps.log\n", 92 | "\n", 93 | "# unzipping creates two folders containing saliency maps\n", 94 | "# 1. train\n", 95 | "# 2. test\n", 96 | "!ls train | head -5" 97 | ], 98 | "execution_count": 0, 99 | "outputs": [] 100 | }, 101 | { 102 | "metadata": { 103 | "id": "wUzj_PvjEX7P", 104 | "colab_type": "text" 105 | }, 106 | "cell_type": "markdown", 107 | "source": [ 108 | "### 0.1 Organizing Data Into Folder\n", 109 | " \n", 110 | "\n", 111 | "---\n", 112 | "**images**\n", 113 | "> contains training Images (Input)\n", 114 | "\n", 115 | "**val_images** \n", 116 | "> contains validation Images (Input)\n", 117 | "\n", 118 | "**test_images**\n", 119 | "> contains Test-set Images (Input)\n", 120 | "\n", 121 | "**train**\n", 122 | "> contains Ground Truth Saliency Map for training Images in Folder \"images\" (Output)\n", 123 | "\n", 124 | "**val**\n", 125 | "> contains Ground Truth Saliency Map for validation Images in Folder \"val_images\" (Output)" 126 | ] 127 | }, 128 | { 129 | "metadata": { 130 | "id": "Bcsv4JS91FOA", 131 | "colab_type": "code", 132 | "colab": {} 133 | }, 134 | "cell_type": "code", 135 | "source": [ 136 | "# moving testing data to another dir\n", 137 | "import os\n", 138 | "import shutil\n", 139 | "\n", 140 | "images_files = os.listdir('images')\n", 141 | "print (\"Total Number of Images: {}\".format(len(images_files)))\n", 142 | "\n", 143 | "!mkdir test_images\n", 144 | "!mkdir val_images\n", 145 | "\n", 146 | "cnt = 0\n", 147 | "\n", 148 | "for f in images_files:\n", 149 | " if 'test' in f:\n", 150 | " shutil.move('images/'+f,'test_images/')\n", 151 | " elif 'val' in f:\n", 152 | " shutil.move('images/'+f,'val_images/')\n", 153 | " \n", 154 | "\n", 155 | "! ls test_images | head -5\n", 156 | "! ls val_images | head -5" 157 | ], 158 | "execution_count": 0, 159 | "outputs": [] 160 | }, 161 | { 162 | "metadata": { 163 | "id": "NYM1hbnn9K0E", 164 | "colab_type": "code", 165 | "colab": {} 166 | }, 167 | "cell_type": "code", 168 | "source": [ 169 | "print (\"Total Train Images: {}\".format(len(os.listdir('images/'))))\n", 170 | "print (\"Total Valid Images: {}\".format(len(os.listdir('val_images/'))))\n", 171 | "print (\"Total Test Images: {}\".format(len(os.listdir('test_images/'))))" 172 | ], 173 | "execution_count": 0, 174 | "outputs": [] 175 | }, 176 | { 177 | "metadata": { 178 | "id": "W08B04x3or2k", 179 | "colab_type": "text" 180 | }, 181 | "cell_type": "markdown", 182 | "source": [ 183 | "## 1. Pre-processing Function and Generator\n" 184 | ] 185 | }, 186 | { 187 | "metadata": { 188 | "id": "hF7_WYWRHQT-", 189 | "colab_type": "text" 190 | }, 191 | "cell_type": "markdown", 192 | "source": [ 193 | "### 1.0 Pre-processing Function\n", 194 | "\n", 195 | "**Pre-Process Images**: Converts Input Images to 4:3 ration and use padding function for padding zeros. and it also pre-process for VGG-16 Architure substracting Mean from all channels.\n", 196 | "\n", 197 | "**Pre-Process Maps**: Converts Output Images (Saliency Maps) to 4:3 ration and use padding function for padding zeros. and it also convert gray scale range of 0-255 to 0-1.\n", 198 | "\n", 199 | "Note: pre-process, pre-process maps and padding are taken from reference code." 200 | ] 201 | }, 202 | { 203 | "metadata": { 204 | "id": "JIxmTdqXn6fZ", 205 | "colab_type": "code", 206 | "colab": {} 207 | }, 208 | "cell_type": "code", 209 | "source": [ 210 | "import cv2\n", 211 | "import numpy as np \n", 212 | "\n", 213 | "def padding(img, shape_r=480, shape_c=640, channels=3):\n", 214 | " img_padded = np.zeros((shape_r, shape_c, channels), dtype=np.uint8)\n", 215 | " if channels == 1:\n", 216 | " img_padded = np.zeros((shape_r, shape_c), dtype=np.uint8)\n", 217 | "\n", 218 | " original_shape = img.shape\n", 219 | " rows_rate = original_shape[0]/shape_r\n", 220 | " cols_rate = original_shape[1]/shape_c\n", 221 | "\n", 222 | " if rows_rate > cols_rate:\n", 223 | " new_cols = (original_shape[1] * shape_r) // original_shape[0]\n", 224 | " img = cv2.resize(img, (new_cols, shape_r))\n", 225 | " if new_cols > shape_c:\n", 226 | " new_cols = shape_c\n", 227 | " img_padded[:, ((img_padded.shape[1] - new_cols) // 2):((img_padded.shape[1] - new_cols) // 2 + new_cols)] = img\n", 228 | " else:\n", 229 | " new_rows = (original_shape[0] * shape_c) // original_shape[1]\n", 230 | " img = cv2.resize(img, (shape_c, new_rows))\n", 231 | " if new_rows > shape_r:\n", 232 | " new_rows = shape_r\n", 233 | " img_padded[((img_padded.shape[0] - new_rows) // 2):((img_padded.shape[0] - new_rows) // 2 + new_rows), :] = img\n", 234 | "\n", 235 | " return img_padded\n", 236 | "\n", 237 | "\n", 238 | "def preprocess_images(paths, shape_r, shape_c):\n", 239 | " ims = np.zeros((len(paths), shape_r, shape_c, 3))\n", 240 | "\n", 241 | " for i, path in enumerate(paths):\n", 242 | " original_image = cv2.imread(path)\n", 243 | " padded_image = padding(original_image, shape_r, shape_c, 3)\n", 244 | " ims[i] = padded_image.astype('float')\n", 245 | " \n", 246 | "# cv2 : BGR\n", 247 | "# PIL : RGB\n", 248 | " ims = ims[...,::-1]\n", 249 | " ims /= 255.0\n", 250 | " ims = np.rollaxis(ims, 3, 1) \n", 251 | " return ims\n", 252 | "\n", 253 | "\n", 254 | "def preprocess_maps(paths, shape_r, shape_c):\n", 255 | " ims = np.zeros((len(paths), 1, shape_r, shape_c))\n", 256 | "\n", 257 | " for i, path in enumerate(paths):\n", 258 | " original_map = cv2.imread(path, 0)\n", 259 | " padded_map = padding(original_map, shape_r, shape_c, 1)\n", 260 | " ims[i, 0] = padded_map.astype(np.float32)\n", 261 | " ims[i, 0] /= 255.0\n", 262 | " \n", 263 | "\n", 264 | " return ims" 265 | ], 266 | "execution_count": 0, 267 | "outputs": [] 268 | }, 269 | { 270 | "metadata": { 271 | "id": "aHUybGNzHNW5", 272 | "colab_type": "text" 273 | }, 274 | "cell_type": "markdown", 275 | "source": [ 276 | "### 1.1 Generator\n", 277 | "\n", 278 | "**generator**: It is used to supply images during training/testing with specified batch sizes. Function is modified from reference code. Shuffle and breaking condition of loop is added." 279 | ] 280 | }, 281 | { 282 | "metadata": { 283 | "id": "3Td9bdophNQs", 284 | "colab_type": "code", 285 | "colab": {} 286 | }, 287 | "cell_type": "code", 288 | "source": [ 289 | "import os \n", 290 | "from sklearn.utils import shuffle\n", 291 | "\n", 292 | "imgs_train_path = 'images/'\n", 293 | "maps_train_path = 'train/'\n", 294 | "\n", 295 | "imgs_val_path = 'val_images/'\n", 296 | "maps_val_path = 'val/'\n", 297 | "\n", 298 | "\n", 299 | "\n", 300 | "def generator(b_s, phase_gen='train'):\n", 301 | " if phase_gen == 'train':\n", 302 | " images = [imgs_train_path + f for f in os.listdir(imgs_train_path) if f.endswith('.jpg')]\n", 303 | " maps = [maps_train_path + f for f in os.listdir(maps_train_path) if f.endswith('.png')]\n", 304 | " elif phase_gen == 'val':\n", 305 | " images = [imgs_val_path + f for f in os.listdir(imgs_val_path) if f.endswith('.jpg')]\n", 306 | " maps = [maps_val_path + f for f in os.listdir(maps_val_path) if f.endswith('.png')]\n", 307 | " else:\n", 308 | " raise NotImplementedError\n", 309 | "\n", 310 | " images.sort()\n", 311 | " maps.sort()\n", 312 | " \n", 313 | " images , maps = shuffle(images,maps)\n", 314 | " \n", 315 | " counter = 0\n", 316 | " \n", 317 | " while True:\n", 318 | " yield preprocess_images(images[counter:counter + b_s], shape_r, shape_c), preprocess_maps(maps[counter:counter + b_s], shape_r_gt, shape_c_gt)\n", 319 | " if counter + b_s >= len(images):\n", 320 | " break\n", 321 | " counter = counter + b_s" 322 | ], 323 | "execution_count": 0, 324 | "outputs": [] 325 | }, 326 | { 327 | "metadata": { 328 | "id": "cSC0rytdo_kg", 329 | "colab_type": "text" 330 | }, 331 | "cell_type": "markdown", 332 | "source": [ 333 | "## 2. Defining Model and Loss Function" 334 | ] 335 | }, 336 | { 337 | "metadata": { 338 | "id": "cV3BMhfKLkAQ", 339 | "colab_type": "text" 340 | }, 341 | "cell_type": "markdown", 342 | "source": [ 343 | "### 2.1 Installing PyTorch" 344 | ] 345 | }, 346 | { 347 | "metadata": { 348 | "id": "v1-vcw1so-m6", 349 | "colab_type": "code", 350 | "colab": {} 351 | }, 352 | "cell_type": "code", 353 | "source": [ 354 | "# installing pytorch and pytorch vision\n", 355 | "!pip3 install torchvision" 356 | ], 357 | "execution_count": 0, 358 | "outputs": [] 359 | }, 360 | { 361 | "metadata": { 362 | "id": "GojPzAz3Lnxo", 363 | "colab_type": "text" 364 | }, 365 | "cell_type": "markdown", 366 | "source": [ 367 | "### 2.2 Defining Model\n", 368 | "\n", 369 | "More Detail of Model in Paper : https://arxiv.org/abs/1609.01064\n", 370 | "\n", 371 | "![Model](https://raw.githubusercontent.com/marcellacornia/mlnet/master/figs/mlnet.jpg)" 372 | ] 373 | }, 374 | { 375 | "metadata": { 376 | "id": "jrzCqMe3pyFM", 377 | "colab_type": "code", 378 | "colab": {} 379 | }, 380 | "cell_type": "code", 381 | "source": [ 382 | "import torch\n", 383 | "import torch.nn as nn\n", 384 | "import torchvision.models as models\n", 385 | "\n", 386 | "\n", 387 | "class MLNet(nn.Module):\n", 388 | " \n", 389 | " def __init__(self,prior_size):\n", 390 | " super(MLNet, self).__init__()\n", 391 | " # loading pre-trained vgg16 model and \n", 392 | " # removing last max pooling layer\n", 393 | " features = list(models.vgg16(pretrained = True).features)[:-1]\n", 394 | " \n", 395 | " # making same spatial size\n", 396 | " # by calculation :) \n", 397 | " # in pytorch there was problem outputing same size in maxpool2d\n", 398 | " features[23].stride = 1\n", 399 | " features[23].kernel_size = 5\n", 400 | " features[23].padding = 2\n", 401 | " \n", 402 | " self.features = nn.ModuleList(features).eval() \n", 403 | " # adding dropout layer\n", 404 | " self.fddropout = nn.Dropout2d(p=0.5)\n", 405 | " # adding convolution layer to down number of filters 1280 ==> 64\n", 406 | " self.int_conv = nn.Conv2d(1280,64,kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n", 407 | " self.pre_final_conv = nn.Conv2d(64,1,kernel_size=(1, 1), stride=(1, 1) ,padding=(0, 0))\n", 408 | " # prior initialized to ones\n", 409 | " self.prior = nn.Parameter(torch.ones((1,1,prior_size[0],prior_size[1]), requires_grad=True))\n", 410 | " \n", 411 | " # bilinear upsampling layer\n", 412 | " self.bilinearup = torch.nn.UpsamplingBilinear2d(scale_factor=10)\n", 413 | " \n", 414 | " def forward(self, x):\n", 415 | " \n", 416 | " results = []\n", 417 | " for ii,model in enumerate(self.features):\n", 418 | " x = model(x)\n", 419 | " if ii in {16,23,29}:\n", 420 | " results.append(x)\n", 421 | " \n", 422 | " # concat to get 1280 = 512 + 512 + 256\n", 423 | " x = torch.cat((results[0],results[1],results[2]),1) \n", 424 | " \n", 425 | " # adding dropout layer with dropout set to 0.5 (default)\n", 426 | " x = self.fddropout(x)\n", 427 | " \n", 428 | " # 64 filters convolution layer\n", 429 | " x = self.int_conv(x)\n", 430 | " # 1*1 convolution layer\n", 431 | " x = self.pre_final_conv(x)\n", 432 | " \n", 433 | " upscaled_prior = self.bilinearup(self.prior)\n", 434 | " # print (\"upscaled_prior shape: {}\".format(upscaled_prior.shape))\n", 435 | "\n", 436 | " # dot product with prior\n", 437 | " x = x * upscaled_prior\n", 438 | " x = torch.nn.functional.relu(x,inplace=True)\n", 439 | " return x\n" 440 | ], 441 | "execution_count": 0, 442 | "outputs": [] 443 | }, 444 | { 445 | "metadata": { 446 | "id": "NxuCG8B6MpEd", 447 | "colab_type": "text" 448 | }, 449 | "cell_type": "markdown", 450 | "source": [ 451 | "### 2.3 Defining Custom Loss function derived From MSE Loss" 452 | ] 453 | }, 454 | { 455 | "metadata": { 456 | "id": "LhBxYsvb0BXC", 457 | "colab_type": "code", 458 | "colab": {} 459 | }, 460 | "cell_type": "code", 461 | "source": [ 462 | "# Modified MSE Loss Function\n", 463 | "class ModMSELoss(torch.nn.Module):\n", 464 | " def __init__(self,shape_r_gt,shape_c_gt):\n", 465 | " super(ModMSELoss, self).__init__()\n", 466 | " self.shape_r_gt = shape_r_gt\n", 467 | " self.shape_c_gt = shape_c_gt\n", 468 | " \n", 469 | " def forward(self, output , label , prior):\n", 470 | " prior_size = prior.shape\n", 471 | " output_max = torch.max(torch.max(output,2)[0],2)[0].unsqueeze(2).unsqueeze(2).expand(output.shape[0],output.shape[1],self.shape_r_gt,self.shape_c_gt)\n", 472 | " reg = ( 1.0/(prior_size[0]*prior_size[1]) ) * ( 1 - prior)**2\n", 473 | " loss = torch.mean( ((output / output_max) - label)**2 / (1 - label + 0.1) ) + torch.sum(reg)\n", 474 | " return loss" 475 | ], 476 | "execution_count": 0, 477 | "outputs": [] 478 | }, 479 | { 480 | "metadata": { 481 | "id": "L67bssepBflY", 482 | "colab_type": "text" 483 | }, 484 | "cell_type": "markdown", 485 | "source": [ 486 | "## 3. Training Model" 487 | ] 488 | }, 489 | { 490 | "metadata": { 491 | "id": "1lsVWtq7Rdj3", 492 | "colab_type": "text" 493 | }, 494 | "cell_type": "markdown", 495 | "source": [ 496 | "#### Memory Warning: \n", 497 | "\n", 498 | "This model require huge amount of memory. Paper doesn't freeze any layer and uses configratution of Image size = (480,640) , batch_size = 10.\n", 499 | "Training with default configration result into cuda out of memory (12 GB of GPU RAM).\n", 500 | "\n", 501 | "To tackle this problem, I have tried to train model on two variant.\n", 502 | "> 1.\n", 503 | "\n", 504 | " shape_r = 240 ==> shape_r_gt = 30\n", 505 | " shape_c = 320 ==> shape_c_gt = 40\n", 506 | " batch_size = 16\n", 507 | " last_freeze_layer = 23\n", 508 | "> 2.\n", 509 | "\n", 510 | " shape_r = 480 ==> shape_r_gt = 60\n", 511 | " shape_c = 640 ==> shape_c_gt = 80\n", 512 | " batch_size = 16\n", 513 | " last_freeze_layer = 28\n", 514 | " \n", 515 | " \n", 516 | "**Note : Second Approch didn't perform well.**\n", 517 | "\n", 518 | "#### Prior Size:\n", 519 | "\n", 520 | "prior size (w',h') where w' << w and h' << h as mentioned in paper where w,h are width and height of output.\n", 521 | "\n", 522 | "**w' = w / 10**\n", 523 | "\n", 524 | "**h' = h / 10**\n" 525 | ] 526 | }, 527 | { 528 | "metadata": { 529 | "id": "fsnFIGwPRJ4X", 530 | "colab_type": "code", 531 | "colab": {} 532 | }, 533 | "cell_type": "code", 534 | "source": [ 535 | "# Input Images size\n", 536 | "shape_r = 240\n", 537 | "shape_c = 320\n", 538 | "# shape_r = 480\n", 539 | "# shape_c = 640\n", 540 | "\n", 541 | "# Output Image size (generally divided by 8 from Input size)\n", 542 | "shape_r_gt = 30\n", 543 | "shape_c_gt = 40\n", 544 | "# shape_r_gt = 60\n", 545 | "# shape_c_gt = 80\n", 546 | "\n", 547 | "\n", 548 | "last_freeze_layer = 23\n", 549 | "# last_freeze_layer = 28" 550 | ], 551 | "execution_count": 0, 552 | "outputs": [] 553 | }, 554 | { 555 | "metadata": { 556 | "id": "7qbZC28MdPK1", 557 | "colab_type": "code", 558 | "colab": {} 559 | }, 560 | "cell_type": "code", 561 | "source": [ 562 | "prior_size = ( int(shape_r_gt / 10) , int(shape_c_gt / 10) )\n", 563 | "\n", 564 | "model = MLNet(prior_size).cuda()\n", 565 | "\n", 566 | "\n", 567 | "# freezing Layer\n", 568 | "for i,param in enumerate(model.parameters()):\n", 569 | " if i < last_freeze_layer:\n", 570 | " param.requires_grad = False\n", 571 | "\n", 572 | " \n", 573 | "criterion = ModMSELoss(shape_r_gt,shape_c_gt).cuda()\n", 574 | "\n", 575 | "# optimizer = torch.optim.SGD(model.parameters(), lr=1e-3,weight_decay=0.0005,momentum=0.9,nesterov=True)\n", 576 | "optimizer = torch.optim.Adam(model.parameters(), lr=1e-3,weight_decay=1e-4)" 577 | ], 578 | "execution_count": 0, 579 | "outputs": [] 580 | }, 581 | { 582 | "metadata": { 583 | "id": "r4wrJnCdWsQJ", 584 | "colab_type": "code", 585 | "colab": {} 586 | }, 587 | "cell_type": "code", 588 | "source": [ 589 | "\n", 590 | "# mean = [0.485, 0.456, 0.406]\n", 591 | "# std = [0.229, 0.224, 0.225]\n", 592 | "import time\n", 593 | "import torchvision.transforms as transforms\n", 594 | "normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],\n", 595 | " std=[0.229, 0.224, 0.225])\n", 596 | "\n", 597 | "loss_history = []\n", 598 | "nb_epochs = 10\n", 599 | "batch_size = 16\n", 600 | "\n", 601 | "for epoch in range(nb_epochs):\n", 602 | " t1 = time.time()\n", 603 | " image_trained = 0\n", 604 | " \n", 605 | " for i,gt_map in generator(batch_size):\n", 606 | " \n", 607 | " optimizer.zero_grad()\n", 608 | "# print (i.shape)\n", 609 | "\n", 610 | " i,gt_map = torch.tensor(i.copy(),dtype=torch.float),torch.tensor(gt_map,dtype=torch.float)\n", 611 | " for idx,x in enumerate(i):\n", 612 | " i[idx] = normalize(x) \n", 613 | " i,gt_map = i.cuda(),gt_map.cuda()\n", 614 | " \n", 615 | " image_trained += batch_size\n", 616 | " \n", 617 | " out = model.forward(i)\n", 618 | " loss = criterion(out,gt_map,model.prior.clone())\n", 619 | " loss.backward()\n", 620 | " optimizer.step()\n", 621 | " \n", 622 | " if image_trained % (batch_size*20) == 0:\n", 623 | " print (\"Epcohs:{} Images:{} Loss:{}\".format(epoch,image_trained,loss.item()) )\n", 624 | " t2 = time.time()\n", 625 | " time_per_epoch = (t2 - t1) / 60.0\n", 626 | " print ('Time taken for epoch-{} : {}m'.format(epoch,time_per_epoch))" 627 | ], 628 | "execution_count": 0, 629 | "outputs": [] 630 | }, 631 | { 632 | "metadata": { 633 | "id": "QgeWfu5yBnBU", 634 | "colab_type": "text" 635 | }, 636 | "cell_type": "markdown", 637 | "source": [ 638 | "## 4. Visualizing Model Output and Saving Model Weights" 639 | ] 640 | }, 641 | { 642 | "metadata": { 643 | "id": "jRB-R-s1Pi1F", 644 | "colab_type": "text" 645 | }, 646 | "cell_type": "markdown", 647 | "source": [ 648 | "### 4.0 Visualizing Model output on Validation Images\n", 649 | "Note :Each Time running code will output different Image visualization " 650 | ] 651 | }, 652 | { 653 | "metadata": { 654 | "id": "sMhGnQ8p6P7n", 655 | "colab_type": "code", 656 | "colab": {} 657 | }, 658 | "cell_type": "code", 659 | "source": [ 660 | "# loading saved model to visualize\n", 661 | "# !gdown https://drive.google.com/uc?id=1vhA5Uc547nZL0rI9IsHWEbhx2j-oSnrn&export=download\n", 662 | "# PATH = \"2018-10-04 09_20_57.364231_5_epochs_v1.model\"\n", 663 | "# model.load_state_dict(torch.load(PATH))" 664 | ], 665 | "execution_count": 0, 666 | "outputs": [] 667 | }, 668 | { 669 | "metadata": { 670 | "id": "iPi75x-zCcZ8", 671 | "colab_type": "code", 672 | "colab": {} 673 | }, 674 | "cell_type": "code", 675 | "source": [ 676 | "import matplotlib.pyplot as plt\n", 677 | "\n", 678 | "# how many pic you want to visualiz at randomly\n", 679 | "no_visual = 15\n", 680 | "\n", 681 | "\n", 682 | "visual_cnt = 0\n", 683 | "for i,gt_map in generator(1,phase_gen='val'):\n", 684 | " print (\"Original\")\n", 685 | " org_image = i[0].copy()\n", 686 | " \n", 687 | " org_image = np.rollaxis(org_image, 0, 3) \n", 688 | " print (org_image.shape)\n", 689 | " i = torch.tensor(i.copy(),dtype=torch.float)\n", 690 | " for idx,x in enumerate(i):\n", 691 | " i[idx] = normalize(x)\n", 692 | " i = i.cuda()\n", 693 | " out = model.forward(i)\n", 694 | " # adding term which were subtracted at pre processing\n", 695 | " plt.imshow(org_image)\n", 696 | " plt.show()\n", 697 | " print (\"predicted\")\n", 698 | " plt.imshow(out[0].squeeze(0).data.cpu().numpy(),cmap='gray')\n", 699 | " plt.show()\n", 700 | " print (\"Original\")\n", 701 | " plt.imshow(gt_map[0][0],cmap='gray')\n", 702 | " plt.show()\n", 703 | " visual_cnt += 1\n", 704 | " if visual_cnt > no_visual:\n", 705 | " break" 706 | ], 707 | "execution_count": 0, 708 | "outputs": [] 709 | }, 710 | { 711 | "metadata": { 712 | "id": "IFlU0IOnQkbB", 713 | "colab_type": "text" 714 | }, 715 | "cell_type": "markdown", 716 | "source": [ 717 | "### 4.1 Saving Model\n", 718 | "\n", 719 | "Note: Weight file can be downloaded using File section at left." 720 | ] 721 | }, 722 | { 723 | "metadata": { 724 | "id": "5rbDIbZdGf0o", 725 | "colab_type": "code", 726 | "colab": {} 727 | }, 728 | "cell_type": "code", 729 | "source": [ 730 | "# creatin Dir for saving model\n", 731 | "!mkdir saved_models -p\n", 732 | "\n", 733 | "\n", 734 | "import time\n", 735 | "import datetime\n", 736 | "\n", 737 | "# saving model weight\n", 738 | "additional_info = '25_epochs_v3'\n", 739 | "full_path = 'saved_models/' + str(datetime.datetime.now()) + '_' + additional_info + '.model'\n", 740 | "torch.save(model.state_dict(), full_path)\n", 741 | "\n", 742 | "# for loading Model\n", 743 | "# model.load_state_dict(torch.load(PATH))\n" 744 | ], 745 | "execution_count": 0, 746 | "outputs": [] 747 | }, 748 | { 749 | "metadata": { 750 | "id": "_lwx1RGVjsrJ", 751 | "colab_type": "code", 752 | "colab": {} 753 | }, 754 | "cell_type": "code", 755 | "source": [ 756 | "from google.colab import files\n", 757 | "files.download(full_path)" 758 | ], 759 | "execution_count": 0, 760 | "outputs": [] 761 | }, 762 | { 763 | "metadata": { 764 | "id": "kzp1rQ9tBxsd", 765 | "colab_type": "text" 766 | }, 767 | "cell_type": "markdown", 768 | "source": [ 769 | "## 5. Creating Submission.zip for submitting to CodaLab" 770 | ] 771 | }, 772 | { 773 | "metadata": { 774 | "id": "CspRk5Pkok9n", 775 | "colab_type": "code", 776 | "colab": {} 777 | }, 778 | "cell_type": "code", 779 | "source": [ 780 | "# creating dir for storing prediction of test images\n", 781 | "! mkdir test_maps" 782 | ], 783 | "execution_count": 0, 784 | "outputs": [] 785 | }, 786 | { 787 | "metadata": { 788 | "id": "zzpGsdynmWJj", 789 | "colab_type": "code", 790 | "colab": {} 791 | }, 792 | "cell_type": "code", 793 | "source": [ 794 | "test_file = [ f for f in os.listdir('test_images/') if f.endswith('.jpg') ]\n", 795 | "\n", 796 | "for i in test_file:\n", 797 | " img = preprocess_images(['test_images/'+i],shape_r,shape_c)\n", 798 | " img = torch.tensor(img.copy(),dtype=torch.float)\n", 799 | " for idx,x in enumerate(img):\n", 800 | " img[idx] = normalize(x)\n", 801 | " img = img.cuda()\n", 802 | " pred = model.forward(img)\n", 803 | " cv2.imwrite('test_maps/' + i[:-3] + 'png',pred[0].squeeze(0).data.cpu().numpy())" 804 | ], 805 | "execution_count": 0, 806 | "outputs": [] 807 | }, 808 | { 809 | "metadata": { 810 | "id": "Yax5DZF2udC6", 811 | "colab_type": "code", 812 | "colab": {} 813 | }, 814 | "cell_type": "code", 815 | "source": [ 816 | "# generatung Submission.zip \n", 817 | "! cd test_maps ; zip ../submission.zip *.png > zipping.log" 818 | ], 819 | "execution_count": 0, 820 | "outputs": [] 821 | } 822 | ] 823 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MLNet-Pytorch 2 | 3 | Implementation of A Deep Multi-Level Network for Saliency Prediction in Pytorch 4 | 5 | ### Description : 6 | As Human, We only focus on certain part of Image which is called salient region. This Project predict Saliency map of given Image which is useful in many areas like Robotics, Image-aware editing, caption generation, fast-response systems. 7 | 8 | ##### For Mobile Users: https://nbviewer.jupyter.org/github/immortal3/MLNet-Pytorch/blob/master/MLNet_Pytorch.ipynb 9 | 10 | Notebook is directly runnable to Google colab. 11 | 12 | 13 | ##### Note : Due to Memory Limit, some layers were frozen and output saliency maps size was reduced by half during Training. 14 | 15 | ### Result : 16 | 17 | 18 | | |AUC|CC|KL|SAUC|IG|NSS|SIM| 19 | |----|---|--|--|----|--|---|---| 20 | |Ours|0.771|0.553|1.142|0.619|-0.380|1.014|0.573| 21 | 22 | | | | | | | 23 | |---|---|---|---|---| 24 | | Original Image | ![1](https://github.com/immortal3/MLNet-Pytorch/blob/master/readme-content/1.png) | ![2](https://github.com/immortal3/MLNet-Pytorch/blob/master/readme-content/2.png)|![3](https://github.com/immortal3/MLNet-Pytorch/blob/master/readme-content/3.png) |![4](https://github.com/immortal3/MLNet-Pytorch/blob/master/readme-content/4.png) | 25 | | Predicted Saliency Map| ![1](https://github.com/immortal3/MLNet-Pytorch/blob/master/readme-content/1_pred.png)| ![2](https://github.com/immortal3/MLNet-Pytorch/blob/master/readme-content/2_pred.png) |![3](https://github.com/immortal3/MLNet-Pytorch/blob/master/readme-content/3_pred.png) | ![4](https://github.com/immortal3/MLNet-Pytorch/blob/master/readme-content/4_pred.png) | 26 | | Ground Truth| ![3](https://github.com/immortal3/MLNet-Pytorch/blob/master/readme-content/1_gt.png)| ![3](https://github.com/immortal3/MLNet-Pytorch/blob/master/readme-content/2_gt.png) |![3](https://github.com/immortal3/MLNet-Pytorch/blob/master/readme-content/3_gt.png) |![3](https://github.com/immortal3/MLNet-Pytorch/blob/master/readme-content/4_gt.png) | 27 | 28 | 29 | #### References: 30 | 31 | #### [1] Cornia, Marcella, et al. "A deep multi-level network for saliency prediction." Pattern Recognition (ICPR), 2016 23rd International Conference on. IEEE, 2016. 32 | #### [2] Jiang, Ming, et al. "Salicon: Saliency in context." Proceedings of the IEEE conference on computer vision and pattern recognition. 2015. 33 | -------------------------------------------------------------------------------- /readme-content/1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/immortal3/MLNet-Pytorch/62ff6eab9a32fcd4bc2f5634346057431e0bd652/readme-content/1.png -------------------------------------------------------------------------------- /readme-content/1_gt.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/immortal3/MLNet-Pytorch/62ff6eab9a32fcd4bc2f5634346057431e0bd652/readme-content/1_gt.png -------------------------------------------------------------------------------- /readme-content/1_pred.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/immortal3/MLNet-Pytorch/62ff6eab9a32fcd4bc2f5634346057431e0bd652/readme-content/1_pred.png -------------------------------------------------------------------------------- /readme-content/2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/immortal3/MLNet-Pytorch/62ff6eab9a32fcd4bc2f5634346057431e0bd652/readme-content/2.png -------------------------------------------------------------------------------- /readme-content/2_gt.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/immortal3/MLNet-Pytorch/62ff6eab9a32fcd4bc2f5634346057431e0bd652/readme-content/2_gt.png -------------------------------------------------------------------------------- /readme-content/2_pred.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/immortal3/MLNet-Pytorch/62ff6eab9a32fcd4bc2f5634346057431e0bd652/readme-content/2_pred.png -------------------------------------------------------------------------------- /readme-content/3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/immortal3/MLNet-Pytorch/62ff6eab9a32fcd4bc2f5634346057431e0bd652/readme-content/3.png -------------------------------------------------------------------------------- /readme-content/3_gt.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/immortal3/MLNet-Pytorch/62ff6eab9a32fcd4bc2f5634346057431e0bd652/readme-content/3_gt.png -------------------------------------------------------------------------------- /readme-content/3_pred.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/immortal3/MLNet-Pytorch/62ff6eab9a32fcd4bc2f5634346057431e0bd652/readme-content/3_pred.png -------------------------------------------------------------------------------- /readme-content/4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/immortal3/MLNet-Pytorch/62ff6eab9a32fcd4bc2f5634346057431e0bd652/readme-content/4.png -------------------------------------------------------------------------------- /readme-content/4_gt.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/immortal3/MLNet-Pytorch/62ff6eab9a32fcd4bc2f5634346057431e0bd652/readme-content/4_gt.png -------------------------------------------------------------------------------- /readme-content/4_pred.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/immortal3/MLNet-Pytorch/62ff6eab9a32fcd4bc2f5634346057431e0bd652/readme-content/4_pred.png --------------------------------------------------------------------------------