Javier Pérez de Frutos commited on
Commit
a03ac95
·
unverified ·
2 Parent(s): f9e0075 c292437

Merge pull request #19 from jpdefrutos/clean_repo

Browse files
DeepDeformationMapRegistration/main.py ADDED
@@ -0,0 +1,418 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+ import os, sys
3
+ import shutil
4
+ import re
5
+ import argparse
6
+ import subprocess
7
+ import logging
8
+ import time
9
+ import warnings
10
+
11
+ # currentdir = os.path.dirname(os.path.realpath(__file__))
12
+ # parentdir = os.path.dirname(currentdir)
13
+ # sys.path.append(parentdir) # PYTHON > 3.3 does not allow relative referencing
14
+
15
+ import tensorflow as tf
16
+
17
+ import numpy as np
18
+ import nibabel as nib
19
+ from scipy.ndimage import gaussian_filter, zoom
20
+ from skimage.measure import regionprops
21
+ import SimpleITK as sitk
22
+
23
+ import voxelmorph as vxm
24
+ from voxelmorph.tf.layers import SpatialTransformer
25
+
26
+ import DeepDeformationMapRegistration.utils.constants as C
27
+ from DeepDeformationMapRegistration.utils.nifti_utils import save_nifti
28
+ from DeepDeformationMapRegistration.losses import StructuralSimilarity_simplified, NCC
29
+ from DeepDeformationMapRegistration.ms_ssim_tf import MultiScaleStructuralSimilarity
30
+ from DeepDeformationMapRegistration.utils.operators import min_max_norm
31
+ from DeepDeformationMapRegistration.utils.misc import resize_displacement_map
32
+ from DeepDeformationMapRegistration.utils.model_utils import get_models_path, load_model
33
+ from DeepDeformationMapRegistration.utils.logger import LOGGER
34
+
35
+ from importlib.util import find_spec
36
+
37
+
38
+ def rigidly_align_images(image_1: str, image_2: str) -> nib.Nifti1Image:
39
+ """
40
+ Rigidly align the images and resample to the same array size, to the dense displacement map is correct
41
+
42
+ """
43
+ def resample_to_isotropic(image: sitk.Image) -> sitk.Image:
44
+ spacing = image.GetSpacing()
45
+ spacing = min(spacing)
46
+ resamp_spacing = [spacing] * image.GetDimension()
47
+ resamp_size = [int(round(or_size*or_space/spacing)) for or_size, or_space in zip(image.GetSize(), image.GetSpacing())]
48
+ return sitk.Resample(image,
49
+ resamp_size, sitk.Transform(), sitk.sitkLinear,image.GetOrigin(),
50
+ resamp_spacing, image.GetDirection(), 0, image.GetPixelID())
51
+
52
+ image_1 = sitk.ReadImage(image_1, sitk.sitkFloat32)
53
+ image_2 = sitk.ReadImage(image_2, sitk.sitkFloat32)
54
+
55
+ image_1 = resample_to_isotropic(image_1)
56
+ image_2 = resample_to_isotropic(image_2)
57
+
58
+ rig_reg = sitk.ImageRegistrationMethod()
59
+ rig_reg.SetMetricAsMeanSquares()
60
+ rig_reg.SetOptimizerAsRegularStepGradientDescent(4.0, 0.01, 200)
61
+ rig_reg.SetInitialTransform(sitk.TranslationTransform(image_1.GetDimension()))
62
+ rig_reg.SetInterpolator(sitk.sitkLinear)
63
+
64
+ print('Running rigid registration...')
65
+ rig_reg_trf = rig_reg.Execute(image_1, image_2)
66
+ print('Rigid registration completed\n----------------------------')
67
+ print('Optimizer stop condition: {}'.format(rig_reg.GetOptimizerStopConditionDescription()))
68
+ print('Iteration: {}'.format(rig_reg.GetOptimizerIteration()))
69
+ print('Metric value: {}'.format(rig_reg.GetMetricValue()))
70
+
71
+ resampler = sitk.ResampleImageFilter()
72
+ resampler.SetReferenceImage(image_1)
73
+ resampler.SetInterpolator(sitk.sitkLinear)
74
+ resampler.SetDefaultPixelValue(100)
75
+ resampler.SetTransform(rig_reg_trf)
76
+
77
+ image_2 = resampler.Execute(image_2)
78
+
79
+ # TODO: Build a common image to hold both image_1 and image_2
80
+
81
+
82
+ def pad_images(image_1: nib.Nifti1Image, image_2: nib.Nifti1Image):
83
+ """
84
+ Align image_1 and image_2 by the top left corner and pad them to the largest dimensions along the three axes
85
+ """
86
+ joint_image_shape = np.maximum(image_1.shape, image_2.shape)
87
+ pad_1 = [[0, p] for p in joint_image_shape - image_1.shape]
88
+ pad_2 = [[0, p] for p in joint_image_shape - image_2.shape]
89
+ image_1_padded = np.pad(image_1.dataobj, pad_1, mode='edge').astype(np.float32)
90
+ image_2_padded = np.pad(image_2.dataobj, pad_2, mode='edge').astype(np.float32)
91
+
92
+ return image_1_padded, image_2_padded
93
+
94
+
95
+ def pad_crop_to_original_shape(crop_image: np.asarray, output_shape: [tuple, np.asarray], top_left_corner: [tuple, np.asarray]):
96
+ """
97
+ Pad crop_image so the output image has output_shape with the crop where it originally was found
98
+ """
99
+ output_shape = np.asarray(output_shape)
100
+ top_left_corner = np.asarray(top_left_corner)
101
+
102
+ pad = [[c, o - (c + i)] for c, o, i in zip(top_left_corner[:3], output_shape[:3], crop_image.shape[:3])]
103
+ if len(crop_image.shape) == 4:
104
+ pad += [[0, 0]]
105
+ return np.pad(crop_image, pad, mode='constant', constant_values=np.min(crop_image)).astype(crop_image.dtype)
106
+
107
+
108
+ def pad_displacement_map(disp_map: np.ndarray, crop_min: np.ndarray, crop_max: np.ndarray, output_shape: (np.ndarray, list)) -> np.ndarray:
109
+ ret_val = disp_map
110
+ if np.all([d != i for d, i in zip(disp_map.shape[:3], output_shape)]):
111
+ padding = [[crop_min[i], max(0, output_shape[i] - crop_max[i])] for i in range(3)] + [[0, 0]]
112
+ ret_val = np.pad(disp_map, padding, mode='constant')
113
+ return ret_val
114
+
115
+
116
+ def run_livermask(input_image_path, outputdir, filename: str = 'segmentation') -> np.ndarray:
117
+ assert find_spec('livermask'), 'Livermask is not available'
118
+ LOGGER.info('Getting parenchyma segmentations...')
119
+ shutil.copy2(input_image_path, os.path.join(outputdir, f'{filename}.nii.gz'))
120
+ livermask_cmd = "{} -m livermask.livermask --input {} --output {}".format(sys.executable,
121
+ input_image_path,
122
+ os.path.join(outputdir,
123
+ f'{filename}.nii.gz'))
124
+ subprocess.run(livermask_cmd)
125
+ LOGGER.info('done!')
126
+ segmentation_path = os.path.join(outputdir, f'{filename}.nii.gz')
127
+ return np.asarray(nib.load(segmentation_path).dataobj, dtype=int)
128
+
129
+
130
+ def debug_save_image(image: (np.ndarray, nib.Nifti1Image), filename: str, outputdir: str, debug: bool = True):
131
+ def disp_map_modulus(disp_map, scale: float = None):
132
+ disp_map_mod = np.sqrt(np.sum(np.power(disp_map, 2), -1))
133
+ if scale:
134
+ min_disp = np.min(disp_map_mod)
135
+ max_disp = np.max(disp_map_mod)
136
+ disp_map_mod = disp_map_mod - min_disp / (max_disp - min_disp)
137
+ disp_map_mod *= scale
138
+ LOGGER.debug('Scaled displacement map to [0., 1.] range')
139
+ return disp_map_mod
140
+
141
+ if debug:
142
+ os.makedirs(os.path.join(outputdir, 'debug'), exist_ok=True)
143
+ if image.shape[-1] > 1:
144
+ image = disp_map_modulus(image, 1.)
145
+ save_nifti(image, os.path.join(outputdir, 'debug', filename+'.nii.gz'), verbose=False)
146
+ LOGGER.debug(f'Saved {filename} at {os.path.join(outputdir, filename + ".nii.gz")}')
147
+
148
+
149
+ def get_roi(image_filepath: str,
150
+ compute_segmentation: bool,
151
+ outputdir: str,
152
+ filename_filepath: str = 'segmentation',
153
+ segmentation_file: str = None,
154
+ debug: bool = False) -> list:
155
+ segm = None
156
+ if segmentation_file is None and compute_segmentation:
157
+ LOGGER.info(f'Computing segmentation using livermask. Only for liver in abdominal CTs')
158
+ try:
159
+ segm = run_livermask(image_filepath, outputdir, filename_filepath)
160
+ LOGGER.info(f'Loaded segmentation using livermask from {os.path.join(outputdir, filename_filepath)}')
161
+ except (AssertionError, FileNotFoundError) as er:
162
+ LOGGER.warning(er)
163
+ LOGGER.warning('No segmentation provided! Using the full volume')
164
+ pass
165
+ elif segmentation_file is not None:
166
+ segm = np.asarray(nib.load(segmentation_file).dataobj, dtype=int)
167
+ LOGGER.info(f'Loaded fixed segmentation from {segmentation_file}')
168
+ else:
169
+ LOGGER.warning('No segmentation provided! Using the full volume')
170
+ if segm is not None:
171
+ segm[segm > 0] = 1
172
+ ret_val = regionprops(segm)[0].bbox
173
+ debug_save_image(segm, f'img_1_{filename_filepath}', outputdir, debug)
174
+ else:
175
+ ret_val = [0, 0, 0] + list(nib.load(image_filepath).shape[:3])
176
+ LOGGER.debug(f'ROI found at coordinates {ret_val}')
177
+ return ret_val
178
+
179
+
180
+ def main():
181
+ parser = argparse.ArgumentParser()
182
+ parser.add_argument('-f', '--fixed', type=str, help='Path to fixed image file (NIfTI)')
183
+ parser.add_argument('-m', '--moving', type=str, help='Path to moving segmentation image file (NIfTI)', default=None)
184
+ parser.add_argument('-F', '--fixedsegm', type=str, help='Path to fixed image segmentation file(NIfTI)',
185
+ default=None)
186
+ parser.add_argument('-M', '--movingsegm', type=str, help='Path to moving image file (NIfTI)')
187
+ parser.add_argument('-o', '--outputdir', type=str, help='Output directory', default='./Registration_output')
188
+ parser.add_argument('-a', '--anatomy', type=str, help='Anatomical structure: liver (L) (Default) or brain (B)',
189
+ default='L')
190
+ parser.add_argument('-s', '--make-segmentation', action='store_true', help='Try to create a segmentation for liver in CT images', default=False)
191
+ parser.add_argument('--gpu', type=int,
192
+ help='In case of multi-GPU systems, limits the execution to the defined GPU number',
193
+ default=None)
194
+ parser.add_argument('--model', type=str, help='Which model to use: BL-N, BL-S, SG-ND, SG-NSD, UW-NSD, UW-NSDH',
195
+ default='UW-NSD')
196
+ parser.add_argument('-d', '--debug', action='store_true', help='Produce additional debug information', default=False)
197
+ parser.add_argument('-c', '--clear-outputdir', action='store_true', help='Clear output folder if this has content', default=False)
198
+ parser.add_argument('--original-resolution', action='store_true',
199
+ help='Re-scale the displacement map to the originla resolution and apply it to the original moving image. WARNING: longer processing time.',
200
+ default=False)
201
+ parser.add_argument('--save-displacement-map', action='store_true', help='Save the displacement map. An NPZ file will be created.',
202
+ default=False)
203
+ args = parser.parse_args()
204
+
205
+ assert os.path.exists(args.fixed), 'Fixed image not found'
206
+ assert os.path.exists(args.moving), 'Moving image not found'
207
+ assert args.model in C.MODEL_TYPES.keys(), 'Invalid model type'
208
+ assert args.anatomy in C.ANATOMIES.keys(), 'Invalid anatomy option'
209
+ if os.path.exists(args.outputdir) and len(os.listdir(args.outputdir)):
210
+ if args.clear_outputdir:
211
+ erase = 'y'
212
+ else:
213
+ erase = input('Output directory is not empty, erase content? (y/n)')
214
+ if erase.lower() in ['y', 'yes']:
215
+ shutil.rmtree(args.outputdir, ignore_errors=True)
216
+ print('Erased directory: ' + args.outputdir)
217
+ elif erase.lower() in ['n', 'no']:
218
+ args.outputdir = os.path.join(args.outputdir, datetime.datetime.now().strftime('%H%M%S_%Y%m%d'))
219
+ print('New output directory: ' + args.outputdir)
220
+ os.makedirs(args.outputdir, exist_ok=True)
221
+
222
+ log_format = '%(asctime)s [%(levelname)s]:\t%(message)s'
223
+ logging.basicConfig(filename=os.path.join(args.outputdir, 'log.log'), filemode='w',
224
+ format=log_format, datefmt='%Y-%m-%d %H:%M:%S')
225
+
226
+ stdout_handler = logging.StreamHandler(sys.stdout)
227
+ stdout_handler.setFormatter(logging.Formatter(log_format, datefmt='%Y-%m-%d %H:%M:%S'))
228
+ LOGGER.addHandler(stdout_handler)
229
+ if isinstance(args.gpu, int):
230
+ os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'
231
+ os.environ['CUDA_VISIBLE_DEVICES'] = str(args.gpu) # Check availability before running using 'nvidia-smi'
232
+ LOGGER.setLevel('INFO')
233
+ if args.debug:
234
+ LOGGER.setLevel('DEBUG')
235
+ LOGGER.debug('DEBUG MODE ENABLED')
236
+
237
+ if args.original_resolution:
238
+ LOGGER.info('The results will be rescaled back to the original image resolution. '
239
+ 'Expect longer post-processing times.')
240
+ else:
241
+ LOGGER.info(f'The results will NOT be rescaled. Output shape will be {C.IMG_SHAPE[:3]}.')
242
+
243
+ # Load the file and preprocess it
244
+ LOGGER.info('Loading image files')
245
+ fixed_image_or = nib.load(args.fixed)
246
+ moving_image_or = nib.load(args.moving)
247
+ moving_image_header = moving_image_or.header.copy()
248
+ image_shape_or = np.asarray(fixed_image_or.shape)
249
+ fixed_image_or, moving_image_or = pad_images(fixed_image_or, moving_image_or)
250
+ fixed_image_or = fixed_image_or[..., np.newaxis] # add channel dim
251
+ moving_image_or = moving_image_or[..., np.newaxis] # add channel dim
252
+ debug_save_image(fixed_image_or, 'img_0_loaded_fix_image', args.outputdir, args.debug)
253
+ debug_save_image(moving_image_or, 'img_0_loaded_moving_image', args.outputdir, args.debug)
254
+
255
+ # TF stuff
256
+ LOGGER.info('Setting up configuration')
257
+ config = tf.compat.v1.ConfigProto() # device_count={'GPU':0})
258
+ config.gpu_options.allow_growth = True
259
+ config.log_device_placement = False ## to log device placement (on which device the operation ran)
260
+ config.allow_soft_placement = True
261
+
262
+ sess = tf.compat.v1.Session(config=config)
263
+ tf.compat.v1.keras.backend.set_session(sess)
264
+
265
+ # Preprocess data
266
+ # 1. Run Livermask to get the mask around the liver in both the fixed and moving image
267
+ LOGGER.info('Getting ROI')
268
+ fixed_segm_bbox = get_roi(args.fixed, args.make_segmentation, args.outputdir,
269
+ 'fixed_segmentation', args.fixedsegm, args.debug)
270
+ moving_segm_bbox = get_roi(args.moving, args.make_segmentation, args.outputdir,
271
+ 'moving_segmentation', args.movingsegm, args.debug)
272
+
273
+ crop_min = np.amin(np.vstack([fixed_segm_bbox[:3], moving_segm_bbox[:3]]), axis=0)
274
+ crop_max = np.amax(np.vstack([fixed_segm_bbox[3:], moving_segm_bbox[3:]]), axis=0)
275
+
276
+ # 2.2 Crop the fixed and moving images using such boxes
277
+ fixed_image = fixed_image_or[crop_min[0]: crop_max[0],
278
+ crop_min[1]: crop_max[1],
279
+ crop_min[2]: crop_max[2], ...]
280
+ debug_save_image(fixed_image, 'img_2_cropped_fixed_image', args.outputdir, args.debug)
281
+
282
+ moving_image = moving_image_or[crop_min[0]: crop_max[0],
283
+ crop_min[1]: crop_max[1],
284
+ crop_min[2]: crop_max[2], ...]
285
+ debug_save_image(moving_image, 'img_2_cropped_moving_image', args.outputdir, args.debug)
286
+
287
+ image_shape_crop = fixed_image.shape
288
+ # 2.3 Resize the images to the expected input size
289
+ zoom_factors = np.asarray(C.IMG_SHAPE) / np.asarray(image_shape_crop)
290
+ fixed_image = zoom(fixed_image, zoom_factors)
291
+ moving_image = zoom(moving_image, zoom_factors)
292
+ fixed_image = min_max_norm(fixed_image)
293
+ moving_image = min_max_norm(moving_image)
294
+ debug_save_image(fixed_image, 'img_3_preproc_fixed_image', args.outputdir, args.debug)
295
+ debug_save_image(moving_image, 'img_3_preproc_moving_image', args.outputdir, args.debug)
296
+
297
+ # 3. Build the whole graph
298
+ LOGGER.info('Building TF graph')
299
+ ### METRICS GRAPH ###
300
+ fix_img_ph = tf.compat.v1.placeholder(tf.float32, (1, None, None, None, 1), name='fix_img')
301
+ pred_img_ph = tf.compat.v1.placeholder(tf.float32, (1, None, None, None, 1), name='pred_img')
302
+
303
+ ssim_tf = StructuralSimilarity_simplified(patch_size=2, dim=3, dynamic_range=1.).metric(fix_img_ph, pred_img_ph)
304
+ ncc_tf = NCC(image_shape_or).metric(fix_img_ph, pred_img_ph)
305
+ mse_tf = vxm.losses.MSE().loss(fix_img_ph, pred_img_ph)
306
+ ms_ssim_tf = MultiScaleStructuralSimilarity(max_val=1., filter_size=3).metric(fix_img_ph, pred_img_ph)
307
+
308
+ LOGGER.info(f'Getting model: {"Brain" if args.anatomy == "B" else "Liver"} -> {args.model}')
309
+ MODEL_FILE = get_models_path(args.anatomy, args.model, os.getcwd()) # MODELS_FILE[args.anatomy][args.model]
310
+
311
+ network, registration_model = load_model(MODEL_FILE, False, True)
312
+ deb_model = network.apply_transform
313
+
314
+ LOGGER.info('Computing registration')
315
+ with sess.as_default():
316
+ if args.debug:
317
+ registration_model.summary(line_length=C.SUMMARY_LINE_LENGTH)
318
+ LOGGER.info('Computing displacement map...')
319
+ time_disp_map_start = time.time()
320
+ # disp_map = registration_model.predict([moving_image[np.newaxis, ...], fixed_image[np.newaxis, ...]])
321
+ p, disp_map = network.predict([moving_image[np.newaxis, ...], fixed_image[np.newaxis, ...]])
322
+ time_disp_map_end = time.time()
323
+ LOGGER.info(f'\t... done ({time_disp_map_end - time_disp_map_start})')
324
+ disp_map = np.squeeze(disp_map)
325
+ debug_save_image(np.squeeze(disp_map), 'disp_map_0_raw', args.outputdir, args.debug)
326
+ debug_save_image(p[0, ...], 'img_4_net_pred_image', args.outputdir, args.debug)
327
+ # pred_image = min_max_norm(pred_image)
328
+ # pred_image_isot = zoom(pred_image[0, ...], zoom_factors, order=3)[np.newaxis, ...]
329
+ # fixed_image_isot = zoom(fixed_image[0, ...], zoom_factors, order=3)[np.newaxis, ...]
330
+
331
+ LOGGER.info('Applying displacement map...')
332
+ time_pred_img_start = time.time()
333
+ pred_image = SpatialTransformer(interp_method='linear', indexing='ij', single_transform=False)([moving_image[np.newaxis, ...], disp_map[np.newaxis, ...]]).eval()
334
+ time_pred_img_end = time.time()
335
+ LOGGER.info(f'\t... done ({time_pred_img_end - time_pred_img_start} s)')
336
+ pred_image = pred_image[0, ...]
337
+
338
+ if args.original_resolution:
339
+ LOGGER.info('Scaling predicted image...')
340
+ moving_image = moving_image_or
341
+ fixed_image = fixed_image_or
342
+ # disp_map = disp_map_or
343
+ pred_image = zoom(pred_image, 1/zoom_factors)
344
+ pred_image = pad_crop_to_original_shape(pred_image, fixed_image_or.shape, crop_min)
345
+ LOGGER.info('Done...')
346
+
347
+ LOGGER.info('Computing metrics...')
348
+ if args.original_resolution:
349
+ ssim, ncc, mse, ms_ssim = sess.run([ssim_tf, ncc_tf, mse_tf, ms_ssim_tf],
350
+ {'fix_img:0': fixed_image[np.newaxis,
351
+ crop_min[0]: crop_max[0],
352
+ crop_min[1]: crop_max[1],
353
+ crop_min[2]: crop_max[2],
354
+ ...],
355
+ 'pred_img:0': pred_image[np.newaxis,
356
+ crop_min[0]: crop_max[0],
357
+ crop_min[1]: crop_max[1],
358
+ crop_min[2]: crop_max[2],
359
+ ...]}) # to only compare the deformed region!
360
+ else:
361
+
362
+ ssim, ncc, mse, ms_ssim = sess.run([ssim_tf, ncc_tf, mse_tf, ms_ssim_tf],
363
+ {'fix_img:0': fixed_image[np.newaxis, ...],
364
+ 'pred_img:0': pred_image[np.newaxis, ...]})
365
+ ssim = np.mean(ssim)
366
+ ms_ssim = ms_ssim[0]
367
+
368
+ if args.original_resolution:
369
+ save_nifti(pred_image, os.path.join(args.outputdir, 'pred_image.nii.gz'), header=moving_image_header)
370
+ else:
371
+ save_nifti(pred_image, os.path.join(args.outputdir, 'pred_image.nii.gz'))
372
+ save_nifti(fixed_image, os.path.join(args.outputdir, 'fixed_image.nii.gz'))
373
+ save_nifti(moving_image, os.path.join(args.outputdir, 'moving_image.nii.gz'))
374
+
375
+ if args.save_displacement_map or args.debug:
376
+ if args.original_resolution:
377
+ # Up sample the displacement map to the full res
378
+ LOGGER.info('Scaling displacement map...')
379
+ trf = np.eye(4)
380
+ np.fill_diagonal(trf, 1 / zoom_factors)
381
+ disp_map = resize_displacement_map(disp_map, None, trf, moving_image_header.get_zooms())
382
+ debug_save_image(disp_map, 'disp_map_1_upsampled', args.outputdir, args.debug)
383
+ disp_map = pad_displacement_map(disp_map, crop_min, crop_max, image_shape_or)
384
+ debug_save_image(np.squeeze(disp_map), 'disp_map_2_padded', args.outputdir, args.debug)
385
+ disp_map = gaussian_filter(disp_map, 5)
386
+ debug_save_image(np.squeeze(disp_map), 'disp_map_3_smoothed', args.outputdir, args.debug)
387
+ LOGGER.info('\t... done')
388
+ if args.debug:
389
+ np.savez_compressed(os.path.join(args.outputdir, 'displacement_map.npz'), disp_map)
390
+ else:
391
+ np.savez_compressed(os.path.join(os.path.join(args.outputdir, 'debug'), 'displacement_map.npz'), disp_map)
392
+ LOGGER.info('Predicted image and displacement map saved in: '.format(args.outputdir))
393
+ LOGGER.info(f'Displacement map prediction time: {time_disp_map_end - time_disp_map_start} s')
394
+ LOGGER.info(f'Predicted image time: {time_pred_img_end - time_pred_img_start} s')
395
+
396
+ LOGGER.info('Similarity metrics\n------------------')
397
+ LOGGER.info('SSIM: {:.03f}'.format(ssim))
398
+ LOGGER.info('NCC: {:.03f}'.format(ncc))
399
+ LOGGER.info('MSE: {:.03f}'.format(mse))
400
+ LOGGER.info('MS SSIM: {:.03f}'.format(ms_ssim))
401
+
402
+ # ssim, ncc, mse, ms_ssim = sess.run([ssim_tf, ncc_tf, mse_tf, ms_ssim_tf],
403
+ # {'fix_img:0': fixed_image[np.newaxis, ...], 'pred_img:0': p})
404
+ # ssim = np.mean(ssim)
405
+ # ms_ssim = ms_ssim[0]
406
+ # LOGGER.info('\nSimilarity metrics (ROI)\n------------------')
407
+ # LOGGER.info('SSIM: {:.03f}'.format(ssim))
408
+ # LOGGER.info('NCC: {:.03f}'.format(ncc))
409
+ # LOGGER.info('MSE: {:.03f}'.format(mse))
410
+ # LOGGER.info('MS SSIM: {:.03f}'.format(ms_ssim))
411
+
412
+ del registration_model
413
+ LOGGER.info('Done')
414
+ exit(0)
415
+
416
+
417
+ if __name__ == '__main__':
418
+ main()
DeepDeformationMapRegistration/networks.py CHANGED
@@ -1,9 +1,9 @@
1
  import os, sys
2
- currentdir = os.path.dirname(os.path.realpath(__file__))
3
- parentdir = os.path.dirname(currentdir)
4
- sys.path.append(parentdir) # PYTHON > 3.3 does not allow relative referencing
5
-
6
- PYCHARM_EXEC = os.getenv('PYCHARM_EXEC') == 'True'
7
 
8
  import tensorflow as tf
9
  import voxelmorph as vxm
 
1
  import os, sys
2
+ # currentdir = os.path.dirname(os.path.realpath(__file__))
3
+ # parentdir = os.path.dirname(currentdir)
4
+ # sys.path.append(parentdir) # PYTHON > 3.3 does not allow relative referencing
5
+ #
6
+ # PYCHARM_EXEC = os.getenv('PYCHARM_EXEC') == 'True'
7
 
8
  import tensorflow as tf
9
  import voxelmorph as vxm
DeepDeformationMapRegistration/utils/constants.py CHANGED
@@ -30,7 +30,7 @@ PRED_IMG_GT = 1
30
  DISP_VECT_GT = 2
31
  DISP_VECT_LOC_GT = 3
32
 
33
- IMG_SIZE = 64 # Assumed a square image
34
  IMG_SHAPE = (IMG_SIZE, IMG_SIZE, IMG_SIZE, 1) # (IMG_SIZE, IMG_SIZE, 1)
35
  DISP_MAP_SHAPE = (IMG_SIZE, IMG_SIZE, IMG_SIZE, 3)
36
  BATCH_SHAPE = (None, IMG_SIZE, IMG_SIZE, IMG_SIZE, 2) # Expected batch shape by the network
@@ -196,8 +196,8 @@ DROPOUT = True
196
  DROPOUT_RATE = 0.2
197
  MAX_DATA_SIZE = (1000, 1000, 1)
198
  PLATEAU_THR = 0.01 # A slope between +-PLATEAU_THR will be considered a plateau for the LR updating function
199
- ENCODER_FILTERS = [4, 8, 16, 32, 64]
200
-
201
  # SSIM
202
  SSIM_FILTER_SIZE = 11 # Size of Gaussian filter
203
  SSIM_FILTER_SIGMA = 1.5 # Width of Gaussian filter
@@ -205,7 +205,7 @@ SSIM_K1 = 0.01 # Def. 0.01
205
  SSIM_K2 = 0.03 # Recommended values 0 < K2 < 0.4
206
  MAX_VALUE = 1.0 # Maximum intensity values
207
 
208
- # Mathematic constants
209
  EPS = 1e-8
210
  EPS_tf = tf.constant(EPS, dtype=tf.float32)
211
  LOG2 = tf.math.log(tf.constant(2, dtype=tf.float32))
@@ -523,3 +523,11 @@ GAMMA_AUGMENTATION = True
523
  BRIGHTNESS_AUGMENTATION = False
524
  NUM_CONTROL_PTS_AUG = 10
525
  NUM_AUGMENTATIONS = 1
 
 
 
 
 
 
 
 
 
30
  DISP_VECT_GT = 2
31
  DISP_VECT_LOC_GT = 3
32
 
33
+ IMG_SIZE = 128 # Assumed a square image
34
  IMG_SHAPE = (IMG_SIZE, IMG_SIZE, IMG_SIZE, 1) # (IMG_SIZE, IMG_SIZE, 1)
35
  DISP_MAP_SHAPE = (IMG_SIZE, IMG_SIZE, IMG_SIZE, 3)
36
  BATCH_SHAPE = (None, IMG_SIZE, IMG_SIZE, IMG_SIZE, 2) # Expected batch shape by the network
 
196
  DROPOUT_RATE = 0.2
197
  MAX_DATA_SIZE = (1000, 1000, 1)
198
  PLATEAU_THR = 0.01 # A slope between +-PLATEAU_THR will be considered a plateau for the LR updating function
199
+ ENCODER_FILTERS = [32, 64, 128, 256, 512, 1024]
200
+ DECODER_FILTERS = ENCODER_FILTERS[::-1] + [16, 16]
201
  # SSIM
202
  SSIM_FILTER_SIZE = 11 # Size of Gaussian filter
203
  SSIM_FILTER_SIGMA = 1.5 # Width of Gaussian filter
 
205
  SSIM_K2 = 0.03 # Recommended values 0 < K2 < 0.4
206
  MAX_VALUE = 1.0 # Maximum intensity values
207
 
208
+ # Mathematics constants
209
  EPS = 1e-8
210
  EPS_tf = tf.constant(EPS, dtype=tf.float32)
211
  LOG2 = tf.math.log(tf.constant(2, dtype=tf.float32))
 
523
  BRIGHTNESS_AUGMENTATION = False
524
  NUM_CONTROL_PTS_AUG = 10
525
  NUM_AUGMENTATIONS = 1
526
+
527
+ ANATOMIES = {'L': 'liver', 'B': 'brain'}
528
+ MODEL_TYPES = {'BL-N': 'bl_ncc',
529
+ 'BL-NS': 'bl_ncc_ssim',
530
+ 'SG-ND': 'sg_ncc_dsc',
531
+ 'SG-NSD': 'sg_ncc_ssim_dsc',
532
+ 'UW-NSD': 'uw_ncc_ssim_dsc',
533
+ 'UW-NSDH': 'uw_ncc_ssim_dsc_hd'}
DeepDeformationMapRegistration/utils/misc.py CHANGED
@@ -167,7 +167,7 @@ def segmentation_cardinal_to_ohe(segmentation, labels_list: list = None):
167
  return cpy
168
 
169
 
170
- def resize_displacement_map(displacement_map: np.ndarray, dest_shape: [list, np.ndarray, tuple], scale_trf: np.ndarray=None):
171
  if scale_trf is None:
172
  scale_trf = scale_transformation(displacement_map.shape, dest_shape)
173
  else:
@@ -175,11 +175,12 @@ def resize_displacement_map(displacement_map: np.ndarray, dest_shape: [list, np.
175
  zoom_factors = scale_trf.diagonal()
176
  # First scale the values, so we cut down the number of multiplications
177
  dm_resized = np.copy(displacement_map)
178
- dm_resized[..., 0] *= zoom_factors[0]
179
- dm_resized[..., 1] *= zoom_factors[1]
180
- dm_resized[..., 2] *= zoom_factors[2]
181
  # Then rescale using zoom
182
  dm_resized = zoom(dm_resized, zoom_factors)
 
 
 
 
183
  return dm_resized
184
 
185
 
 
167
  return cpy
168
 
169
 
170
+ def resize_displacement_map(displacement_map: np.ndarray, dest_shape: [list, np.ndarray, tuple], scale_trf: np.ndarray = None, resolution_factors: [tuple, np.ndarray] = np.ones((3,))):
171
  if scale_trf is None:
172
  scale_trf = scale_transformation(displacement_map.shape, dest_shape)
173
  else:
 
175
  zoom_factors = scale_trf.diagonal()
176
  # First scale the values, so we cut down the number of multiplications
177
  dm_resized = np.copy(displacement_map)
 
 
 
178
  # Then rescale using zoom
179
  dm_resized = zoom(dm_resized, zoom_factors)
180
+ dm_resized *= np.asarray(resolution_factors)
181
+ # dm_resized[..., 0] *= resolution_factors[0]
182
+ # dm_resized[..., 1] *= resolution_factors[1]
183
+ # dm_resized[..., 2] *= resolution_factors[2]
184
  return dm_resized
185
 
186
 
DeepDeformationMapRegistration/utils/model_utils.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import requests
3
+ from datetime import datetime
4
+ from email.utils import parsedate_to_datetime, formatdate
5
+ from DeepDeformationMapRegistration.utils.constants import ANATOMIES, MODEL_TYPES, ENCODER_FILTERS, DECODER_FILTERS, IMG_SHAPE
6
+ import voxelmorph as vxm
7
+ from DeepDeformationMapRegistration.utils.logger import LOGGER
8
+
9
+
10
+ # taken from: https://lenon.dev/blog/downloading-and-caching-large-files-using-python/
11
+ def download(url, destination_file):
12
+ headers = {}
13
+
14
+ if os.path.exists(destination_file):
15
+ mtime = os.path.getmtime(destination_file)
16
+ headers["if-modified-since"] = formatdate(mtime, usegmt=True)
17
+
18
+ response = requests.get(url, headers=headers, stream=True)
19
+ response.raise_for_status()
20
+
21
+ if response.status_code == requests.codes.not_modified:
22
+ return
23
+
24
+ if response.status_code == requests.codes.ok:
25
+ with open(destination_file, "wb") as f:
26
+ for chunk in response.iter_content(chunk_size=1048576):
27
+ f.write(chunk)
28
+
29
+ last_modified = response.headers.get("last-modified")
30
+ if last_modified:
31
+ new_mtime = parsedate_to_datetime(last_modified).timestamp()
32
+ os.utime(destination_file, times=(datetime.now().timestamp(), new_mtime))
33
+
34
+
35
+ def get_models_path(anatomy: str, model_type: str, output_root_dir: str):
36
+ assert anatomy in ANATOMIES.keys(), 'Invalid anatomy'
37
+ assert model_type in MODEL_TYPES.keys(), 'Invalid model type'
38
+ anatomy = ANATOMIES[anatomy]
39
+ model_type = MODEL_TYPES[model_type]
40
+ url = 'https://github.com/jpdefrutos/DDMR/releases/download/trained_models_v0/' + anatomy + '_' + model_type + '.h5'
41
+ file_path = os.path.join(output_root_dir, 'models', anatomy, model_type + '.h5')
42
+ if not os.path.exists(file_path):
43
+ LOGGER.info(f'Model not found. Downloading from {url}... ')
44
+ os.makedirs(os.path.split(file_path)[0], exist_ok=True)
45
+ download(url, file_path)
46
+ LOGGER.info(f'... downloaded model. Stored in {file_path}')
47
+ else:
48
+ LOGGER.info(f'Found model: {file_path}')
49
+ return file_path
50
+
51
+
52
+ def load_model(weights_file_path: str, trainable: bool = False, return_registration_model: bool=True):
53
+ assert os.path.exists(weights_file_path), f'File {weights_file_path} not found'
54
+ assert weights_file_path.endswith('h5'), 'Invalid file extension. Expected .h5'
55
+
56
+ ret_val = vxm.networks.VxmDense(inshape=IMG_SHAPE[:-1],
57
+ nb_unet_features=[ENCODER_FILTERS, DECODER_FILTERS],
58
+ int_steps=0)
59
+ ret_val.load_weights(weights_file_path, by_name=True)
60
+ ret_val.trainable = trainable
61
+
62
+ if return_registration_model:
63
+ ret_val = (ret_val, ret_val.get_registration_model())
64
+
65
+ return ret_val
setup.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from setuptools import find_packages, setup
2
+ import os
3
+
4
+ # with open("README.md", "r", encoding="utf-8") as f:
5
+ # long_description = f.read()
6
+
7
+ with open("requirements.txt", "r") as f:
8
+ reqs = [line.strip('\n') for line in f.readlines()]
9
+
10
+ setup(
11
+ name='DeepDeformationMapRegistration',
12
+ py_modules=['DeepDeformationMapRegistration'],
13
+ packages=find_packages(include=['DeepDeformationMapRegistration', 'DeepDeformationMapRegistration.*'],
14
+ exclude=['test_images', 'test_images.*']),
15
+ version='1.0',
16
+ description='Deep-registration training toolkit',
17
+ # long_description=long_description,
18
+ author='Javier Pérez de Frutos',
19
+ classifiers=[
20
+ 'Programming language :: Python :: 3',
21
+ 'License :: OSI Approveed :: MIT License',
22
+ 'Operating System :: OS Independent'
23
+ ],
24
+ python_requires='>=3.6',
25
+ install_requires=[
26
+ 'fastrlock>=0.3', # required by cupy-cuda110
27
+ 'testresources', # required by launchpadlib
28
+ 'scipy',
29
+ 'scikit-image',
30
+ 'simpleITK',
31
+ 'voxelmorph==0.1',
32
+ 'pystrum==0.1',
33
+ 'tensorflow-gpu==1.14.0',
34
+ 'tensorflow-addons',
35
+ 'tensorflow-datasets',
36
+ 'tensorflow-metadata',
37
+ 'tensorboard==1.14.0',
38
+ 'nibabel==3.2.1',
39
+ 'numpy==1.18.5',
40
+ 'h5py==2.10'
41
+ ],
42
+ entry_points={
43
+ 'console_scripts': ['ddmr=DeepDeformationMapRegistration.main:main']
44
+ }
45
+ )