├── LICENSE ├── README.md ├── convert.py ├── data.py ├── index.py ├── mask.py ├── run.py ├── settings.py ├── video.py └── visuals ├── train-chunk-0.avi ├── train-chunk-0.png ├── train-chunk-1.avi ├── train-chunk-1.png ├── train-chunk-2.avi ├── train-chunk-2.png ├── train-chunk-3.avi ├── train-chunk-3.png ├── train-chunk-4.avi ├── train-chunk-4.png ├── train-chunk-5.avi ├── train-chunk-5.png ├── train-chunk-6.avi ├── train-chunk-6.png ├── train-chunk-7.avi ├── train-chunk-7.png ├── train-vid.avi └── train-vid.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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Data Science Bowl 2017 2 | 3 | ## Description 4 | 5 | This code is for training a 3D Convolutional Neural Network on the [LUNA16](https://luna16.grand-challenge.org/home/) dataset in order to detect malignant nodules. I am hopeful that this can be used as the first step towards solving the [DSB 2017 challenge](https://www.kaggle.com/c/data-science-bowl-2017). 6 | 7 | #### What it does 8 | 9 | As given, the code does not make predictions on the DSB dataset provided by Kaggle. What it does do is build a model to predict the probability that a 64mm x 64mm x 64mm chunk of tissue contains a malignant nodule. The model is trained on the LUNA16 dataset, which includes labels that identify nodule locations in 3D space. The DSB dataset on the other hand, comes with binary labels and is not suitable for training such a model (using LUNA16 data is allowed per the contest rules). 10 | 11 | During data preparation, the images are converted to 3D data and segmented to eliminate non-lung tissue. The segmentation algorithm used is rather simplistic and in fact fails in about 10% of the cases. The entire image is used when a segmentation failure is detected. 12 | 13 | During training, chunks are extracted based on the coordinates given in `annotations_excluded.csv` (this has both positive and negative locations). Dimension shuffling is used randomly to augment the training set. To minimize overfitting further, some amount of jitter is applied to the coordinates. 14 | 15 | Here's a visualization of the first eight chunks extracted from the first sample in the training set (it is quite easy to spot the nodule). 16 | 17 | | | | | | 18 | |------------|--------------|------------|----------| 19 | |![](visuals/train-chunk-0.png) | ![](visuals/train-chunk-1.png) | ![](visuals/train-chunk-2.png) | ![](visuals/train-chunk-3.png) | 20 | |![](visuals/train-chunk-4.png) | ![](visuals/train-chunk-5.png) | ![](visuals/train-chunk-6.png) | ![](visuals/train-chunk-7.png) | 21 | 22 | The chunks can be downloaded in video form from the [`visuals`](visuals) directory. The file [`train-vid.avi`](visuals/train-vid.avi) contains the entire 3D sample from which the above chunks were obtained. Since this is a positive sample, all of the chunks derived from it are assigned a label of 1. A label of 0 is assigned to all chunks extracted from negative samples. 80% of the training set is thus used to train the network to perform a binary classification. The model is validated on the rest of the data and a log loss of **0.3080** is observed after six epochs of training. 23 | 24 | #### Where to go from here 25 | 26 | Once you have trained a model by following the recipe given in the `Usage` section below, there are a couple of possible ways to proceed with the DSB challenge. 27 | 28 | 1) If you already have a system to detect locations of possible candidates, you can feed chunks from those locations to the trained model in order to get predictions. Before you submit the predictions to Kaggle, they need to be calibrated to match the distribution of the DSB dataset. 29 | 30 | Or 31 | 32 | 2) From each sample in the DSB dataset, extract overlapping chunks and feed them to the trained model to get a 3D heatmap of nodule probabilities over the entire sample. Use heatmaps generated from the DSB training set along with the corresponding binary labels to train a second model. Once trained, use this model to generate predictions on the test dataset and submit them to Kaggle for scoring. 33 | 34 | ## Usage 35 | 1. Download and install [neon](https://github.com/NervanaSystems/neon) **1.8.2** 36 | 37 | For information about requirements of neon, see the [installation instructions](http://neon.nervanasys.com/docs/latest/installation.html). Once the required packages are installed, issue the following commands to install neon: 38 | ``` 39 | git clone https://github.com/NervanaSystems/neon.git 40 | cd neon 41 | git checkout v1.8.2 42 | make 43 | source .venv/bin/activate 44 | ``` 45 | 46 | 2. Verify neon installation 47 | 48 | Make sure that this command does not result in any errors: 49 | ``` 50 | ./examples/mnist_mlp.py -e 1 -b gpu 51 | ``` 52 | 53 | 3. Download the data files from [LUNA16 Website](https://luna16.grand-challenge.org/home/): 54 | 55 | The CT images (`subset0.zip` to `subset9.zip`) can be obtained from [Google Drive](https://drive.google.com/folderview?id=0Bz-jINrxV740SWE1UjR4RXFKRm8&usp=sharing). You will also need `annotations_excluded.csv` from the [evaluation script package](https://www.dropbox.com/s/wue67fg9bk5xdxt/evaluationScript.zip?dl=0). Unzip all the zip files to a directory (referred to as `luna` from now on) and copy `annotations_excluded.csv` to the same directory. 56 | 57 | 4. Install the prerequisites for this repository 58 | 59 | ``` 60 | pip install scipy scikit-image pandas SimpleITK blosc 61 | ``` 62 | 63 | 5. Clone this repository 64 | 65 | ``` 66 | git clone https://github.com/anlthms/dsb-2017.git 67 | cd dsb-2017 68 | ``` 69 | 70 | 6. Prepare the data, train a model and validate 71 | 72 | ``` 73 | ./convert.py luna luna/vids train 74 | ./index.py luna/vids luna/vids/metadata.csv 75 | ./run.py -e 6 -w luna/vids -r 0 -v -eval 1 -s model.pkl 76 | ``` 77 | 78 | The first command performs segmentation of the CT images and saves the result as blosc compressed files. This could take a couple of hours and in the end you should have 871 files with the extension `blp` inside `luna/vids`. You will also see two CSV files, `metadata.csv` and `labels.csv`. First few lines from both are shown below: 79 | 80 | **metadata.csv** 81 | 82 | |Column name | Description | 83 | |------------|-------------| 84 | | uid | user ID 85 | | flag | malignancy 86 | | z_len | number of frames 87 | | y_len | number of rows 88 | | x_len | number of columns 89 | 90 | ``` 91 | uid,flag,z_len,y_len,x_len 92 | 1.3.6.1.4.1.14519.5.2.1.6279.6001.139258777898746693365877042411,1.0,264.0,199.0,256.0 93 | 1.3.6.1.4.1.14519.5.2.1.6279.6001.458525794434429386945463560826,1.0,309.0,250.0,332.0 94 | 1.3.6.1.4.1.14519.5.2.1.6279.6001.296066944953051278419805374238,0.0,298.0,185.0,263.0 95 | ... 96 | ``` 97 | 98 | **labels.csv** 99 | 100 | |Column name | Description | 101 | |------------|-------------| 102 | | uid | user ID 103 | | flag | malignancy 104 | | z | Z coordinate of ROI center 105 | | y | Y coordinate of ROI center 106 | | x | X coordinate of ROI center 107 | | diam | diameter of nodule in voxels 108 | | vol | volume of nodule in voxels 109 | 110 | All coordinates are specified in voxel space. 111 | 112 | ``` 113 | uid,flag,z,y,x,diam,vol 114 | 1.3.6.1.4.1.14519.5.2.1.6279.6001.139258777898746693365877042411,1.0,113.0,65.0,45.0,8.664065325,340.536585116 115 | 1.3.6.1.4.1.14519.5.2.1.6279.6001.139258777898746693365877042411,1.0,113.0,65.0,45.0,8.757032371,351.616695126 116 | 1.3.6.1.4.1.14519.5.2.1.6279.6001.139258777898746693365877042411,1.0,113.0,64.0,45.0,9.214425385,409.640978834 117 | 1.3.6.1.4.1.14519.5.2.1.6279.6001.458525794434429386945463560826,1.0,63.0,198.0,277.0,4.863875316,60.2484561207 118 | 1.3.6.1.4.1.14519.5.2.1.6279.6001.458525794434429386945463560826,1.0,270.0,161.0,122.0,5.987144555,112.371933691 119 | 1.3.6.1.4.1.14519.5.2.1.6279.6001.458525794434429386945463560826,1.0,83.0,144.0,303.0,4.909763642,61.9698405721 120 | 1.3.6.1.4.1.14519.5.2.1.6279.6001.458525794434429386945463560826,1.0,270.0,161.0,122.0,5.971288559,111.481498684 121 | 1.3.6.1.4.1.14519.5.2.1.6279.6001.458525794434429386945463560826,1.0,270.0,161.0,122.0,5.722485538,98.1189142203 122 | 1.3.6.1.4.1.14519.5.2.1.6279.6001.296066944953051278419805374238,0.0,253.0,146.0,185.0,0.0,0.0 123 | 1.3.6.1.4.1.14519.5.2.1.6279.6001.296066944953051278419805374238,0.0,230.0,142.0,219.0,0.0,0.0 124 | ... 125 | ``` 126 | 127 | The second command divides the data into training and validation subsets and produces two index files named `train-metadata.csv` and `val-metadata.csv`. These files are used in the next step for loading the data. 128 | 129 | The third command fits a model on the training dataset and performs validation. The output should look similar to: 130 | 131 | ``` 132 | Epoch 0 [Train |████████████████████| 696/696 batches, 0.74 cost, 638.26s] [CrossEntropyBinary Loss 0.72, 147.45s] 133 | 2017-03-19 23:44:46,501 - neon.callbacks.callbacks - INFO - Epoch 0 complete. Train Cost 0.773655. Eval Cost 0.716362 134 | 135 | Epoch 1 [Train |████████████████████| 696/696 batches, 0.70 cost, 502.88s] [CrossEntropyBinary Loss 0.94, 121.08s] 136 | 2017-03-19 23:55:33,975 - neon.callbacks.callbacks - INFO - Epoch 1 complete. Train Cost 0.644113. Eval Cost 0.937822 137 | 138 | Epoch 2 [Train |████████████████████| 696/696 batches, 0.59 cost, 610.48s] [CrossEntropyBinary Loss 0.77, 143.17s] 139 | 2017-03-20 00:08:32,596 - neon.callbacks.callbacks - INFO - Epoch 2 complete. Train Cost 0.596019. Eval Cost 0.765760 140 | 141 | Epoch 3 [Train |████████████████████| 696/696 batches, 0.53 cost, 619.91s] [CrossEntropyBinary Loss 0.74, 141.25s] 142 | 2017-03-20 00:21:39,025 - neon.callbacks.callbacks - INFO - Epoch 3 complete. Train Cost 0.570212. Eval Cost 0.737797 143 | 144 | Epoch 4 [Train |████████████████████| 696/696 batches, 0.64 cost, 491.20s] [CrossEntropyBinary Loss 0.68, 111.02s] 145 | 2017-03-20 00:32:06,076 - neon.callbacks.callbacks - INFO - Epoch 4 complete. Train Cost 0.547899. Eval Cost 0.681645 146 | 147 | Epoch 5 [Train |████████████████████| 696/696 batches, 0.57 cost, 604.10s] [CrossEntropyBinary Loss 0.62, 118.09s] 148 | 2017-03-20 00:44:33,088 - neon.callbacks.callbacks - INFO - Epoch 5 complete. Train Cost 0.520916. Eval Cost 0.619619 149 | 2017-03-20 00:53:33,183 - neon - DISPLAY - Test Logloss = 0.3080 150 | ``` 151 | 152 | The trained weights are saved to model.pkl which can be used for performing inference on test data. 153 | 154 | ## Source code files 155 | 156 | | File | Description | 157 | |-----------|-------------------------------------------------------------------------------| 158 | |convert.py | code for converting DICOM images to video data 159 | |index.py | code to generate index files for training and validation 160 | |data.py | specialized dataloader (and augmenter) that extracts chunks from videos 161 | |run.py | model to train classifier on chunks 162 | |video.py | utility functions for video related operations 163 | |mask.py | utility functions for segmenting 164 | |settings.py| common settings 165 | 166 | 167 | ## Notes 168 | 169 | To preprocess the DSB dataset, use this command: 170 | 171 | ``` 172 | ./convert.py dsb/stage1 dsb/vids test 173 | ``` 174 | 175 | The directory `dsb` refers to the directory where the dataset was unzipped into. The result of preprocessing may be found inside `dsb/vids`. 176 | -------------------------------------------------------------------------------- /convert.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # 3 | # Copyright 2017 Anil Thomas 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | # 17 | """ 18 | Convert DICOM images to video data 19 | """ 20 | 21 | from __future__ import print_function, division 22 | import os 23 | import sys 24 | import SimpleITK as sitk 25 | import numpy as np 26 | import pandas as pd 27 | import functools 28 | import multiprocessing 29 | from scipy import ndimage 30 | from glob import glob 31 | 32 | import settings 33 | import video 34 | import mask 35 | 36 | 37 | def process_annotations(uid, annots, origin, labels, shape, starts): 38 | if not is_train: 39 | return (True, -1) 40 | 41 | uid_data = annots[annots['seriesuid'] == uid] 42 | if uid_data.shape[0] == 0: 43 | return (True, 0) 44 | 45 | locs = [] 46 | for idx in range(uid_data.shape[0]): 47 | row = uid_data.iloc[idx] 48 | center = np.array([row['coordZ'], row['coordY'], row['coordX']]) 49 | diam = row['diameter_mm'] 50 | if diam == -1: 51 | diam = 0 52 | diam /= settings.resolution 53 | flag = 0 if diam == 0 else 1 54 | vox_center = np.int32(np.rint((center - origin)/settings.resolution)) 55 | vox_center -= starts 56 | for i in range(3): 57 | if vox_center[i] < 0: 58 | return (False, 0) 59 | if vox_center[i] >= shape[i]: 60 | return (False, 0) 61 | vol = 0 if diam == 0 else 4*np.pi*((diam/2)**3)/3 62 | locs.append(dict(uid=uid, flag=flag, 63 | z=vox_center[0], y=vox_center[1], x=vox_center[2], 64 | diam=diam, vol=vol)) 65 | 66 | filtered, is_positive = filter_cands(locs) 67 | for line in filtered: 68 | labels.loc[labels.shape[0]] = line 69 | return (True, is_positive) 70 | 71 | 72 | def filter_cands(locs): 73 | diams = [loc['diam'] for loc in locs] 74 | if np.sum(diams) == 0: 75 | # No malignancy - no need to filter 76 | return locs, 0 77 | # Do not take negative candidates from a sample with malignancy 78 | result = [loc for loc in locs if loc['diam'] != 0] 79 | return result, 1 80 | 81 | 82 | def read_scan(path): 83 | uid = os.path.basename(path) 84 | if uid.split('.')[-1] == 'mhd': 85 | uid = uid[:-4] 86 | return sitk.ReadImage(path), uid 87 | 88 | reader = sitk.ImageSeriesReader() 89 | image_files = reader.GetGDCMSeriesFileNames(path) 90 | assert len(image_files) > 0 91 | if len(image_files) < settings.chunk_size: 92 | print('Ignoring %s - only %d slices' % (path, len(image_files))) 93 | return None, uid 94 | 95 | reader.SetFileNames(image_files) 96 | return reader.Execute(), uid 97 | 98 | 99 | def get_data(scan_data): 100 | data = sitk.GetArrayFromImage(scan_data) 101 | # Convert to (z, y, x) ordering 102 | spacing = np.array(list(reversed(scan_data.GetSpacing()))) 103 | spacing /= settings.resolution 104 | slices = ndimage.interpolation.zoom(data, spacing, mode='nearest') 105 | origin = np.array(list(reversed(scan_data.GetOrigin()))) 106 | return slices, spacing, origin 107 | 108 | 109 | def trim(slices): 110 | starts = np.zeros(3, dtype=np.int32) 111 | end_vals = [slices.shape[i] for i in range(3)] 112 | ends = np.array(end_vals, dtype=np.int32) 113 | 114 | while slices[starts[0]].sum() == 0: 115 | starts[0] += 1 116 | while slices[:, starts[1]].sum() == 0: 117 | starts[1] += 1 118 | while slices[..., starts[2]].sum() == 0: 119 | starts[2] += 1 120 | 121 | while slices[ends[0] - 1].sum() == 0: 122 | ends[0] -= 1 123 | while slices[:, ends[1] - 1].sum() == 0: 124 | ends[1] -= 1 125 | while slices[..., ends[2] - 1].sum() == 0: 126 | ends[2] -= 1 127 | 128 | trimmed = slices[starts[0]:ends[0], starts[1]:ends[1], starts[2]:ends[2]] 129 | return trimmed, starts 130 | 131 | 132 | def convert(path_list, annots, batch_size, max_idx, idx): 133 | start = idx * batch_size 134 | end = min(start + batch_size, max_idx) 135 | path_list = path_list[start:end] 136 | meta = pd.DataFrame(columns=['uid', 'flag', 'z_len', 'y_len', 'x_len']) 137 | labels = pd.DataFrame(columns=['uid', 'flag', 'z', 'y', 'x', 'diam', 'vol']) 138 | for i, path in enumerate(path_list): 139 | if os.path.basename(path) == 'b8bb02d229361a623a4dc57aa0e5c485': 140 | # ITK cannot read this file 141 | continue 142 | print('Converting %s' % path) 143 | scan_data, uid = read_scan(path) 144 | if scan_data is None: 145 | continue 146 | 147 | slices, spacing, origin = get_data(scan_data) 148 | skip = 0 149 | 150 | video.clip(slices, settings.low_thresh, settings.high_thresh) 151 | msk = mask.get_mask(slices, uid) 152 | slices = video.normalize(slices, settings.low_thresh, settings.high_thresh) 153 | mask.apply_mask(slices, msk) 154 | slices, starts = trim(slices) 155 | valid, flag = process_annotations(uid, annots, origin, labels, slices.shape, starts) 156 | if not valid: 157 | print('Ignoring %s - bad metadata' % path) 158 | continue 159 | 160 | video.write_data(slices, os.path.join(output_path, uid)) 161 | meta.loc[meta.shape[0]] = dict(uid=uid, flag=flag, z_len=slices.shape[0], 162 | y_len=slices.shape[1], x_len=slices.shape[2]) 163 | return meta, labels 164 | 165 | 166 | if len(sys.argv) < 4: 167 | print('Usage %s train/test' % sys.argv[0]) 168 | sys.exit(0) 169 | 170 | np.random.seed(0) 171 | input_path = sys.argv[1] 172 | output_path = sys.argv[2] 173 | is_train = sys.argv[3] == 'train' 174 | if is_train: 175 | search_path = os.path.join(input_path, 'subset*', '*.mhd') 176 | else: 177 | search_path = os.path.join(input_path, '*') 178 | 179 | if not os.path.exists(output_path): 180 | os.mkdir(output_path) 181 | 182 | path_list = glob(search_path) 183 | path_list = sorted(path_list) 184 | np.random.shuffle(path_list) 185 | if is_train: 186 | annots = pd.read_csv(os.path.join(input_path, 'annotations_excluded.csv')) 187 | else: 188 | annots = None 189 | 190 | count = len(path_list) 191 | assert count > 0, 'Could not find %s' % search_path 192 | print('Converting %d scans...' % count) 193 | 194 | cpu_count = multiprocessing.cpu_count() 195 | batch_size = (count - 1) // cpu_count + 1 196 | processes = (count - 1) // batch_size + 1 197 | 198 | func = functools.partial(convert, path_list, annots, batch_size, count) 199 | pool = multiprocessing.Pool(processes=processes) 200 | ret_list = pool.map(func, range(processes)) 201 | pool.close() 202 | meta_list, labels_list = zip(*ret_list) 203 | meta = pd.concat(meta_list) 204 | labels = pd.concat(labels_list) 205 | meta.to_csv(os.path.join(output_path, 'metadata.csv'), index=False) 206 | if is_train: 207 | labels.to_csv(os.path.join(output_path, 'labels.csv'), index=False) 208 | -------------------------------------------------------------------------------- /data.py: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright 2017 Anil Thomas 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | """ 17 | Data loader that can be iterated over to retrieve minibatches 18 | """ 19 | import logging 20 | import numpy as np 21 | import pandas as pd 22 | import os 23 | import video 24 | import settings 25 | from neon import NervanaObject 26 | 27 | 28 | class ChunkLoader(NervanaObject): 29 | def __init__(self, set_name, repo_dir, datum_dtype=np.uint8, 30 | nclasses=2, augment=False, test_mode=False): 31 | assert test_mode is False, 'Test mode not implemented yet' 32 | super(ChunkLoader, self).__init__() 33 | np.random.seed(0) 34 | self.reset() 35 | self.set_name = set_name 36 | self.bsz = self.be.bsz 37 | self.augment = augment 38 | self.repo_dir = repo_dir 39 | self.is_training = (set_name == 'train') 40 | self.chunk_size = settings.chunk_size 41 | self.chunk_shape = (self.chunk_size, self.chunk_size, self.chunk_size) 42 | self.chunk_volume = np.prod(self.chunk_shape) 43 | self.metadata = pd.read_csv(os.path.join(self.repo_dir, set_name + '-metadata.csv')) 44 | self.nvids = self.metadata.shape[0] 45 | self.chunks_filled = 0 46 | # Load this many videos at a time 47 | self.vids_per_macrobatch = 128 48 | # Extract this many chunks from each video 49 | self.chunks_per_vid = 128 50 | self.macrobatch_offset = 0 51 | self.chunks_left_in_macrobatch = 0 52 | self.macrobatch_size = self.vids_per_macrobatch*self.chunks_per_vid 53 | 54 | self.ndata = self.nvids*self.chunks_per_vid 55 | self.labels = pd.read_csv(os.path.join(self.repo_dir, 'labels.csv')) 56 | # Host buffers for macrobatch data and targets 57 | self.data = np.empty((self.macrobatch_size, self.chunk_volume), dtype=datum_dtype) 58 | self.targets = np.empty((self.macrobatch_size, nclasses), dtype=np.float32) 59 | self.minibatch_data = np.empty((self.bsz, self.chunk_volume), dtype=datum_dtype) 60 | self.minibatch_targets = np.empty((self.bsz, nclasses), dtype=np.float32) 61 | self.test_mode = test_mode 62 | self.chunk_count = 0 63 | self.shape = (1, self.chunk_size, self.chunk_size, self.chunk_size) 64 | 65 | self.transform_buffer = np.empty(self.chunk_shape, dtype=datum_dtype) 66 | # Device buffers for minibatch data and targets 67 | self.dev_data = self.be.empty((self.chunk_volume, self.bsz), dtype=self.be.default_dtype) 68 | self.dev_targets = self.be.empty((nclasses, self.bsz), dtype=self.be.default_dtype) 69 | self.current_flag = self.current_meta = None 70 | 71 | def reset(self): 72 | self.start_idx = 0 73 | self.video_idx = 0 74 | self.macrobatch_offset = 0 75 | self.chunks_left_in_macrobatch = 0 76 | 77 | def next_macrobatch(self): 78 | curr_idx = 0 79 | self.targets[:] = 0 80 | for idx in range(self.vids_per_macrobatch): 81 | vid_data = self.next_video() 82 | self.chunk_count = self.chunks_per_vid 83 | self.extract_chunks(vid_data, curr_idx, self.current_flag, self.chunks_per_vid) 84 | curr_idx += self.chunks_per_vid 85 | self.chunks_filled += self.chunks_per_vid 86 | self.chunks_left_in_macrobatch = self.macrobatch_size 87 | if self.is_training: 88 | self.shuffle(self.data, self.targets) 89 | 90 | def next_minibatch(self, start): 91 | end = min(start + self.bsz, self.ndata) 92 | if end == self.ndata: 93 | self.start_idx = self.bsz - (self.ndata - start) 94 | 95 | if self.chunks_left_in_macrobatch == 0: 96 | self.next_macrobatch() 97 | self.macrobatch_offset = 0 98 | 99 | start = self.macrobatch_offset 100 | end = start + self.bsz 101 | 102 | self.minibatch_data[:] = self.data[start:end] 103 | self.minibatch_targets[:] = self.targets[start:end] 104 | self.dev_data[:] = self.minibatch_data.T.copy() 105 | self.dev_data[:] = self.dev_data / 255. 106 | self.dev_targets[:] = self.minibatch_targets.T.copy() 107 | self.macrobatch_offset += self.bsz 108 | self.chunks_left_in_macrobatch -= self.bsz 109 | return self.dev_data, self.dev_targets 110 | 111 | def next_video(self): 112 | self.current_meta = self.metadata.iloc[self.video_idx] 113 | uid = self.current_meta['uid'] 114 | self.current_flag = int(self.current_meta['flag']) 115 | data_filename = os.path.join(self.repo_dir, uid + '.' + settings.file_ext) 116 | vid_shape = (int(self.current_meta['z_len']), 117 | int(self.current_meta['y_len']), 118 | int(self.current_meta['x_len'])) 119 | data = video.read_blp(data_filename, vid_shape) 120 | self.video_idx += 1 121 | if self.video_idx == self.nvids: 122 | self.video_idx = 0 123 | return data 124 | 125 | @property 126 | def nbatches(self): 127 | return -((self.start_idx - self.ndata) // self.bsz) 128 | 129 | def __iter__(self): 130 | for start in range(self.start_idx, self.ndata, self.bsz): 131 | yield self.next_minibatch(start) 132 | 133 | def transform(self, vid): 134 | rand1 = np.random.randint(18) 135 | rand2 = np.random.randint(12) 136 | if rand1 == 0: 137 | vid = vid.transpose((0, 2, 1)) 138 | elif rand1 == 1: 139 | vid = vid.transpose((1, 0, 2)) 140 | elif rand1 == 2: 141 | vid = vid.transpose((1, 2, 0)) 142 | elif rand1 == 3: 143 | vid = vid.transpose((2, 0, 1)) 144 | elif rand1 == 4: 145 | vid = vid.transpose((2, 1, 0)) 146 | 147 | if rand2 == 0: 148 | vid = vid[::-1] 149 | elif rand2 == 1: 150 | vid = vid[:, ::-1] 151 | elif rand2 == 2: 152 | vid = vid[:, :, ::-1] 153 | return vid 154 | 155 | def slice_chunk(self, start, data): 156 | return data[start[0]:start[0]+self.chunk_size, 157 | start[1]:start[1]+self.chunk_size, 158 | start[2]:start[2]+self.chunk_size].ravel() 159 | 160 | def extract_one(self, cur_idx, chunk_idx, data, data_shape, flag, uid_data): 161 | assert uid_data.shape[0] != 0 162 | rand = np.random.randint(8) 163 | if flag == 1 or rand > 0: 164 | # Could be a real nodule or a negative sample selected from 165 | # possible candidates 166 | i = np.random.randint(uid_data.shape[0]) 167 | center = np.array((uid_data['z'].iloc[i], 168 | uid_data['y'].iloc[i], 169 | uid_data['x'].iloc[i]), dtype=np.int32) 170 | rad = 0.5 * uid_data['diam'].iloc[i] 171 | if rad == 0: 172 | # Assign an arbitrary radius to candidate nodules 173 | rad = 24 / settings.resolution 174 | low = np.int32(center + rad - self.chunk_size) 175 | high = np.int32(center - rad) 176 | else: 177 | # Let in a random negative sample 178 | low = np.zeros(3, dtype=np.int32) 179 | high = np.int32(low + data_shape - self.chunk_size) 180 | 181 | for j in range(3): 182 | low[j] = max(0, low[j]) 183 | high[j] = max(low[j] + 1, high[j]) 184 | high[j] = min(data_shape[j] - self.chunk_size, high[j]) 185 | low[j] = min(low[j], high[j] - 1) 186 | # Jitter the location of this chunk 187 | start = [np.random.randint(low=low[i], high=high[i]) for i in range(3)] 188 | chunk = self.slice_chunk(start, data) 189 | 190 | if self.current_flag != -1: 191 | self.targets[cur_idx + chunk_idx, self.current_flag] = 1 192 | if self.augment: 193 | self.transform_buffer[:] = chunk.reshape(self.transform_buffer.shape) 194 | self.data[cur_idx + chunk_idx] = self.transform(self.transform_buffer).ravel() 195 | else: 196 | self.data[cur_idx + chunk_idx] = chunk 197 | return True 198 | 199 | def extract_chunks(self, data, cur_idx, flag, count): 200 | assert count <= self.chunk_count 201 | meta = self.current_meta 202 | data_shape = np.array(data.shape, dtype=np.int32) 203 | 204 | uid = meta['uid'] 205 | uid_data = self.labels[self.labels['uid'] == uid] 206 | chunk_idx = 0 207 | while chunk_idx < count: 208 | if self.extract_one(cur_idx, chunk_idx, data, data_shape, flag, uid_data): 209 | chunk_idx += 1 210 | 211 | def shuffle(self, data, targets): 212 | inds = np.arange(self.data.shape[0]) 213 | np.random.shuffle(inds) 214 | data[:] = data[inds] 215 | targets[:] = targets[inds] 216 | -------------------------------------------------------------------------------- /index.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # 3 | # Copyright 2017 Anil Thomas 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | # 17 | """ 18 | Create index files for training and validation subsets 19 | """ 20 | import sys 21 | import os 22 | import numpy as np 23 | import settings 24 | 25 | 26 | def write_meta(data_path, idx_file, meta): 27 | with open(os.path.join(data_path, idx_file), 'w') as fd: 28 | fd.write('uid,flag,z_len,y_len,x_len\n') 29 | for row in meta: 30 | fd.write(','.join(row) + '\n') 31 | 32 | if len(sys.argv) < 3: 33 | print('Usage: %s ' % sys.argv[0]) 34 | sys.exit(0) 35 | 36 | data_path = sys.argv[1] 37 | meta_path = sys.argv[2] 38 | meta_agg = np.loadtxt(meta_path, delimiter=',', skiprows=1, dtype=bytes).astype(str) 39 | 40 | meta = [] 41 | for row in meta_agg: 42 | uid, label = row[0], row[1] 43 | filename = uid + '.' + settings.file_ext 44 | if os.path.exists(os.path.join(data_path, filename)): 45 | meta.append(row) 46 | else: 47 | print('could not find %s' % filename) 48 | 49 | print('%d samples' % len(meta)) 50 | train_len = int(len(meta) * 0.8) 51 | train_meta = meta[:train_len] 52 | val_meta = meta[train_len:] 53 | 54 | write_meta(data_path, 'train-metadata.csv', train_meta) 55 | write_meta(data_path, 'val-metadata.csv', val_meta) 56 | -------------------------------------------------------------------------------- /mask.py: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright 2017 Anil Thomas 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | """ 17 | Segmenting lung CT scans 18 | """ 19 | import os 20 | import numpy as np 21 | import settings 22 | from skimage import measure 23 | from scipy import ndimage 24 | 25 | 26 | def get_mask(image, uid): 27 | mask = np.array(image > -320, dtype=np.int8) 28 | # Set the edges to zeros. This is to connect the air regions, which 29 | # may appear separated in some scans 30 | mask[:, 0] = 0 31 | mask[:, -1] = 0 32 | mask[:, :, 0] = 0 33 | mask[:, :, -1] = 0 34 | labels = measure.label(mask, connectivity=1, background=-1) 35 | vals, counts = np.unique(labels, return_counts=True) 36 | inds = np.argsort(counts) 37 | # Assume that the lungs make up the third largest region 38 | lung_val = vals[inds][-3] 39 | if mask[labels == lung_val].sum() != 0: 40 | print('Warning: could not get mask for %s' % uid) 41 | mask[:] = 1 42 | return mask 43 | 44 | mask[labels == lung_val] = 1 45 | mask[labels != lung_val] = 0 46 | fill_mask(mask) 47 | left_center = mask[mask.shape[0] // 2, mask.shape[1] // 2, mask.shape[2] // 4] 48 | right_center = mask[mask.shape[0] // 2, mask.shape[1] // 2, mask.shape[2] * 3 // 4] 49 | if (left_center == 0) or (right_center == 0): 50 | print('Warning: could not get mask for %s' % uid) 51 | mask[:] = 1 52 | return mask 53 | 54 | mask = ndimage.morphology.binary_dilation(mask, iterations=settings.mask_dilation) 55 | return mask 56 | 57 | 58 | def apply_mask(image, mask): 59 | image[mask == 0] = 0 60 | 61 | 62 | def fill_mask(mask): 63 | for i in range(mask.shape[0]): 64 | slc = mask[i] 65 | fill_mask_slice(slc) 66 | for i in range(mask.shape[1]): 67 | slc = mask[:, i] 68 | fill_mask_slice(slc) 69 | for i in range(mask.shape[2]): 70 | slc = mask[:, :, i] 71 | fill_mask_slice(slc) 72 | 73 | 74 | def fill_mask_slice(slc): 75 | labels = measure.label(slc, connectivity=1, background=-1) 76 | vals, counts = np.unique(labels, return_counts=True) 77 | inds = np.argsort(counts) 78 | max_val = vals[inds][-1] 79 | if len(vals) > 1: 80 | next_val = vals[inds][-2] 81 | labels[labels == next_val] = max_val 82 | slc[labels != max_val] = 1 83 | -------------------------------------------------------------------------------- /run.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # 3 | # Copyright 2017 Anil Thomas 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | # 17 | """ 18 | Train and validate a model 19 | 20 | Usage: 21 | ./run.py -w -e 8 -r 0 22 | """ 23 | import os 24 | import numpy as np 25 | from neon import logger as neon_logger 26 | from neon.layers import GeneralizedCost 27 | from neon.optimizers import Adadelta 28 | from neon.transforms import LogLoss, CrossEntropyBinary 29 | from neon.callbacks.callbacks import Callbacks 30 | from neon.util.argparser import NeonArgparser 31 | from neon.initializers import Kaiming 32 | from neon.layers import Conv, Dropout, Pooling, Affine 33 | from neon.transforms import Rectlin, Softmax 34 | from neon.models import Model 35 | from data import ChunkLoader 36 | import settings 37 | import video 38 | 39 | 40 | def create_network(): 41 | init = Kaiming() 42 | padding = dict(pad_d=1, pad_h=1, pad_w=1) 43 | strides = dict(str_d=2, str_h=2, str_w=2) 44 | dilation = dict(dil_d=2, dil_h=2, dil_w=2) 45 | common = dict(init=init, batch_norm=True, activation=Rectlin()) 46 | layers = [ 47 | Conv((9, 9, 9, 16), padding=padding, strides=strides, init=init, activation=Rectlin()), 48 | Conv((5, 5, 5, 32), dilation=dilation, **common), 49 | Conv((3, 3, 3, 64), dilation=dilation, **common), 50 | Pooling((2, 2, 2), padding=padding, strides=strides), 51 | Conv((2, 2, 2, 128), **common), 52 | Conv((2, 2, 2, 128), **common), 53 | Conv((2, 2, 2, 128), **common), 54 | Conv((2, 2, 2, 256), **common), 55 | Conv((2, 2, 2, 1024), **common), 56 | Conv((2, 2, 2, 4096), **common), 57 | Conv((2, 2, 2, 2048), **common), 58 | Conv((2, 2, 2, 1024), **common), 59 | Dropout(), 60 | Affine(2, init=Kaiming(local=False), batch_norm=True, activation=Softmax()) 61 | ] 62 | return Model(layers=layers) 63 | 64 | 65 | # Parse the command line arguments 66 | parser = NeonArgparser(__doc__) 67 | parser.add_argument('-tm', '--test_mode', action='store_true', 68 | help='make predictions on test data') 69 | args = parser.parse_args() 70 | 71 | # Create model 72 | model = create_network() 73 | 74 | # Setup data provider 75 | repo_dir = args.data_dir 76 | common = dict(datum_dtype=np.uint8, repo_dir=repo_dir, test_mode=args.test_mode) 77 | train = ChunkLoader(set_name='train', augment=not args.test_mode, **common) 78 | test = ChunkLoader(set_name='val', augment=False, **common) 79 | 80 | if args.test_mode: 81 | assert args.model_file is not None 82 | model.load_params(args.model_file) 83 | 84 | for dataset in [train, test]: 85 | pred = model.get_outputs(dataset) 86 | np.save(os.path.join(repo_dir, dataset.set_name + '-pred.npy'), pred[:, 1]) 87 | else: 88 | # Setup callbacks 89 | callbacks = Callbacks(model, eval_set=test, **args.callback_args) 90 | 91 | # Train model 92 | opt = Adadelta() 93 | cost = GeneralizedCost(costfunc=CrossEntropyBinary()) 94 | model.fit(train, optimizer=opt, num_epochs=args.epochs, cost=cost, callbacks=callbacks) 95 | 96 | # Output metrics 97 | neon_logger.display('Test Logloss = %.4f' % (model.eval(test, metric=LogLoss()))) 98 | -------------------------------------------------------------------------------- /settings.py: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright 2017 Anil Thomas 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | """ 17 | Configuration settings 18 | """ 19 | chunk_size = 64 20 | low_thresh = -1100 21 | high_thresh = 500 22 | mask_dilation = 4 23 | resolution = 1.0 24 | file_ext = 'blp' 25 | -------------------------------------------------------------------------------- /video.py: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright 2017 Anil Thomas 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | """ 17 | Video related utility functions 18 | """ 19 | 20 | import numpy as np 21 | import settings 22 | import blosc 23 | 24 | 25 | def write_blp(data, file_name): 26 | file_name += '.blp' 27 | print('Saving %s' % file_name) 28 | bytes_array = data.tostring() 29 | packed = blosc.compress(bytes_array) 30 | with open(file_name, 'wb') as fd: 31 | fd.write(packed) 32 | 33 | 34 | def read_blp(file_name, shape): 35 | with open(file_name, 'rb') as fd: 36 | bytes_array = fd.read() 37 | unpacked = blosc.decompress(bytes_array) 38 | return np.frombuffer(unpacked, dtype=np.uint8).reshape((shape)) 39 | 40 | 41 | def write_data(vid, file_name): 42 | write_blp(vid, file_name) 43 | 44 | 45 | def clip(image, min_bound, max_bound): 46 | image[image > max_bound] = max_bound 47 | image[image < min_bound] = min_bound 48 | 49 | 50 | def normalize(image, min_bound, max_bound): 51 | image = np.float32(image) 52 | image = (image - min_bound) / (max_bound - min_bound) 53 | assert image[image > 1].sum() == 0 54 | assert image[image < 0].sum() == 0 55 | image *= 255 56 | return np.uint8(np.rint(image)) 57 | 58 | 59 | def copy_to_frame(video, frame_shape): 60 | in_shape = video.shape 61 | out_shape = frame_shape 62 | frame = np.zeros(out_shape, dtype=video.dtype) 63 | for idx in range(3): 64 | assert in_shape[idx] <= out_shape[idx] 65 | starts = [(out_shape[i] - in_shape[i]) // 2 for i in range(3)] 66 | ends = [starts[i] + in_shape[i] for i in range(3)] 67 | frame[starts[0]:ends[0], starts[1]:ends[1], starts[2]:ends[2]] = video 68 | return frame 69 | -------------------------------------------------------------------------------- /visuals/train-chunk-0.avi: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anlthms/dsb-2017/0ba41971434381c15aa7e123ee2f706be785bd55/visuals/train-chunk-0.avi -------------------------------------------------------------------------------- /visuals/train-chunk-0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anlthms/dsb-2017/0ba41971434381c15aa7e123ee2f706be785bd55/visuals/train-chunk-0.png -------------------------------------------------------------------------------- /visuals/train-chunk-1.avi: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anlthms/dsb-2017/0ba41971434381c15aa7e123ee2f706be785bd55/visuals/train-chunk-1.avi -------------------------------------------------------------------------------- /visuals/train-chunk-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anlthms/dsb-2017/0ba41971434381c15aa7e123ee2f706be785bd55/visuals/train-chunk-1.png -------------------------------------------------------------------------------- /visuals/train-chunk-2.avi: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anlthms/dsb-2017/0ba41971434381c15aa7e123ee2f706be785bd55/visuals/train-chunk-2.avi -------------------------------------------------------------------------------- /visuals/train-chunk-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anlthms/dsb-2017/0ba41971434381c15aa7e123ee2f706be785bd55/visuals/train-chunk-2.png -------------------------------------------------------------------------------- /visuals/train-chunk-3.avi: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anlthms/dsb-2017/0ba41971434381c15aa7e123ee2f706be785bd55/visuals/train-chunk-3.avi -------------------------------------------------------------------------------- /visuals/train-chunk-3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anlthms/dsb-2017/0ba41971434381c15aa7e123ee2f706be785bd55/visuals/train-chunk-3.png -------------------------------------------------------------------------------- /visuals/train-chunk-4.avi: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anlthms/dsb-2017/0ba41971434381c15aa7e123ee2f706be785bd55/visuals/train-chunk-4.avi -------------------------------------------------------------------------------- /visuals/train-chunk-4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anlthms/dsb-2017/0ba41971434381c15aa7e123ee2f706be785bd55/visuals/train-chunk-4.png -------------------------------------------------------------------------------- /visuals/train-chunk-5.avi: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anlthms/dsb-2017/0ba41971434381c15aa7e123ee2f706be785bd55/visuals/train-chunk-5.avi -------------------------------------------------------------------------------- /visuals/train-chunk-5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anlthms/dsb-2017/0ba41971434381c15aa7e123ee2f706be785bd55/visuals/train-chunk-5.png -------------------------------------------------------------------------------- /visuals/train-chunk-6.avi: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anlthms/dsb-2017/0ba41971434381c15aa7e123ee2f706be785bd55/visuals/train-chunk-6.avi -------------------------------------------------------------------------------- /visuals/train-chunk-6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anlthms/dsb-2017/0ba41971434381c15aa7e123ee2f706be785bd55/visuals/train-chunk-6.png -------------------------------------------------------------------------------- /visuals/train-chunk-7.avi: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anlthms/dsb-2017/0ba41971434381c15aa7e123ee2f706be785bd55/visuals/train-chunk-7.avi -------------------------------------------------------------------------------- /visuals/train-chunk-7.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anlthms/dsb-2017/0ba41971434381c15aa7e123ee2f706be785bd55/visuals/train-chunk-7.png -------------------------------------------------------------------------------- /visuals/train-vid.avi: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anlthms/dsb-2017/0ba41971434381c15aa7e123ee2f706be785bd55/visuals/train-vid.avi -------------------------------------------------------------------------------- /visuals/train-vid.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anlthms/dsb-2017/0ba41971434381c15aa7e123ee2f706be785bd55/visuals/train-vid.png --------------------------------------------------------------------------------