├── LICENSE
├── README.md
├── get_predictions.ipynb
├── results
├── 1.png
├── 2.png
├── 3.png
└── 4.png
├── test_anchors.ipynb
├── train.ipynb
└── visualize.ipynb
/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 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # ESRI Object Detection Challenge 2019
2 | I used [keras-retinanet](https://github.com/fizyr/keras-retinanet) to fine tune a pretrained RetinaNet model on this dataset. It achieves an AP of 83% on test set with IoU Threshold of 0.3. [Link to Dataset](https://www.kaggle.com/kbhartiya83/swimming-pool-and-car-detection)
3 |
4 | ## Requirements
5 | - Everything required by [keras-retinanet](https://github.com/fizyr/keras-retinanet)
6 | - TQDM
7 | - imgaug
8 | - sklearn
9 |
10 | ## Results
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/get_predictions.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Generate Predictions from Trained Model"
8 | ]
9 | },
10 | {
11 | "cell_type": "code",
12 | "execution_count": null,
13 | "metadata": {},
14 | "outputs": [],
15 | "source": [
16 | "import os\n",
17 | "from os import listdir, walk\n",
18 | "from os.path import join\n",
19 | "from keras_retinanet.bin.train import create_models\n",
20 | "from keras_retinanet.models import backbone,convert_model\n",
21 | "from keras_retinanet.utils.config import read_config_file,parse_anchor_parameters\n",
22 | "import numpy as np\n",
23 | "import keras\n",
24 | "import math\n",
25 | "import tensorflow as tf\n",
26 | "tf.set_random_seed(31)\n",
27 | "np.random.seed(17)"
28 | ]
29 | },
30 | {
31 | "cell_type": "code",
32 | "execution_count": null,
33 | "metadata": {},
34 | "outputs": [],
35 | "source": [
36 | "model, training_model, prediction_model = create_models(\n",
37 | " backbone_retinanet=backbone('resnet50').retinanet,\n",
38 | " num_classes=2,\n",
39 | " weights=None,\n",
40 | " multi_gpu=False,\n",
41 | " freeze_backbone=False,\n",
42 | " lr=1e-3,\n",
43 | " config=read_config_file('config.ini')\n",
44 | " )"
45 | ]
46 | },
47 | {
48 | "cell_type": "markdown",
49 | "metadata": {},
50 | "source": [
51 | "# Load and Convert Model\n",
52 | "\n",
53 | "Training model needs to be converted to inference model"
54 | ]
55 | },
56 | {
57 | "cell_type": "code",
58 | "execution_count": null,
59 | "metadata": {},
60 | "outputs": [],
61 | "source": [
62 | "training_model.load_weights('saved/resnet50_csv_70.h5')"
63 | ]
64 | },
65 | {
66 | "cell_type": "code",
67 | "execution_count": null,
68 | "metadata": {},
69 | "outputs": [],
70 | "source": [
71 | "infer_model = convert_model(training_model,anchor_params=parse_anchor_parameters(read_config_file('config.ini')))"
72 | ]
73 | },
74 | {
75 | "cell_type": "markdown",
76 | "metadata": {},
77 | "source": [
78 | "# Create Generator to load images"
79 | ]
80 | },
81 | {
82 | "cell_type": "code",
83 | "execution_count": null,
84 | "metadata": {},
85 | "outputs": [],
86 | "source": [
87 | "from keras_retinanet.utils.image import read_image_bgr, preprocess_image, resize_image\n",
88 | "from tqdm import tqdm\n",
89 | "\n",
90 | "def test_gen(image_ids, bs = 32, size=672,test = True):\n",
91 | " imgs = []\n",
92 | " scale = None\n",
93 | " idx = 0\n",
94 | " if test:\n",
95 | " path = 'test_data_images/images/'\n",
96 | " else:\n",
97 | " path = 'training_data/images/'\n",
98 | " \n",
99 | " while idx < len(image_ids):\n",
100 | " if len(imgs) < bs:\n",
101 | " imgs.append(resize_image(preprocess_image(read_image_bgr(path + image_ids[idx] + '.jpg')),min_side=size,max_side=size)[0]) \n",
102 | " if scale is None:\n",
103 | " scale = resize_image(preprocess_image(read_image_bgr(path + image_ids[idx] + '.jpg')),min_side=size,max_side=size)[1]\n",
104 | " idx += 1\n",
105 | " else:\n",
106 | " yield np.array(imgs),scale\n",
107 | " imgs = []\n",
108 | " \n",
109 | " \n",
110 | " if len(imgs) > 0:\n",
111 | " yield np.array(imgs),scale "
112 | ]
113 | },
114 | {
115 | "cell_type": "markdown",
116 | "metadata": {},
117 | "source": [
118 | "# Save Predictions"
119 | ]
120 | },
121 | {
122 | "cell_type": "code",
123 | "execution_count": null,
124 | "metadata": {},
125 | "outputs": [],
126 | "source": [
127 | "_,_,image_ids = next(walk('test_data_images/images'))\n",
128 | "image_ids = [i[:-4] for i in image_ids]\n",
129 | "image_ids = sorted(image_ids)\n",
130 | "\n",
131 | "os.system('mkdir predictions')\n",
132 | "\n",
133 | "iter_num = 0\n",
134 | "test_bs = 8\n",
135 | "\n",
136 | "\n",
137 | "for imgs,scale in tqdm(test_gen(image_ids,bs=test_bs),total=math.ceil(len(image_ids)/test_bs)):\n",
138 | " boxes, scores, labels = infer_model.predict_on_batch(imgs)\n",
139 | " boxes /= scale\n",
140 | " for img_num in range(len(imgs)):\n",
141 | " with open('predictions/' + image_ids[(iter_num*test_bs) + img_num] + '.txt', 'w') as f:\n",
142 | " for box, score, label in zip(boxes[img_num], scores[img_num], labels[img_num]):\n",
143 | " # scores are sorted so we can break\n",
144 | " if score < 0:\n",
145 | " break\n",
146 | " f.write(f'{label + 1} {score} {int((box[1]))} {int((box[0]))} {int((box[3]))} {int((box[2]))} \\n')\n",
147 | " iter_num += 1"
148 | ]
149 | },
150 | {
151 | "cell_type": "code",
152 | "execution_count": null,
153 | "metadata": {},
154 | "outputs": [],
155 | "source": [
156 | "os.system('zip -r predictions.zip predictions/')"
157 | ]
158 | },
159 | {
160 | "cell_type": "code",
161 | "execution_count": null,
162 | "metadata": {},
163 | "outputs": [],
164 | "source": []
165 | }
166 | ],
167 | "metadata": {
168 | "kernelspec": {
169 | "display_name": "Python 3",
170 | "language": "python",
171 | "name": "python3"
172 | },
173 | "language_info": {
174 | "codemirror_mode": {
175 | "name": "ipython",
176 | "version": 3
177 | },
178 | "file_extension": ".py",
179 | "mimetype": "text/x-python",
180 | "name": "python",
181 | "nbconvert_exporter": "python",
182 | "pygments_lexer": "ipython3",
183 | "version": "3.6.7"
184 | }
185 | },
186 | "nbformat": 4,
187 | "nbformat_minor": 2
188 | }
189 |
--------------------------------------------------------------------------------
/results/1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kunwar31/ESRI_Object_Detection/c78451d94ee1a5a2df344f7ef9849ad140a5b379/results/1.png
--------------------------------------------------------------------------------
/results/2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kunwar31/ESRI_Object_Detection/c78451d94ee1a5a2df344f7ef9849ad140a5b379/results/2.png
--------------------------------------------------------------------------------
/results/3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kunwar31/ESRI_Object_Detection/c78451d94ee1a5a2df344f7ef9849ad140a5b379/results/3.png
--------------------------------------------------------------------------------
/results/4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kunwar31/ESRI_Object_Detection/c78451d94ee1a5a2df344f7ef9849ad140a5b379/results/4.png
--------------------------------------------------------------------------------
/test_anchors.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Visualize Anchor Boxes\n",
8 | "\n",
9 | "!OpenCV must be installed to run this notebook!"
10 | ]
11 | },
12 | {
13 | "cell_type": "code",
14 | "execution_count": null,
15 | "metadata": {},
16 | "outputs": [],
17 | "source": [
18 | "from keras_retinanet.bin.train import create_generators\n",
19 | "from keras_retinanet.models import backbone\n",
20 | "from keras_retinanet.utils.config import read_config_file,parse_anchor_parameters\n",
21 | "from keras_retinanet.bin.debug import run"
22 | ]
23 | },
24 | {
25 | "cell_type": "code",
26 | "execution_count": null,
27 | "metadata": {},
28 | "outputs": [],
29 | "source": [
30 | "b = backbone('resnet50')\n",
31 | "\n",
32 | "class args:\n",
33 | " batch_size = 4\n",
34 | " config = read_config_file('config.ini')\n",
35 | " random_transform = True\n",
36 | " annotations = 'annotations.csv'\n",
37 | " val_annotations = 'val_annotations.csv'\n",
38 | " classes = 'classes.csv'\n",
39 | " image_min_side = 672\n",
40 | " image_max_side = 672\n",
41 | " dataset_type = 'csv'\n",
42 | " tensorboard_dir = ''\n",
43 | " evaluation = True\n",
44 | " snapshots = True\n",
45 | " snapshot_path = \"saved/\"\n",
46 | " backbone = 'resnet50'\n",
47 | " weighted_average = True\n",
48 | " resize=True\n",
49 | " anchors=True\n",
50 | " \n",
51 | "train_gen,valid_gen = create_generators(args,b.preprocess_image)"
52 | ]
53 | },
54 | {
55 | "cell_type": "code",
56 | "execution_count": null,
57 | "metadata": {},
58 | "outputs": [],
59 | "source": [
60 | "while run(valid_gen,args,parse_anchor_parameters(args.config)):\n",
61 | " pass"
62 | ]
63 | },
64 | {
65 | "cell_type": "code",
66 | "execution_count": null,
67 | "metadata": {},
68 | "outputs": [],
69 | "source": []
70 | }
71 | ],
72 | "metadata": {
73 | "kernelspec": {
74 | "display_name": "Python 3",
75 | "language": "python",
76 | "name": "python3"
77 | },
78 | "language_info": {
79 | "codemirror_mode": {
80 | "name": "ipython",
81 | "version": 3
82 | },
83 | "file_extension": ".py",
84 | "mimetype": "text/x-python",
85 | "name": "python",
86 | "nbconvert_exporter": "python",
87 | "pygments_lexer": "ipython3",
88 | "version": "3.6.7"
89 | }
90 | },
91 | "nbformat": 4,
92 | "nbformat_minor": 2
93 | }
94 |
--------------------------------------------------------------------------------
/train.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {
6 | "_uuid": "1fd9570466736b09c16d4ed020cb81aef494753d"
7 | },
8 | "source": [
9 | "# **ESRI DATA SCIENCE CHALLENGE 2019**\n",
10 | "\n",
11 | "\n",
12 | "In this challenge, we have been given 224x224 images containing cars and swimming pools labelled in PASCAL VOC Format. As we'll be using RetinaNet for this challenge, we'll make use of keras-retinanet package from github. \n",
13 | "* [Focal Loss for Dense Object Detection](https://arxiv.org/abs/1708.02002) - Research paper describing RetinaNet and Focal Loss which it uses\n",
14 | "* [keras-retinanet](https://github.com/fizyr/keras-retinanet) - Keras RetinaNet implimentation"
15 | ]
16 | },
17 | {
18 | "cell_type": "code",
19 | "execution_count": null,
20 | "metadata": {
21 | "_cell_guid": "b1076dfc-b9ad-4769-8c92-a6c4dae69d19",
22 | "_uuid": "8f2839f25d086af736a60e9eeb907d3b93b6e0e5"
23 | },
24 | "outputs": [],
25 | "source": [
26 | "!git clone https://github.com/fizyr/keras-retinanet"
27 | ]
28 | },
29 | {
30 | "cell_type": "code",
31 | "execution_count": null,
32 | "metadata": {
33 | "_cell_guid": "79c7e3d0-c299-4dcb-8224-4455121ee9b0",
34 | "_uuid": "d629ff2d2480ee46fbb7e2d37f6b5fab8052498a"
35 | },
36 | "outputs": [],
37 | "source": [
38 | "!pip3 install keras-retinanet/ --user"
39 | ]
40 | },
41 | {
42 | "cell_type": "code",
43 | "execution_count": null,
44 | "metadata": {
45 | "_uuid": "fb2593dea04ab0e20ef4ee521dd8cba7f3bd987b"
46 | },
47 | "outputs": [],
48 | "source": [
49 | "!rm keras-retinanet/ -R"
50 | ]
51 | },
52 | {
53 | "cell_type": "code",
54 | "execution_count": null,
55 | "metadata": {
56 | "_uuid": "907236db932c74a1170900b8e6d9cc60bd086206"
57 | },
58 | "outputs": [],
59 | "source": [
60 | "import xml.etree.ElementTree as ET\n",
61 | "import os\n",
62 | "import numpy as np\n",
63 | "import keras\n",
64 | "import math\n",
65 | "import tensorflow as tf\n",
66 | "import cv2\n",
67 | "from os import listdir, walk\n",
68 | "from os.path import join\n",
69 | "from keras_retinanet.bin.train import create_generators,create_models,create_callbacks\n",
70 | "from keras_retinanet.models import backbone,load_model,convert_model\n",
71 | "from keras_retinanet.utils.config import read_config_file,parse_anchor_parameters\n",
72 | "from keras_retinanet.utils.visualization import draw_boxes\n",
73 | "from sklearn.model_selection import train_test_split\n",
74 | "from imgaug import augmenters as iaa\n",
75 | "\n",
76 | "tf.set_random_seed(31) # SEEDS MAKE RESULTS MORE REPRODUCABLE\n",
77 | "np.random.seed(17)"
78 | ]
79 | },
80 | {
81 | "cell_type": "code",
82 | "execution_count": null,
83 | "metadata": {
84 | "_uuid": "faef2a3eac3226eb2e8211a9c81f89b9a6a811b3"
85 | },
86 | "outputs": [],
87 | "source": [
88 | "classes = ['1','2']"
89 | ]
90 | },
91 | {
92 | "cell_type": "markdown",
93 | "metadata": {
94 | "_uuid": "56a388a1b5fc53f9ffd6c207a87bae5b8ffbc543"
95 | },
96 | "source": [
97 | "# Load and Convert Annotations\n",
98 | "\n",
99 | "Here we load annotations given in PASCAL VOC Format and save them in CSV Format as required by keras-retinanet package"
100 | ]
101 | },
102 | {
103 | "cell_type": "code",
104 | "execution_count": null,
105 | "metadata": {
106 | "_uuid": "7673f02c16e5bb5e3734f23d2a533326b9fba562"
107 | },
108 | "outputs": [],
109 | "source": [
110 | "def convert_annotation(image_id,filename):\n",
111 | " in_file = open('training_data/labels/%s.xml'%(image_id))\n",
112 | " out_file = open(filename, 'a')\n",
113 | " tree=ET.parse(in_file)\n",
114 | " root = tree.getroot()\n",
115 | " \n",
116 | " if root.iter('object') is not None:\n",
117 | " for obj in root.iter('object'):\n",
118 | " cls = obj.find('name').text\n",
119 | " if cls not in classes:\n",
120 | " continue\n",
121 | " cls_id = classes.index(cls)\n",
122 | " \n",
123 | " xmlbox = obj.find('bndbox')\n",
124 | " x1 = math.ceil(float(xmlbox.find('xmin').text))\n",
125 | " y1 = math.ceil(float(xmlbox.find('ymin').text))\n",
126 | " x2 = math.ceil(float(xmlbox.find('xmax').text))\n",
127 | " y2 = math.ceil(float(xmlbox.find('ymax').text))\n",
128 | " if x1 == x2 or y1 == y2:\n",
129 | " continue\n",
130 | " \n",
131 | " out_file.write(f'training_data/images/{image_id}.jpg,{x1},{y1},{x2},{y2},{cls}\\n')\n",
132 | " else:\n",
133 | " out_file.write(f'training_data/images/{image_id}.jpg,,,,,\\n')"
134 | ]
135 | },
136 | {
137 | "cell_type": "markdown",
138 | "metadata": {
139 | "_uuid": "04461e1dd8304d4224c0ce6fe9a1da1040b8aa9d"
140 | },
141 | "source": [
142 | "# Training and Validation split\n",
143 | "\n",
144 | "Normally we would have 10-30% of our images in validation set but as we want best possible score we'll use all our images to train, as we have quite few training images already. "
145 | ]
146 | },
147 | {
148 | "cell_type": "code",
149 | "execution_count": null,
150 | "metadata": {
151 | "_uuid": "32f27dd808794bf8659b9e668b0e490bc6a104b7"
152 | },
153 | "outputs": [],
154 | "source": [
155 | "_,_,image_ids = next(walk('training_data/images'))\n",
156 | "image_ids = [i[:-4] for i in image_ids]\n",
157 | "open('annotations.csv','w')\n",
158 | "open('val_annotations.csv','w')\n",
159 | "\n",
160 | "train_ids,val_ids = train_test_split(image_ids,random_state=31,test_size=0)\n",
161 | "\n",
162 | "for image_id in train_ids:\n",
163 | " convert_annotation(image_id,'annotations.csv')\n",
164 | " \n",
165 | "for image_id in val_ids:\n",
166 | " convert_annotation(image_id,'val_annotations.csv')\n",
167 | " \n",
168 | "print(len(train_ids),len(val_ids))"
169 | ]
170 | },
171 | {
172 | "cell_type": "code",
173 | "execution_count": null,
174 | "metadata": {
175 | "_uuid": "93124e395a1fdc94926afe1b71179770c84d587b"
176 | },
177 | "outputs": [],
178 | "source": [
179 | "with open('classes.csv','w') as f:\n",
180 | " f.write('1,0\\n2,1\\n')"
181 | ]
182 | },
183 | {
184 | "cell_type": "markdown",
185 | "metadata": {
186 | "_uuid": "add87f5c791fbe8da4793a384e983235587d1626"
187 | },
188 | "source": [
189 | "# Anchor Parameters\n",
190 | "\n",
191 | "1. Anchor parameters are used to decide how anchor boxes will be generated for the model.\n",
192 | "1. As we're dealing mostly small boxes with can be highly elongated, we'll change ratios and scales to fit our needs.\n",
193 | "1. test_anchors.ipynb is used to visualize anchors on ground truth boxes"
194 | ]
195 | },
196 | {
197 | "cell_type": "code",
198 | "execution_count": null,
199 | "metadata": {
200 | "_uuid": "17398f319e28dd6e38948e2e09dc87481e1966bc"
201 | },
202 | "outputs": [],
203 | "source": [
204 | "with open('config.ini','w') as f:\n",
205 | " f.write('[anchor_parameters]\\nsizes = 32 64 128 256 512\\nstrides = 8 16 32 64 128\\nratios = 0.25 0.5 0.75 1 1.5 2 4 6 8 10\\nscales = 0.5 1 2\\n')"
206 | ]
207 | },
208 | {
209 | "cell_type": "markdown",
210 | "metadata": {
211 | "_uuid": "867d2c56814d761227270459f837b787e616f4c5"
212 | },
213 | "source": [
214 | "# Some Hyperparameters\n",
215 | "\n",
216 | "We will rescale our images to 672x672 for better precision"
217 | ]
218 | },
219 | {
220 | "cell_type": "code",
221 | "execution_count": null,
222 | "metadata": {
223 | "_uuid": "ab8e28dc982006ee8f8800a9021433f0d716fc48"
224 | },
225 | "outputs": [],
226 | "source": [
227 | "b = backbone('resnet50')\n",
228 | "\n",
229 | "class args:\n",
230 | " batch_size = 64\n",
231 | " config = read_config_file('config.ini')\n",
232 | " random_transform = True # Image augmentation\n",
233 | " annotations = 'annotations.csv'\n",
234 | " val_annotations = 'val_annotations.csv'\n",
235 | " classes = 'classes.csv'\n",
236 | " image_min_side = 672\n",
237 | " image_max_side = 672\n",
238 | " dataset_type = 'csv'\n",
239 | " tensorboard_dir = ''\n",
240 | " evaluation = False\n",
241 | " snapshots = True\n",
242 | " snapshot_path = \"saved/\"\n",
243 | " backbone = 'resnet50'\n",
244 | " epochs = 70\n",
245 | " steps = len(train_ids)//(batch_size)\n",
246 | " weighted_average = True"
247 | ]
248 | },
249 | {
250 | "cell_type": "code",
251 | "execution_count": null,
252 | "metadata": {
253 | "_uuid": "e4551ed97d6ee33f91283f559bbb7d9549d2d1f6"
254 | },
255 | "outputs": [],
256 | "source": [
257 | "train_gen,valid_gen = create_generators(args,b.preprocess_image)"
258 | ]
259 | },
260 | {
261 | "cell_type": "markdown",
262 | "metadata": {
263 | "_uuid": "48482aa28034ede1fc5dd69661bbf83163ddb7bd"
264 | },
265 | "source": [
266 | "# Image Augmentation\n",
267 | "\n",
268 | "In addition to augmentations already done by keras-retinanet [here](https://github.com/fizyr/keras-retinanet/blob/master/keras_retinanet/bin/train.py#L227) , we'll use a package called imgaug to furthur augment the data.\n"
269 | ]
270 | },
271 | {
272 | "cell_type": "code",
273 | "execution_count": null,
274 | "metadata": {
275 | "_uuid": "c09f817a02a3c385181a216f1c7c1af993efcf09"
276 | },
277 | "outputs": [],
278 | "source": [
279 | "sometimes = lambda aug: iaa.Sometimes(0.5, aug)\n",
280 | "# Define our sequence of augmentation steps that will be applied to every image.\n",
281 | "seq = iaa.Sequential(\n",
282 | " [\n",
283 | " #\n",
284 | " # Execute 1 to 9 of the following (less important) augmenters per\n",
285 | " # image. Don't execute all of them, as that would often be way too\n",
286 | " # strong.\n",
287 | " #\n",
288 | " iaa.SomeOf((1, 9),\n",
289 | " [\n",
290 | "\n",
291 | " # Blur each image with varying strength using\n",
292 | " # gaussian blur (sigma between 0 and .5),\n",
293 | " # average/uniform blur (kernel size 1x1)\n",
294 | " # median blur (kernel size 1x1).\n",
295 | " iaa.OneOf([\n",
296 | " iaa.GaussianBlur((0,0.5)),\n",
297 | " iaa.AverageBlur(k=(1)),\n",
298 | " iaa.MedianBlur(k=(1)),\n",
299 | " ]),\n",
300 | "\n",
301 | " # Sharpen each image, overlay the result with the original\n",
302 | " # image using an alpha between 0 (no sharpening) and 1\n",
303 | " # (full sharpening effect).\n",
304 | " iaa.Sharpen(alpha=(0, 0.25), lightness=(0.75, 1.5)),\n",
305 | "\n",
306 | " # Add gaussian noise to some images.\n",
307 | " # In 50% of these cases, the noise is randomly sampled per\n",
308 | " # channel and pixel.\n",
309 | " # In the other 50% of all cases it is sampled once per\n",
310 | " # pixel (i.e. brightness change).\n",
311 | " iaa.AdditiveGaussianNoise(\n",
312 | " loc=0, scale=(0.0, 0.01*255), per_channel=0.5\n",
313 | " ),\n",
314 | "\n",
315 | " # Either drop randomly 1 to 10% of all pixels (i.e. set\n",
316 | " # them to black) or drop them on an image with 2-5% percent\n",
317 | " # of the original size, leading to large dropped\n",
318 | " # rectangles.\n",
319 | " iaa.OneOf([\n",
320 | " iaa.Dropout((0.01, 0.1), per_channel=0.5),\n",
321 | " iaa.CoarseDropout(\n",
322 | " (0.03, 0.15), size_percent=(0.02, 0.05),\n",
323 | " per_channel=0.2\n",
324 | " ),\n",
325 | " ]),\n",
326 | "\n",
327 | " # Add a value of -5 to 5 to each pixel.\n",
328 | " iaa.Add((-5, 5), per_channel=0.5),\n",
329 | "\n",
330 | " # Change brightness of images (85-115% of original value).\n",
331 | " iaa.Multiply((0.85, 1.15), per_channel=0.5),\n",
332 | "\n",
333 | " # Improve or worsen the contrast of images.\n",
334 | " iaa.ContrastNormalization((0.75, 1.25), per_channel=0.5),\n",
335 | "\n",
336 | " # Convert each image to grayscale and then overlay the\n",
337 | " # result with the original with random alpha. I.e. remove\n",
338 | " # colors with varying strengths.\n",
339 | " iaa.Grayscale(alpha=(0.0, 0.25)),\n",
340 | "\n",
341 | " # In some images distort local areas with varying strength.\n",
342 | " sometimes(iaa.PiecewiseAffine(scale=(0.001, 0.01)))\n",
343 | " ],\n",
344 | " # do all of the above augmentations in random order\n",
345 | " random_order=True\n",
346 | " )\n",
347 | " ],\n",
348 | " # do all of the above augmentations in random order\n",
349 | " random_order=True\n",
350 | ")"
351 | ]
352 | },
353 | {
354 | "cell_type": "code",
355 | "execution_count": null,
356 | "metadata": {
357 | "_uuid": "e2743e4a77f3b2d2e1c702b0c968e07e7603d2cc"
358 | },
359 | "outputs": [],
360 | "source": [
361 | "def augment_train_gen(train_gen,visualize=False):\n",
362 | " '''\n",
363 | " Creates a generator using another generator with applied image augmentation.\n",
364 | " Args\n",
365 | " train_gen : keras-retinanet generator object.\n",
366 | " visualize : Boolean; False will convert bounding boxes to their anchor box targets for the model.\n",
367 | " '''\n",
368 | " imgs = []\n",
369 | " boxes = []\n",
370 | " targets = []\n",
371 | " size = train_gen.size()\n",
372 | " idx = 0\n",
373 | " while True:\n",
374 | " while len(imgs) < args.batch_size:\n",
375 | " image = train_gen.load_image(idx % size)\n",
376 | " annotations = train_gen.load_annotations(idx % size)\n",
377 | " image,annotations = train_gen.random_transform_group_entry(image,annotations)\n",
378 | " imgs.append(image) \n",
379 | " boxes.append(annotations['bboxes'])\n",
380 | " targets.append(annotations)\n",
381 | " idx += 1\n",
382 | " if visualize:\n",
383 | " imgs = seq.augment_images(imgs)\n",
384 | " imgs = np.array(imgs)\n",
385 | " boxes = np.array(boxes)\n",
386 | " yield imgs,boxes\n",
387 | " else:\n",
388 | " imgs = seq.augment_images(imgs)\n",
389 | " imgs,targets = train_gen.preprocess_group(imgs,targets)\n",
390 | " imgs = train_gen.compute_inputs(imgs)\n",
391 | " targets = train_gen.compute_targets(imgs,targets)\n",
392 | " imgs = np.array(imgs)\n",
393 | " yield imgs,targets\n",
394 | " imgs = []\n",
395 | " boxes = []\n",
396 | " targets = []\n",
397 | " "
398 | ]
399 | },
400 | {
401 | "cell_type": "markdown",
402 | "metadata": {
403 | "_uuid": "755f6bb05e3251d40877ddba74c8f6486678f47c"
404 | },
405 | "source": [
406 | "# Visualize augmentations"
407 | ]
408 | },
409 | {
410 | "cell_type": "code",
411 | "execution_count": null,
412 | "metadata": {
413 | "_uuid": "bcd7d99112b845fe8b42ca980d3842361db93614"
414 | },
415 | "outputs": [],
416 | "source": [
417 | "import matplotlib.pyplot as plt\n",
418 | "\n",
419 | "skip_batches = 5\n",
420 | "i = 0\n",
421 | "\n",
422 | "for imgs,boxes in augment_train_gen(train_gen,visualize=True):\n",
423 | " if i > skip_batches:\n",
424 | " fig=plt.figure(figsize=(24,96))\n",
425 | " columns = 2\n",
426 | " rows = 8\n",
427 | " for i in range(1, columns*rows + 1):\n",
428 | " draw_boxes(imgs[i], boxes[i], (0, 255, 0), thickness=1)\n",
429 | " fig.add_subplot(rows, columns, i)\n",
430 | " plt.imshow(cv2.cvtColor(imgs[i],cv2.COLOR_BGR2RGB))\n",
431 | " plt.show()\n",
432 | " break\n",
433 | " else:\n",
434 | " i += 1\n"
435 | ]
436 | },
437 | {
438 | "cell_type": "markdown",
439 | "metadata": {
440 | "_uuid": "35f45954269581be05dbc6a9601965db625609d8"
441 | },
442 | "source": [
443 | "# More Hyperparameters\n",
444 | "\n",
445 | "we'll use learning rate of 0.001 and freeze weights for the backbone"
446 | ]
447 | },
448 | {
449 | "cell_type": "code",
450 | "execution_count": null,
451 | "metadata": {
452 | "_uuid": "de392d655a630d3b73dfa84fe1febbed0f3fdbe2"
453 | },
454 | "outputs": [],
455 | "source": [
456 | "model, training_model, prediction_model = create_models(\n",
457 | " backbone_retinanet=b.retinanet,\n",
458 | " num_classes=train_gen.num_classes(),\n",
459 | " weights=None,\n",
460 | " multi_gpu=False,\n",
461 | " freeze_backbone=True,\n",
462 | " lr=1e-3,\n",
463 | " config=args.config\n",
464 | " )"
465 | ]
466 | },
467 | {
468 | "cell_type": "code",
469 | "execution_count": null,
470 | "metadata": {
471 | "_uuid": "a34e90ba8fec837af9007610241b487b9a6a807c"
472 | },
473 | "outputs": [],
474 | "source": [
475 | "callbacks = create_callbacks(\n",
476 | " model,\n",
477 | " training_model,\n",
478 | " prediction_model,\n",
479 | " valid_gen,\n",
480 | " args,\n",
481 | ")"
482 | ]
483 | },
484 | {
485 | "cell_type": "markdown",
486 | "metadata": {
487 | "_uuid": "33285a3b74dc8580797f86678e080cbfecd7c668"
488 | },
489 | "source": [
490 | "# Download pretrained model\n",
491 | "\n",
492 | "We download a pretrained model on COCO dataset and load it's weights, we'll skip loading the weights for the few last layers"
493 | ]
494 | },
495 | {
496 | "cell_type": "code",
497 | "execution_count": null,
498 | "metadata": {
499 | "_uuid": "764a0430cc7c5f5f341bb3ba3bb89b699248481e"
500 | },
501 | "outputs": [],
502 | "source": [
503 | "!wget https://github.com/fizyr/keras-retinanet/releases/download/0.5.0/resnet50_coco_best_v2.1.0.h5"
504 | ]
505 | },
506 | {
507 | "cell_type": "code",
508 | "execution_count": null,
509 | "metadata": {
510 | "_uuid": "275ddf407b82092a0ec8a514500c0987f918d59b"
511 | },
512 | "outputs": [],
513 | "source": [
514 | "training_model.load_weights('resnet50_coco_best_v2.1.0.h5',skip_mismatch=True,by_name=True)"
515 | ]
516 | },
517 | {
518 | "cell_type": "markdown",
519 | "metadata": {
520 | "_uuid": "f7cd58d21715eb0ec3a9de5b30be8cea85915726"
521 | },
522 | "source": [
523 | "# Train the model\n",
524 | "\n",
525 | "We will train for 70 epochs"
526 | ]
527 | },
528 | {
529 | "cell_type": "code",
530 | "execution_count": null,
531 | "metadata": {
532 | "_uuid": "06bca3482f679c50640b7396bafb9b291b4f402b"
533 | },
534 | "outputs": [],
535 | "source": [
536 | "training_model.fit_generator(generator=augment_train_gen(train_gen),\n",
537 | " steps_per_epoch=args.steps,\n",
538 | " epochs=args.epochs,\n",
539 | " verbose=1,\n",
540 | " callbacks=callbacks,)"
541 | ]
542 | },
543 | {
544 | "cell_type": "code",
545 | "execution_count": null,
546 | "metadata": {
547 | "_uuid": "7a5b84c37c58444c37e6d08fb6de19b756c03926"
548 | },
549 | "outputs": [],
550 | "source": []
551 | }
552 | ],
553 | "metadata": {
554 | "kernelspec": {
555 | "display_name": "Python 3",
556 | "language": "python",
557 | "name": "python3"
558 | },
559 | "language_info": {
560 | "codemirror_mode": {
561 | "name": "ipython",
562 | "version": 3
563 | },
564 | "file_extension": ".py",
565 | "mimetype": "text/x-python",
566 | "name": "python",
567 | "nbconvert_exporter": "python",
568 | "pygments_lexer": "ipython3",
569 | "version": "3.6.7"
570 | }
571 | },
572 | "nbformat": 4,
573 | "nbformat_minor": 2
574 | }
575 |
--------------------------------------------------------------------------------
/visualize.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Visualize predictions on test set\n",
8 | "\n",
9 | "Set image_id to visualize predictions for that image"
10 | ]
11 | },
12 | {
13 | "cell_type": "code",
14 | "execution_count": null,
15 | "metadata": {},
16 | "outputs": [],
17 | "source": [
18 | "from keras_retinanet.utils.visualization import draw_box, draw_caption\n",
19 | "from keras_retinanet.utils.colors import label_color\n",
20 | "from keras_retinanet.utils.image import read_image_bgr, preprocess_image, resize_image\n",
21 | "import cv2\n",
22 | "from os import walk\n",
23 | "import matplotlib.pyplot as plt\n",
24 | "\n",
25 | "_,_,image_ids = next(walk('test_data_images/images'))\n",
26 | "image_ids = [i[:-4] for i in image_ids]\n",
27 | "image_ids = sorted(image_ids)\n",
28 | "\n",
29 | "idx = 0\n",
30 | "image_id = 1\n",
31 | "score_thres = 0.\n",
32 | "\n",
33 | "for id in image_ids:\n",
34 | " # load image\n",
35 | " idx += 1\n",
36 | " if idx == image_id:\n",
37 | " image = read_image_bgr('test_data_images/images/' + id + '.jpg')\n",
38 | "\n",
39 | " # copy to draw on\n",
40 | " draw = image.copy()\n",
41 | " draw = cv2.cvtColor(draw, cv2.COLOR_BGR2RGB)\n",
42 | "\n",
43 | " # process image\n",
44 | " boxes = [list(map(int,(line.split()[3],line.split()[2],line.split()[5],line.split()[4]))) for line in open('predictions/' + id + '.txt','r').readlines()]\n",
45 | " scores = [float(line.split()[1]) for line in open('predictions/' + id + '.txt','r').readlines()]\n",
46 | " labels = [int(line.split()[0]) - 1 for line in open('predictions/' + id + '.txt','r').readlines()]\n",
47 | " for box, score, label in zip(boxes, scores, labels):\n",
48 | " if score < score_thres:\n",
49 | " break\n",
50 | " color = label_color(label)\n",
51 | " draw_box(draw, box, color=color,thickness=1)\n",
52 | " caption = \"{:.3f}\".format(score)\n",
53 | " draw_caption(draw, box, caption)\n",
54 | "\n",
55 | " plt.figure(figsize=(15, 15))\n",
56 | " plt.axis('off')\n",
57 | " plt.imshow(draw)\n",
58 | " plt.show()\n",
59 | " break"
60 | ]
61 | },
62 | {
63 | "cell_type": "code",
64 | "execution_count": null,
65 | "metadata": {},
66 | "outputs": [],
67 | "source": []
68 | }
69 | ],
70 | "metadata": {
71 | "kernelspec": {
72 | "display_name": "Python 3",
73 | "language": "python",
74 | "name": "python3"
75 | },
76 | "language_info": {
77 | "codemirror_mode": {
78 | "name": "ipython",
79 | "version": 3
80 | },
81 | "file_extension": ".py",
82 | "mimetype": "text/x-python",
83 | "name": "python",
84 | "nbconvert_exporter": "python",
85 | "pygments_lexer": "ipython3",
86 | "version": "3.6.7"
87 | }
88 | },
89 | "nbformat": 4,
90 | "nbformat_minor": 2
91 | }
92 |
--------------------------------------------------------------------------------