├── LICENSE
├── README.md
├── brain-tumor-segmentation
└── README.md
├── figures
└── unetr_architecture.png
├── metrics.py
├── results
├── 114.png
├── 124.png
├── 132.png
├── 135.png
├── 2.png
├── 21.png
├── 23.png
├── 26.png
├── 58.png
├── 6.png
├── 60.png
├── 68.png
├── 71.png
├── 75.png
├── 77.png
├── 85.png
├── 86.png
├── 9.png
├── 92.png
└── README.md
├── test.py
├── train.py
└── unetr_2d.py
/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 | # Brain-Tumor-Segmentation-using-UNETR-in-TensorFlow
2 | This repository demonstrates the utilization of UNETR for brain tumor segmentation.
3 |
4 | ## Architecture
5 |
6 | |  |
7 | | :--: |
8 | | *The block diagram of the Original UNETR model.* |
9 |
10 | ## Dataset
11 | The dataset contains 3064 pairs of MRI brain images and their respective binary mask indicating tumor.
12 |
13 | Download the dataset: [Brain Tumor Segmentation](https://www.kaggle.com/datasets/nikhilroxtomar/brain-tumor-segmentation)
14 |
15 | Original Dataset: [Brain Tumor Segmentation](https://figshare.com/articles/dataset/brain_tumor_dataset/1512427)
16 |
17 | ## Results
18 | The sequence in the images below is `Input Image`, `Ground Truth` and `Prediction`.
19 | |  |
20 | | :--: |
21 | |  |
22 | |  |
23 | |  |
24 | |  |
25 |
26 | ## How to improve
27 | - Train on more epochs.
28 | - Increase the input image resolution.
29 | - Apply data augmentation.
30 |
31 |
32 | ## Contact
33 | For more follow me on:
34 |
35 | - YouTube
36 | - Facebook
37 | - Twitter
38 | - Instagram
39 | - Telegram
40 |
--------------------------------------------------------------------------------
/brain-tumor-segmentation/README.md:
--------------------------------------------------------------------------------
1 | # Dataset
2 |
--------------------------------------------------------------------------------
/figures/unetr_architecture.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nikhilroxtomar/Brain-Tumor-Segmentation-using-UNETR-in-TensorFlow/d3752891c438f8961bf1c680d4b431133f6cf586/figures/unetr_architecture.png
--------------------------------------------------------------------------------
/metrics.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import tensorflow as tf
3 |
4 | smooth = 1e-15
5 | def dice_coef(y_true, y_pred):
6 | y_true = tf.keras.layers.Flatten()(y_true)
7 | y_pred = tf.keras.layers.Flatten()(y_pred)
8 | intersection = tf.reduce_sum(y_true * y_pred)
9 | return (2. * intersection + smooth) / (tf.reduce_sum(y_true) + tf.reduce_sum(y_pred) + smooth)
10 |
11 | def dice_loss(y_true, y_pred):
12 | return 1.0 - dice_coef(y_true, y_pred)
13 |
--------------------------------------------------------------------------------
/results/114.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nikhilroxtomar/Brain-Tumor-Segmentation-using-UNETR-in-TensorFlow/d3752891c438f8961bf1c680d4b431133f6cf586/results/114.png
--------------------------------------------------------------------------------
/results/124.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nikhilroxtomar/Brain-Tumor-Segmentation-using-UNETR-in-TensorFlow/d3752891c438f8961bf1c680d4b431133f6cf586/results/124.png
--------------------------------------------------------------------------------
/results/132.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nikhilroxtomar/Brain-Tumor-Segmentation-using-UNETR-in-TensorFlow/d3752891c438f8961bf1c680d4b431133f6cf586/results/132.png
--------------------------------------------------------------------------------
/results/135.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nikhilroxtomar/Brain-Tumor-Segmentation-using-UNETR-in-TensorFlow/d3752891c438f8961bf1c680d4b431133f6cf586/results/135.png
--------------------------------------------------------------------------------
/results/2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nikhilroxtomar/Brain-Tumor-Segmentation-using-UNETR-in-TensorFlow/d3752891c438f8961bf1c680d4b431133f6cf586/results/2.png
--------------------------------------------------------------------------------
/results/21.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nikhilroxtomar/Brain-Tumor-Segmentation-using-UNETR-in-TensorFlow/d3752891c438f8961bf1c680d4b431133f6cf586/results/21.png
--------------------------------------------------------------------------------
/results/23.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nikhilroxtomar/Brain-Tumor-Segmentation-using-UNETR-in-TensorFlow/d3752891c438f8961bf1c680d4b431133f6cf586/results/23.png
--------------------------------------------------------------------------------
/results/26.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nikhilroxtomar/Brain-Tumor-Segmentation-using-UNETR-in-TensorFlow/d3752891c438f8961bf1c680d4b431133f6cf586/results/26.png
--------------------------------------------------------------------------------
/results/58.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nikhilroxtomar/Brain-Tumor-Segmentation-using-UNETR-in-TensorFlow/d3752891c438f8961bf1c680d4b431133f6cf586/results/58.png
--------------------------------------------------------------------------------
/results/6.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nikhilroxtomar/Brain-Tumor-Segmentation-using-UNETR-in-TensorFlow/d3752891c438f8961bf1c680d4b431133f6cf586/results/6.png
--------------------------------------------------------------------------------
/results/60.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nikhilroxtomar/Brain-Tumor-Segmentation-using-UNETR-in-TensorFlow/d3752891c438f8961bf1c680d4b431133f6cf586/results/60.png
--------------------------------------------------------------------------------
/results/68.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nikhilroxtomar/Brain-Tumor-Segmentation-using-UNETR-in-TensorFlow/d3752891c438f8961bf1c680d4b431133f6cf586/results/68.png
--------------------------------------------------------------------------------
/results/71.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nikhilroxtomar/Brain-Tumor-Segmentation-using-UNETR-in-TensorFlow/d3752891c438f8961bf1c680d4b431133f6cf586/results/71.png
--------------------------------------------------------------------------------
/results/75.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nikhilroxtomar/Brain-Tumor-Segmentation-using-UNETR-in-TensorFlow/d3752891c438f8961bf1c680d4b431133f6cf586/results/75.png
--------------------------------------------------------------------------------
/results/77.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nikhilroxtomar/Brain-Tumor-Segmentation-using-UNETR-in-TensorFlow/d3752891c438f8961bf1c680d4b431133f6cf586/results/77.png
--------------------------------------------------------------------------------
/results/85.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nikhilroxtomar/Brain-Tumor-Segmentation-using-UNETR-in-TensorFlow/d3752891c438f8961bf1c680d4b431133f6cf586/results/85.png
--------------------------------------------------------------------------------
/results/86.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nikhilroxtomar/Brain-Tumor-Segmentation-using-UNETR-in-TensorFlow/d3752891c438f8961bf1c680d4b431133f6cf586/results/86.png
--------------------------------------------------------------------------------
/results/9.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nikhilroxtomar/Brain-Tumor-Segmentation-using-UNETR-in-TensorFlow/d3752891c438f8961bf1c680d4b431133f6cf586/results/9.png
--------------------------------------------------------------------------------
/results/92.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nikhilroxtomar/Brain-Tumor-Segmentation-using-UNETR-in-TensorFlow/d3752891c438f8961bf1c680d4b431133f6cf586/results/92.png
--------------------------------------------------------------------------------
/results/README.md:
--------------------------------------------------------------------------------
1 | # Results
2 |
--------------------------------------------------------------------------------
/test.py:
--------------------------------------------------------------------------------
1 | import os
2 | os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
3 |
4 | import numpy as np
5 | import cv2
6 | from tqdm import tqdm
7 | import tensorflow as tf
8 | from patchify import patchify
9 | from train import load_dataset, create_dir
10 | from metrics import dice_loss, dice_coef
11 |
12 |
13 | """ UNETR Configration """
14 | cf = {}
15 | cf["image_size"] = 256
16 | cf["num_channels"] = 3
17 | cf["num_layers"] = 12
18 | cf["hidden_dim"] = 128
19 | cf["mlp_dim"] = 32
20 | cf["num_heads"] = 6
21 | cf["dropout_rate"] = 0.1
22 | cf["patch_size"] = 16
23 | cf["num_patches"] = (cf["image_size"]**2)//(cf["patch_size"]**2)
24 | cf["flat_patches_shape"] = (
25 | cf["num_patches"],
26 | cf["patch_size"]*cf["patch_size"]*cf["num_channels"]
27 | )
28 |
29 |
30 | if __name__ == "__main__":
31 | """ Seeding """
32 | np.random.seed(42)
33 | tf.random.set_seed(42)
34 |
35 | """ Directory for storing files """
36 | create_dir(f"results")
37 |
38 | """ Load the model """
39 | model_path = os.path.join("files", "model.h5")
40 | model = tf.keras.models.load_model(model_path, custom_objects={"dice_loss": dice_loss, "dice_coef": dice_coef})
41 |
42 | """ Dataset """
43 | dataset_path = "brain-tumor-segmentation"
44 | (train_x, train_y), (valid_x, valid_y), (test_x, test_y) = load_dataset(dataset_path)
45 |
46 | print(f"Train: \t{len(train_x)} - {len(train_y)}")
47 | print(f"Valid: \t{len(valid_x)} - {len(valid_y)}")
48 | print(f"Test: \t{len(test_x)} - {len(test_y)}")
49 |
50 | """ Prediction """
51 | for x, y in tqdm(zip(test_x, test_y), total=len(test_x)):
52 | """ Extracting the name """
53 | name = x.split("/")[-1]
54 |
55 | """ Reading the image """
56 | image = cv2.imread(x, cv2.IMREAD_COLOR)
57 | image = cv2.resize(image, (cf["image_size"], cf["image_size"]))
58 | x = image / 255.0
59 |
60 | patch_shape = (cf["patch_size"], cf["patch_size"], cf["num_channels"])
61 | patches = patchify(x, patch_shape, cf["patch_size"])
62 | patches = np.reshape(patches, cf["flat_patches_shape"])
63 | patches = patches.astype(np.float32)
64 | patches = np.expand_dims(patches, axis=0)
65 |
66 | """ Read Mask """
67 | mask = cv2.imread(y, cv2.IMREAD_GRAYSCALE)
68 | mask = cv2.resize(mask, (cf["image_size"], cf["image_size"]))
69 | mask = mask / 255.0
70 | mask = np.expand_dims(mask, axis=-1)
71 | mask = np.concatenate([mask, mask, mask], axis=-1)
72 |
73 | """ Prediction """
74 | pred = model.predict(patches, verbose=0)[0]
75 | pred = np.concatenate([pred, pred, pred], axis=-1)
76 |
77 | """ Save final mask """
78 | line = np.ones((cf["image_size"], 10, 3)) * 255
79 | cat_images = np.concatenate([image, line, mask*255, line, pred*255], axis=1)
80 | save_image_path = os.path.join("results", name)
81 | cv2.imwrite(save_image_path, cat_images)
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 | ## ...
93 |
--------------------------------------------------------------------------------
/train.py:
--------------------------------------------------------------------------------
1 | import os
2 | os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
3 |
4 | import numpy as np
5 | import cv2
6 | from glob import glob
7 | from sklearn.utils import shuffle
8 | import tensorflow as tf
9 | from tensorflow.keras.callbacks import ModelCheckpoint, CSVLogger, ReduceLROnPlateau, EarlyStopping
10 | from tensorflow.keras.optimizers import Adam, SGD
11 | from sklearn.model_selection import train_test_split
12 | from patchify import patchify
13 | from unetr_2d import build_unetr_2d
14 | from metrics import dice_loss, dice_coef
15 |
16 |
17 | """ UNETR Configration """
18 | cf = {}
19 | cf["image_size"] = 256
20 | cf["num_channels"] = 3
21 | cf["num_layers"] = 12
22 | cf["hidden_dim"] = 128
23 | cf["mlp_dim"] = 32
24 | cf["num_heads"] = 6
25 | cf["dropout_rate"] = 0.1
26 | cf["patch_size"] = 16
27 | cf["num_patches"] = (cf["image_size"]**2)//(cf["patch_size"]**2)
28 | cf["flat_patches_shape"] = (
29 | cf["num_patches"],
30 | cf["patch_size"]*cf["patch_size"]*cf["num_channels"]
31 | )
32 |
33 | def create_dir(path):
34 | if not os.path.exists(path):
35 | os.makedirs(path)
36 |
37 | def load_dataset(path, split=0.1):
38 | """ Loading the images and masks """
39 | X = sorted(glob(os.path.join(path, "images", "*.png")))
40 | Y = sorted(glob(os.path.join(path, "masks", "*.png")))
41 |
42 | """ Spliting the data into training and testing """
43 | split_size = int(len(X) * split)
44 |
45 | train_x, valid_x = train_test_split(X, test_size=split_size, random_state=42)
46 | train_y, valid_y = train_test_split(Y, test_size=split_size, random_state=42)
47 |
48 | train_x, test_x = train_test_split(train_x, test_size=split_size, random_state=42)
49 | train_y, test_y = train_test_split(train_y, test_size=split_size, random_state=42)
50 |
51 | return (train_x, train_y), (valid_x, valid_y), (test_x, test_y)
52 |
53 | def read_image(path):
54 | path = path.decode()
55 | image = cv2.imread(path, cv2.IMREAD_COLOR)
56 | image = cv2.resize(image, (cf["image_size"], cf["image_size"]))
57 | image = image / 255.0
58 |
59 | """ Processing to patches """
60 | patch_shape = (cf["patch_size"], cf["patch_size"], cf["num_channels"])
61 | patches = patchify(image, patch_shape, cf["patch_size"])
62 | patches = np.reshape(patches, cf["flat_patches_shape"])
63 | patches = patches.astype(np.float32)
64 |
65 | return patches
66 |
67 | def read_mask(path):
68 | path = path.decode()
69 | mask = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
70 | mask = cv2.resize(mask, (cf["image_size"], cf["image_size"]))
71 | mask = mask / 255.0
72 | mask = mask.astype(np.float32)
73 | mask = np.expand_dims(mask, axis=-1)
74 | return mask
75 |
76 | def tf_parse(x, y):
77 | def _parse(x, y):
78 | x = read_image(x)
79 | y = read_mask(y)
80 | return x, y
81 |
82 | x, y = tf.numpy_function(_parse, [x, y], [tf.float32, tf.float32])
83 | x.set_shape(cf["flat_patches_shape"])
84 | y.set_shape([cf["image_size"], cf["image_size"], 1])
85 | return x, y
86 |
87 | def tf_dataset(X, Y, batch=2):
88 | ds = tf.data.Dataset.from_tensor_slices((X, Y))
89 | ds = ds.map(tf_parse).batch(batch).prefetch(10)
90 | return ds
91 |
92 |
93 | if __name__ == "__main__":
94 | """ Seeding """
95 | np.random.seed(42)
96 | tf.random.set_seed(42)
97 |
98 | """ Directory for storing files """
99 | create_dir("files")
100 |
101 | """ Hyperparameters """
102 | batch_size = 8
103 | lr = 0.1
104 | num_epochs = 500
105 | model_path = os.path.join("files", "model.h5")
106 | csv_path = os.path.join("files", "log.csv")
107 |
108 | """ Dataset """
109 | dataset_path = "brain-tumor-segmentation"
110 | (train_x, train_y), (valid_x, valid_y), (test_x, test_y) = load_dataset(dataset_path)
111 |
112 | print(f"Train: \t{len(train_x)} - {len(train_y)}")
113 | print(f"Valid: \t{len(valid_x)} - {len(valid_y)}")
114 | print(f"Test: \t{len(test_x)} - {len(test_y)}")
115 |
116 | train_dataset = tf_dataset(train_x, train_y, batch=batch_size)
117 | valid_dataset = tf_dataset(valid_x, valid_y, batch=batch_size)
118 |
119 | """ Model """
120 | model = build_unetr_2d(cf)
121 | model.compile(loss=dice_loss, optimizer=SGD(lr), metrics=[dice_coef, "acc"])
122 | # model.summary()
123 |
124 | callbacks = [
125 | ModelCheckpoint(model_path, verbose=1, save_best_only=True),
126 | ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=5, min_lr=1e-7, verbose=1),
127 | CSVLogger(csv_path),
128 | EarlyStopping(monitor='val_loss', patience=20, restore_best_weights=False)
129 | ]
130 |
131 | model.fit(
132 | train_dataset,
133 | epochs=num_epochs,
134 | validation_data=valid_dataset,
135 | callbacks=callbacks
136 | )
137 |
--------------------------------------------------------------------------------
/unetr_2d.py:
--------------------------------------------------------------------------------
1 |
2 | import os
3 | os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
4 |
5 | from math import log2
6 | import tensorflow as tf
7 | import tensorflow.keras.layers as L
8 | from tensorflow.keras.models import Model
9 |
10 | def mlp(x, cf):
11 | x = L.Dense(cf["mlp_dim"], activation="gelu")(x)
12 | x = L.Dropout(cf["dropout_rate"])(x)
13 | x = L.Dense(cf["hidden_dim"])(x)
14 | x = L.Dropout(cf["dropout_rate"])(x)
15 | return x
16 |
17 | def transformer_encoder(x, cf):
18 | skip_1 = x
19 | x = L.LayerNormalization()(x)
20 | x = L.MultiHeadAttention(
21 | num_heads=cf["num_heads"], key_dim=cf["hidden_dim"]
22 | )(x, x)
23 | x = L.Add()([x, skip_1])
24 |
25 | skip_2 = x
26 | x = L.LayerNormalization()(x)
27 | x = mlp(x, cf)
28 | x = L.Add()([x, skip_2])
29 |
30 | return x
31 |
32 | def conv_block(x, num_filters, kernel_size=3):
33 | x = L.Conv2D(num_filters, kernel_size=kernel_size, padding="same")(x)
34 | x = L.BatchNormalization()(x)
35 | x = L.ReLU()(x)
36 | return x
37 |
38 | def deconv_block(x, num_filters, strides=2):
39 | x = L.Conv2DTranspose(num_filters, kernel_size=2, padding="same", strides=strides)(x)
40 | return x
41 |
42 | def build_unetr_2d(cf):
43 | """ Inputs """
44 | input_shape = (cf["num_patches"], cf["patch_size"]*cf["patch_size"]*cf["num_channels"])
45 | inputs = L.Input(input_shape) ## (None, 256, 3072)
46 |
47 | """ Patch + Position Embeddings """
48 | patch_embed = L.Dense(cf["hidden_dim"])(inputs) ## (None, 256, 768)
49 |
50 | positions = tf.range(start=0, limit=cf["num_patches"], delta=1) ## (256,)
51 | pos_embed = L.Embedding(input_dim=cf["num_patches"], output_dim=cf["hidden_dim"])(positions) ## (256, 768)
52 | x = patch_embed + pos_embed ## (None, 256, 768)
53 |
54 | """ Transformer Encoder """
55 | skip_connection_index = [3, 6, 9, 12]
56 | skip_connections = []
57 |
58 | for i in range(1, cf["num_layers"]+1, 1):
59 | x = transformer_encoder(x, cf)
60 |
61 | if i in skip_connection_index:
62 | skip_connections.append(x)
63 |
64 | """ CNN Decoder """
65 | z3, z6, z9, z12 = skip_connections
66 |
67 | ## Reshaping
68 | z0 = L.Reshape((cf["image_size"], cf["image_size"], cf["num_channels"]))(inputs)
69 |
70 | shape = (
71 | cf["image_size"]//cf["patch_size"],
72 | cf["image_size"]//cf["patch_size"],
73 | cf["hidden_dim"]
74 | )
75 | z3 = L.Reshape(shape)(z3)
76 | z6 = L.Reshape(shape)(z6)
77 | z9 = L.Reshape(shape)(z9)
78 | z12 = L.Reshape(shape)(z12)
79 |
80 | ## Additional layers for managing different patch sizes
81 | total_upscale_factor = int(log2(cf["patch_size"]))
82 | upscale = total_upscale_factor - 4
83 |
84 | if upscale >= 2: ## Patch size 16 or greater
85 | z3 = deconv_block(z3, z3.shape[-1], strides=2**upscale)
86 | z6 = deconv_block(z6, z6.shape[-1], strides=2**upscale)
87 | z9 = deconv_block(z9, z9.shape[-1], strides=2**upscale)
88 | z12 = deconv_block(z12, z12.shape[-1], strides=2**upscale)
89 | # print(z3.shape, z6.shape, z9.shape, z12.shape)
90 |
91 | if upscale < 0: ## Patch size less than 16
92 | p = 2**abs(upscale)
93 | z3 = L.MaxPool2D((p, p))(z3)
94 | z6 = L.MaxPool2D((p, p))(z6)
95 | z9 = L.MaxPool2D((p, p))(z9)
96 | z12 = L.MaxPool2D((p, p))(z12)
97 |
98 | ## Decoder 1
99 | x = deconv_block(z12, 128)
100 |
101 | s = deconv_block(z9, 128)
102 | s = conv_block(s, 128)
103 |
104 | x = L.Concatenate()([x, s])
105 |
106 | x = conv_block(x, 128)
107 | x = conv_block(x, 128)
108 |
109 | ## Decoder 2
110 | x = deconv_block(x, 64)
111 |
112 | s = deconv_block(z6, 64)
113 | s = conv_block(s, 64)
114 | s = deconv_block(s, 64)
115 | s = conv_block(s, 64)
116 |
117 | x = L.Concatenate()([x, s])
118 | x = conv_block(x, 64)
119 | x = conv_block(x, 64)
120 |
121 | ## Decoder 3
122 | x = deconv_block(x, 32)
123 |
124 | s = deconv_block(z3, 32)
125 | s = conv_block(s, 32)
126 | s = deconv_block(s, 32)
127 | s = conv_block(s, 32)
128 | s = deconv_block(s, 32)
129 | s = conv_block(s, 32)
130 |
131 | x = L.Concatenate()([x, s])
132 | x = conv_block(x, 32)
133 | x = conv_block(x, 32)
134 |
135 | ## Decoder 4
136 | x = deconv_block(x, 16)
137 |
138 | s = conv_block(z0, 16)
139 | s = conv_block(s, 16)
140 |
141 | x = L.Concatenate()([x, s])
142 | x = conv_block(x, 16)
143 | x = conv_block(x, 16)
144 |
145 | """ Output """
146 | outputs = L.Conv2D(1, kernel_size=1, padding="same", activation="sigmoid")(x)
147 |
148 | return Model(inputs, outputs, name="UNETR_2D")
149 |
150 | if __name__ == "__main__":
151 | config = {}
152 | config["image_size"] = 512
153 | config["num_layers"] = 12
154 | config["hidden_dim"] = 64
155 | config["mlp_dim"] = 128
156 | config["num_heads"] = 6
157 | config["dropout_rate"] = 0.1
158 | config["patch_size"] = 1
159 | config["num_patches"] = (config["image_size"]**2)//(config["patch_size"]**2)
160 | config["num_channels"] = 3
161 |
162 | model = build_unetr_2d(config)
163 | model.summary()
164 |
--------------------------------------------------------------------------------