Commit
·
7b8d670
1
Parent(s):
0e7de0a
Fixed CLI
Browse filesUpdated constants.py to work with the new model downloader functions
Added download functionality to fetch the compiled models from the release files in GitHub (model_dowloader.py)
DeepDeformationMapRegistration/main.py
CHANGED
|
@@ -28,7 +28,11 @@ from DeepDeformationMapRegistration.losses import StructuralSimilarity_simplifie
|
|
| 28 |
from DeepDeformationMapRegistration.ms_ssim_tf import MultiScaleStructuralSimilarity
|
| 29 |
from DeepDeformationMapRegistration.utils.operators import min_max_norm
|
| 30 |
from DeepDeformationMapRegistration.utils.misc import resize_displacement_map
|
|
|
|
| 31 |
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
MODELS_FILE = {'L': {'BL-N': './models/liver/bl_ncc.h5',
|
| 34 |
'BL-S': './models/liver/bl_ncc_ssim.h5',
|
|
@@ -100,26 +104,30 @@ def pad_images(image_1: nib.Nifti1Image, image_2: nib.Nifti1Image):
|
|
| 100 |
joint_image_shape = np.maximum(image_1.shape, image_2.shape)
|
| 101 |
pad_1 = [[0, p] for p in joint_image_shape - image_1.shape]
|
| 102 |
pad_2 = [[0, p] for p in joint_image_shape - image_2.shape]
|
| 103 |
-
image_1_padded = np.pad(image_1.dataobj, pad_1, mode='edge')
|
| 104 |
-
image_2_padded = np.pad(image_2.dataobj, pad_2, mode='edge')
|
| 105 |
|
| 106 |
return image_1_padded, image_2_padded
|
| 107 |
|
| 108 |
|
| 109 |
def pad_displacement_map(disp_map: np.ndarray, crop_min: np.ndarray, crop_max: np.ndarray, output_shape: (np.ndarray, list)) -> np.ndarray:
|
| 110 |
-
|
| 111 |
-
|
|
|
|
|
|
|
|
|
|
| 112 |
|
| 113 |
|
| 114 |
def run_livermask(input_image_path, outputdir, filename: str = 'segmentation') -> np.ndarray:
|
| 115 |
-
|
|
|
|
| 116 |
shutil.copy2(input_image_path, os.path.join(outputdir, f'{filename}.nii.gz'))
|
| 117 |
livermask_cmd = "{} -m livermask.livermask --input {} --output {}".format(sys.executable,
|
| 118 |
input_image_path,
|
| 119 |
os.path.join(outputdir,
|
| 120 |
f'{filename}.nii.gz'))
|
| 121 |
subprocess.run(livermask_cmd)
|
| 122 |
-
|
| 123 |
segmentation_path = os.path.join(outputdir, f'{filename}.nii.gz')
|
| 124 |
return np.asarray(nib.load(segmentation_path).dataobj, dtype=int)
|
| 125 |
|
|
@@ -132,7 +140,7 @@ def debug_save_image(image: (np.ndarray, nib.Nifti1Image), filename: str, output
|
|
| 132 |
max_disp = np.max(disp_map_mod)
|
| 133 |
disp_map_mod = disp_map_mod - min_disp / (max_disp - min_disp)
|
| 134 |
disp_map_mod *= scale
|
| 135 |
-
|
| 136 |
return disp_map_mod
|
| 137 |
|
| 138 |
if debug:
|
|
@@ -140,35 +148,41 @@ def debug_save_image(image: (np.ndarray, nib.Nifti1Image), filename: str, output
|
|
| 140 |
if image.shape[-1] > 1:
|
| 141 |
image = disp_map_modulus(image, 1.)
|
| 142 |
save_nifti(image, os.path.join(outputdir, 'debug', filename+'.nii.gz'), verbose=False)
|
| 143 |
-
|
| 144 |
|
| 145 |
|
| 146 |
def get_roi(image_filepath: str,
|
| 147 |
-
|
| 148 |
outputdir: str,
|
| 149 |
filename_filepath: str = 'segmentation',
|
| 150 |
segmentation_file: str = None,
|
| 151 |
debug: bool = False) -> list:
|
| 152 |
segm = None
|
| 153 |
-
if segmentation_file is None and
|
| 154 |
-
|
| 155 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
elif segmentation_file is not None:
|
| 157 |
segm = np.asarray(nib.load(segmentation_file).dataobj, dtype=int)
|
| 158 |
-
|
| 159 |
else:
|
| 160 |
-
|
| 161 |
if segm is not None:
|
| 162 |
segm[segm > 0] = 1
|
| 163 |
ret_val = regionprops(segm)[0].bbox
|
| 164 |
debug_save_image(segm, f'img_1_{filename_filepath}', outputdir, debug)
|
| 165 |
else:
|
| 166 |
ret_val = [0, 0, 0] + list(nib.load(image_filepath).shape[:3])
|
| 167 |
-
|
| 168 |
return ret_val
|
| 169 |
|
| 170 |
|
| 171 |
-
|
| 172 |
parser = argparse.ArgumentParser()
|
| 173 |
parser.add_argument('-f', '--fixed', type=str, help='Path to fixed image file (NIfTI)')
|
| 174 |
parser.add_argument('-m', '--moving', type=str, help='Path to moving segmentation image file (NIfTI)', default=None)
|
|
@@ -178,23 +192,23 @@ if __name__ == '__main__':
|
|
| 178 |
parser.add_argument('-o', '--outputdir', type=str, help='Output directory', default='./Registration_output')
|
| 179 |
parser.add_argument('-a', '--anatomy', type=str, help='Anatomical structure: liver (L) (Default) or brain (B)',
|
| 180 |
default='L')
|
|
|
|
| 181 |
parser.add_argument('--gpu', type=int,
|
| 182 |
help='In case of multi-GPU systems, limits the execution to the defined GPU number',
|
| 183 |
default=None)
|
| 184 |
parser.add_argument('--model', type=str, help='Which model to use: BL-N, BL-S, SG-ND, SG-NSD, UW-NSD, UW-NSDH',
|
| 185 |
default='UW-NSD')
|
| 186 |
parser.add_argument('--debug', '-d', action='store_true', help='Produce additional debug information', default=False)
|
| 187 |
-
parser.add_argument('-
|
| 188 |
-
# parser.add_argument('--brain', type=bool, action='store_true', help='Perform brain MRi registration', default=False)
|
| 189 |
args = parser.parse_args()
|
| 190 |
|
| 191 |
assert os.path.exists(args.fixed), 'Fixed image not found'
|
| 192 |
assert os.path.exists(args.moving), 'Moving image not found'
|
| 193 |
-
assert args.model in
|
| 194 |
-
assert args.anatomy in
|
| 195 |
|
| 196 |
if os.path.exists(args.outputdir) and len(os.listdir(args.outputdir)):
|
| 197 |
-
if args.
|
| 198 |
erase = 'y'
|
| 199 |
else:
|
| 200 |
erase = input('Output directory is not empty, erase content? (y/n)')
|
|
@@ -209,19 +223,20 @@ if __name__ == '__main__':
|
|
| 209 |
log_format = '%(asctime)s [%(levelname)s]:\t%(message)s'
|
| 210 |
logging.basicConfig(filename=os.path.join(args.outputdir, 'log.log'), filemode='w',
|
| 211 |
format=log_format, datefmt='%Y-%m-%d %H:%M:%S')
|
| 212 |
-
|
| 213 |
stdout_handler = logging.StreamHandler(sys.stdout)
|
| 214 |
stdout_handler.setFormatter(logging.Formatter(log_format, datefmt='%Y-%m-%d %H:%M:%S'))
|
| 215 |
-
|
| 216 |
if isinstance(args.gpu, int):
|
| 217 |
os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'
|
| 218 |
os.environ['CUDA_VISIBLE_DEVICES'] = str(args.gpu) # Check availability before running using 'nvidia-smi'
|
|
|
|
| 219 |
if args.debug:
|
| 220 |
-
|
| 221 |
-
|
| 222 |
|
| 223 |
# Load the file and preprocess it
|
| 224 |
-
|
| 225 |
fixed_image_or = nib.load(args.fixed)
|
| 226 |
moving_image_or = nib.load(args.moving)
|
| 227 |
image_shape_or = np.asarray(fixed_image_or.shape)
|
|
@@ -232,7 +247,7 @@ if __name__ == '__main__':
|
|
| 232 |
debug_save_image(moving_image_or, 'img_0_loaded_moving_image', args.outputdir, args.debug)
|
| 233 |
|
| 234 |
# TF stuff
|
| 235 |
-
|
| 236 |
config = tf.compat.v1.ConfigProto() # device_count={'GPU':0})
|
| 237 |
config.gpu_options.allow_growth = True
|
| 238 |
config.log_device_placement = False ## to log device placement (on which device the operation ran)
|
|
@@ -243,10 +258,10 @@ if __name__ == '__main__':
|
|
| 243 |
|
| 244 |
# Preprocess data
|
| 245 |
# 1. Run Livermask to get the mask around the liver in both the fixed and moving image
|
| 246 |
-
|
| 247 |
-
fixed_segm_bbox = get_roi(args.fixed, args.
|
| 248 |
'fixed_segmentation', args.fixedsegm, args.debug)
|
| 249 |
-
moving_segm_bbox = get_roi(args.moving, args.
|
| 250 |
'moving_segmentation', args.movingsegm, args.debug)
|
| 251 |
|
| 252 |
crop_min = np.amin(np.vstack([fixed_segm_bbox[:3], moving_segm_bbox[:3]]), axis=0)
|
|
@@ -274,7 +289,7 @@ if __name__ == '__main__':
|
|
| 274 |
debug_save_image(moving_image, 'img_3_preproc_moving_image', args.outputdir, args.debug)
|
| 275 |
|
| 276 |
# 3. Build the whole graph
|
| 277 |
-
|
| 278 |
### METRICS GRAPH ###
|
| 279 |
fix_img_ph = tf.compat.v1.placeholder(tf.float32, (1, None, None, None, 1), name='fix_img')
|
| 280 |
pred_img_ph = tf.compat.v1.placeholder(tf.float32, (1, None, None, None, 1), name='pred_img')
|
|
@@ -284,8 +299,8 @@ if __name__ == '__main__':
|
|
| 284 |
mse_tf = vxm.losses.MSE().loss(fix_img_ph, pred_img_ph)
|
| 285 |
ms_ssim_tf = MultiScaleStructuralSimilarity(max_val=1., filter_size=3).metric(fix_img_ph, pred_img_ph)
|
| 286 |
|
| 287 |
-
|
| 288 |
-
MODEL_FILE = MODELS_FILE[args.anatomy][args.model]
|
| 289 |
|
| 290 |
# try:
|
| 291 |
# network = tf.keras.models.load_model(MODEL_FILE,
|
|
@@ -322,14 +337,16 @@ if __name__ == '__main__':
|
|
| 322 |
registration_model = network.get_registration_model()
|
| 323 |
deb_model = network.apply_transform
|
| 324 |
|
| 325 |
-
|
| 326 |
with sess.as_default():
|
| 327 |
if args.debug:
|
| 328 |
registration_model.summary(line_length=C.SUMMARY_LINE_LENGTH)
|
|
|
|
| 329 |
time_disp_map_start = time.time()
|
| 330 |
# disp_map = registration_model.predict([moving_image[np.newaxis, ...], fixed_image[np.newaxis, ...]])
|
| 331 |
p, disp_map = network.predict([moving_image[np.newaxis, ...], fixed_image[np.newaxis, ...]])
|
| 332 |
time_disp_map_end = time.time()
|
|
|
|
| 333 |
debug_save_image(np.squeeze(disp_map), 'disp_map_0_raw', args.outputdir, args.debug)
|
| 334 |
debug_save_image(p[0, ...], 'img_4_net_pred_image', args.outputdir, args.debug)
|
| 335 |
# pred_image = min_max_norm(pred_image)
|
|
@@ -337,6 +354,7 @@ if __name__ == '__main__':
|
|
| 337 |
# fixed_image_isot = zoom(fixed_image[0, ...], zoom_factors, order=3)[np.newaxis, ...]
|
| 338 |
|
| 339 |
# Up sample the displacement map to the full res
|
|
|
|
| 340 |
trf = np.eye(4)
|
| 341 |
np.fill_diagonal(trf, 1/zoom_factors)
|
| 342 |
disp_map = resize_displacement_map(np.squeeze(disp_map), None, trf)
|
|
@@ -345,10 +363,15 @@ if __name__ == '__main__':
|
|
| 345 |
debug_save_image(np.squeeze(disp_map_or), 'disp_map_2_padded', args.outputdir, args.debug)
|
| 346 |
disp_map_or = gaussian_filter(disp_map_or, 5)
|
| 347 |
debug_save_image(np.squeeze(disp_map_or), 'disp_map_3_smoothed', args.outputdir, args.debug)
|
|
|
|
| 348 |
|
|
|
|
| 349 |
time_pred_img_start = time.time()
|
| 350 |
pred_image = SpatialTransformer(interp_method='linear', indexing='ij', single_transform=False)([moving_image_or[np.newaxis, ...], disp_map_or[np.newaxis, ...]]).eval()
|
| 351 |
time_pred_img_end = time.time()
|
|
|
|
|
|
|
|
|
|
| 352 |
ssim, ncc, mse, ms_ssim = sess.run([ssim_tf, ncc_tf, mse_tf, ms_ssim_tf],
|
| 353 |
{'fix_img:0': fixed_image_or[np.newaxis, ...], 'pred_img:0': pred_image})
|
| 354 |
ssim = np.mean(ssim)
|
|
@@ -357,25 +380,30 @@ if __name__ == '__main__':
|
|
| 357 |
|
| 358 |
save_nifti(pred_image, os.path.join(args.outputdir, 'pred_image.nii.gz'))
|
| 359 |
np.savez_compressed(os.path.join(args.outputdir, 'displacement_map.npz'), disp_map_or)
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
|
| 370 |
ssim, ncc, mse, ms_ssim = sess.run([ssim_tf, ncc_tf, mse_tf, ms_ssim_tf],
|
| 371 |
{'fix_img:0': fixed_image[np.newaxis, ...], 'pred_img:0': p})
|
| 372 |
ssim = np.mean(ssim)
|
| 373 |
ms_ssim = ms_ssim[0]
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
|
| 380 |
del registration_model
|
| 381 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
from DeepDeformationMapRegistration.ms_ssim_tf import MultiScaleStructuralSimilarity
|
| 29 |
from DeepDeformationMapRegistration.utils.operators import min_max_norm
|
| 30 |
from DeepDeformationMapRegistration.utils.misc import resize_displacement_map
|
| 31 |
+
from DeepDeformationMapRegistration.utils.model_downloader import get_models_path
|
| 32 |
|
| 33 |
+
from importlib.util import find_spec
|
| 34 |
+
|
| 35 |
+
LOGGER = logging.getLogger(__name__)
|
| 36 |
|
| 37 |
MODELS_FILE = {'L': {'BL-N': './models/liver/bl_ncc.h5',
|
| 38 |
'BL-S': './models/liver/bl_ncc_ssim.h5',
|
|
|
|
| 104 |
joint_image_shape = np.maximum(image_1.shape, image_2.shape)
|
| 105 |
pad_1 = [[0, p] for p in joint_image_shape - image_1.shape]
|
| 106 |
pad_2 = [[0, p] for p in joint_image_shape - image_2.shape]
|
| 107 |
+
image_1_padded = np.pad(image_1.dataobj, pad_1, mode='edge').astype(np.float32)
|
| 108 |
+
image_2_padded = np.pad(image_2.dataobj, pad_2, mode='edge').astype(np.float32)
|
| 109 |
|
| 110 |
return image_1_padded, image_2_padded
|
| 111 |
|
| 112 |
|
| 113 |
def pad_displacement_map(disp_map: np.ndarray, crop_min: np.ndarray, crop_max: np.ndarray, output_shape: (np.ndarray, list)) -> np.ndarray:
|
| 114 |
+
ret_val = disp_map
|
| 115 |
+
if np.all([d != i for d, i in zip(disp_map.shape[:3], output_shape)]):
|
| 116 |
+
padding = [[crop_min[i], max(0, output_shape[i] - crop_max[i])] for i in range(3)] + [[0, 0]]
|
| 117 |
+
ret_val = np.pad(disp_map, padding, mode='constant')
|
| 118 |
+
return ret_val
|
| 119 |
|
| 120 |
|
| 121 |
def run_livermask(input_image_path, outputdir, filename: str = 'segmentation') -> np.ndarray:
|
| 122 |
+
assert find_spec('livermask'), 'Livermask is not available'
|
| 123 |
+
LOGGER.info('Getting parenchyma segmentations...')
|
| 124 |
shutil.copy2(input_image_path, os.path.join(outputdir, f'{filename}.nii.gz'))
|
| 125 |
livermask_cmd = "{} -m livermask.livermask --input {} --output {}".format(sys.executable,
|
| 126 |
input_image_path,
|
| 127 |
os.path.join(outputdir,
|
| 128 |
f'{filename}.nii.gz'))
|
| 129 |
subprocess.run(livermask_cmd)
|
| 130 |
+
LOGGER.info('done!')
|
| 131 |
segmentation_path = os.path.join(outputdir, f'{filename}.nii.gz')
|
| 132 |
return np.asarray(nib.load(segmentation_path).dataobj, dtype=int)
|
| 133 |
|
|
|
|
| 140 |
max_disp = np.max(disp_map_mod)
|
| 141 |
disp_map_mod = disp_map_mod - min_disp / (max_disp - min_disp)
|
| 142 |
disp_map_mod *= scale
|
| 143 |
+
LOGGER.debug('Scaled displacement map to [0., 1.] range')
|
| 144 |
return disp_map_mod
|
| 145 |
|
| 146 |
if debug:
|
|
|
|
| 148 |
if image.shape[-1] > 1:
|
| 149 |
image = disp_map_modulus(image, 1.)
|
| 150 |
save_nifti(image, os.path.join(outputdir, 'debug', filename+'.nii.gz'), verbose=False)
|
| 151 |
+
LOGGER.debug(f'Saved {filename} at {os.path.join(outputdir, filename + ".nii.gz")}')
|
| 152 |
|
| 153 |
|
| 154 |
def get_roi(image_filepath: str,
|
| 155 |
+
compute_segmentation: bool,
|
| 156 |
outputdir: str,
|
| 157 |
filename_filepath: str = 'segmentation',
|
| 158 |
segmentation_file: str = None,
|
| 159 |
debug: bool = False) -> list:
|
| 160 |
segm = None
|
| 161 |
+
if segmentation_file is None and compute_segmentation:
|
| 162 |
+
LOGGER.info(f'Computing segmentation using livermask. Only for liver in abdominal CTs')
|
| 163 |
+
try:
|
| 164 |
+
segm = run_livermask(image_filepath, outputdir, filename_filepath)
|
| 165 |
+
LOGGER.info(f'Loaded segmentation using livermask from {os.path.join(outputdir, filename_filepath)}')
|
| 166 |
+
except (AssertionError, FileNotFoundError) as er:
|
| 167 |
+
LOGGER.warning(er)
|
| 168 |
+
LOGGER.warning('No segmentation provided! Using the full volume')
|
| 169 |
+
pass
|
| 170 |
elif segmentation_file is not None:
|
| 171 |
segm = np.asarray(nib.load(segmentation_file).dataobj, dtype=int)
|
| 172 |
+
LOGGER.info(f'Loaded fixed segmentation from {segmentation_file}')
|
| 173 |
else:
|
| 174 |
+
LOGGER.warning('No segmentation provided! Using the full volume')
|
| 175 |
if segm is not None:
|
| 176 |
segm[segm > 0] = 1
|
| 177 |
ret_val = regionprops(segm)[0].bbox
|
| 178 |
debug_save_image(segm, f'img_1_{filename_filepath}', outputdir, debug)
|
| 179 |
else:
|
| 180 |
ret_val = [0, 0, 0] + list(nib.load(image_filepath).shape[:3])
|
| 181 |
+
LOGGER.debug(f'ROI found at coordinates {ret_val}')
|
| 182 |
return ret_val
|
| 183 |
|
| 184 |
|
| 185 |
+
def main():
|
| 186 |
parser = argparse.ArgumentParser()
|
| 187 |
parser.add_argument('-f', '--fixed', type=str, help='Path to fixed image file (NIfTI)')
|
| 188 |
parser.add_argument('-m', '--moving', type=str, help='Path to moving segmentation image file (NIfTI)', default=None)
|
|
|
|
| 192 |
parser.add_argument('-o', '--outputdir', type=str, help='Output directory', default='./Registration_output')
|
| 193 |
parser.add_argument('-a', '--anatomy', type=str, help='Anatomical structure: liver (L) (Default) or brain (B)',
|
| 194 |
default='L')
|
| 195 |
+
parser.add_argument('-s', '--make-segmentation', action='store_true', help='Try to create a segmentation for liver in CT images', default=False)
|
| 196 |
parser.add_argument('--gpu', type=int,
|
| 197 |
help='In case of multi-GPU systems, limits the execution to the defined GPU number',
|
| 198 |
default=None)
|
| 199 |
parser.add_argument('--model', type=str, help='Which model to use: BL-N, BL-S, SG-ND, SG-NSD, UW-NSD, UW-NSDH',
|
| 200 |
default='UW-NSD')
|
| 201 |
parser.add_argument('--debug', '-d', action='store_true', help='Produce additional debug information', default=False)
|
| 202 |
+
parser.add_argument('-c', '--clear-outputdir', action='store_true', help='Clear output folder if this has content', 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 |
|
| 210 |
if os.path.exists(args.outputdir) and len(os.listdir(args.outputdir)):
|
| 211 |
+
if args.clear_outputdir:
|
| 212 |
erase = 'y'
|
| 213 |
else:
|
| 214 |
erase = input('Output directory is not empty, erase content? (y/n)')
|
|
|
|
| 223 |
log_format = '%(asctime)s [%(levelname)s]:\t%(message)s'
|
| 224 |
logging.basicConfig(filename=os.path.join(args.outputdir, 'log.log'), filemode='w',
|
| 225 |
format=log_format, datefmt='%Y-%m-%d %H:%M:%S')
|
| 226 |
+
|
| 227 |
stdout_handler = logging.StreamHandler(sys.stdout)
|
| 228 |
stdout_handler.setFormatter(logging.Formatter(log_format, datefmt='%Y-%m-%d %H:%M:%S'))
|
| 229 |
+
LOGGER.addHandler(stdout_handler)
|
| 230 |
if isinstance(args.gpu, int):
|
| 231 |
os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'
|
| 232 |
os.environ['CUDA_VISIBLE_DEVICES'] = str(args.gpu) # Check availability before running using 'nvidia-smi'
|
| 233 |
+
LOGGER.setLevel('INFO')
|
| 234 |
if args.debug:
|
| 235 |
+
LOGGER.setLevel('DEBUG')
|
| 236 |
+
LOGGER.debug('DEBUG MODE ENABLED')
|
| 237 |
|
| 238 |
# Load the file and preprocess it
|
| 239 |
+
LOGGER.info('Loading image files')
|
| 240 |
fixed_image_or = nib.load(args.fixed)
|
| 241 |
moving_image_or = nib.load(args.moving)
|
| 242 |
image_shape_or = np.asarray(fixed_image_or.shape)
|
|
|
|
| 247 |
debug_save_image(moving_image_or, 'img_0_loaded_moving_image', args.outputdir, args.debug)
|
| 248 |
|
| 249 |
# TF stuff
|
| 250 |
+
LOGGER.info('Setting up configuration')
|
| 251 |
config = tf.compat.v1.ConfigProto() # device_count={'GPU':0})
|
| 252 |
config.gpu_options.allow_growth = True
|
| 253 |
config.log_device_placement = False ## to log device placement (on which device the operation ran)
|
|
|
|
| 258 |
|
| 259 |
# Preprocess data
|
| 260 |
# 1. Run Livermask to get the mask around the liver in both the fixed and moving image
|
| 261 |
+
LOGGER.info('Getting ROI')
|
| 262 |
+
fixed_segm_bbox = get_roi(args.fixed, args.make_segmentation, args.outputdir,
|
| 263 |
'fixed_segmentation', args.fixedsegm, args.debug)
|
| 264 |
+
moving_segm_bbox = get_roi(args.moving, args.make_segmentation, args.outputdir,
|
| 265 |
'moving_segmentation', args.movingsegm, args.debug)
|
| 266 |
|
| 267 |
crop_min = np.amin(np.vstack([fixed_segm_bbox[:3], moving_segm_bbox[:3]]), axis=0)
|
|
|
|
| 289 |
debug_save_image(moving_image, 'img_3_preproc_moving_image', args.outputdir, args.debug)
|
| 290 |
|
| 291 |
# 3. Build the whole graph
|
| 292 |
+
LOGGER.info('Building TF graph')
|
| 293 |
### METRICS GRAPH ###
|
| 294 |
fix_img_ph = tf.compat.v1.placeholder(tf.float32, (1, None, None, None, 1), name='fix_img')
|
| 295 |
pred_img_ph = tf.compat.v1.placeholder(tf.float32, (1, None, None, None, 1), name='pred_img')
|
|
|
|
| 299 |
mse_tf = vxm.losses.MSE().loss(fix_img_ph, pred_img_ph)
|
| 300 |
ms_ssim_tf = MultiScaleStructuralSimilarity(max_val=1., filter_size=3).metric(fix_img_ph, pred_img_ph)
|
| 301 |
|
| 302 |
+
LOGGER.info(f'Using model: {"Brain" if args.anatomy == "B" else "Liver"} -> {args.model}')
|
| 303 |
+
MODEL_FILE = get_models_path(args.anatomy, args.model, os.getcwd()) # MODELS_FILE[args.anatomy][args.model]
|
| 304 |
|
| 305 |
# try:
|
| 306 |
# network = tf.keras.models.load_model(MODEL_FILE,
|
|
|
|
| 337 |
registration_model = network.get_registration_model()
|
| 338 |
deb_model = network.apply_transform
|
| 339 |
|
| 340 |
+
LOGGER.info('Computing registration')
|
| 341 |
with sess.as_default():
|
| 342 |
if args.debug:
|
| 343 |
registration_model.summary(line_length=C.SUMMARY_LINE_LENGTH)
|
| 344 |
+
LOGGER.info('Computing displacement map...')
|
| 345 |
time_disp_map_start = time.time()
|
| 346 |
# disp_map = registration_model.predict([moving_image[np.newaxis, ...], fixed_image[np.newaxis, ...]])
|
| 347 |
p, disp_map = network.predict([moving_image[np.newaxis, ...], fixed_image[np.newaxis, ...]])
|
| 348 |
time_disp_map_end = time.time()
|
| 349 |
+
LOGGER.info('\t... done')
|
| 350 |
debug_save_image(np.squeeze(disp_map), 'disp_map_0_raw', args.outputdir, args.debug)
|
| 351 |
debug_save_image(p[0, ...], 'img_4_net_pred_image', args.outputdir, args.debug)
|
| 352 |
# pred_image = min_max_norm(pred_image)
|
|
|
|
| 354 |
# fixed_image_isot = zoom(fixed_image[0, ...], zoom_factors, order=3)[np.newaxis, ...]
|
| 355 |
|
| 356 |
# Up sample the displacement map to the full res
|
| 357 |
+
LOGGER.info('Scaling displacement map...')
|
| 358 |
trf = np.eye(4)
|
| 359 |
np.fill_diagonal(trf, 1/zoom_factors)
|
| 360 |
disp_map = resize_displacement_map(np.squeeze(disp_map), None, trf)
|
|
|
|
| 363 |
debug_save_image(np.squeeze(disp_map_or), 'disp_map_2_padded', args.outputdir, args.debug)
|
| 364 |
disp_map_or = gaussian_filter(disp_map_or, 5)
|
| 365 |
debug_save_image(np.squeeze(disp_map_or), 'disp_map_3_smoothed', args.outputdir, args.debug)
|
| 366 |
+
LOGGER.info('\t... done')
|
| 367 |
|
| 368 |
+
LOGGER.info('Applying displacement map...')
|
| 369 |
time_pred_img_start = time.time()
|
| 370 |
pred_image = SpatialTransformer(interp_method='linear', indexing='ij', single_transform=False)([moving_image_or[np.newaxis, ...], disp_map_or[np.newaxis, ...]]).eval()
|
| 371 |
time_pred_img_end = time.time()
|
| 372 |
+
LOGGER.info('\t... done')
|
| 373 |
+
|
| 374 |
+
LOGGER.info('Computing metrics...')
|
| 375 |
ssim, ncc, mse, ms_ssim = sess.run([ssim_tf, ncc_tf, mse_tf, ms_ssim_tf],
|
| 376 |
{'fix_img:0': fixed_image_or[np.newaxis, ...], 'pred_img:0': pred_image})
|
| 377 |
ssim = np.mean(ssim)
|
|
|
|
| 380 |
|
| 381 |
save_nifti(pred_image, os.path.join(args.outputdir, 'pred_image.nii.gz'))
|
| 382 |
np.savez_compressed(os.path.join(args.outputdir, 'displacement_map.npz'), disp_map_or)
|
| 383 |
+
LOGGER.info('Predicted image (full image) and displacement map saved in: '.format(args.outputdir))
|
| 384 |
+
LOGGER.info(f'Displacement map prediction time: {time_disp_map_end - time_disp_map_start} s')
|
| 385 |
+
LOGGER.info(f'Predicted image time: {time_pred_img_end - time_pred_img_start} s')
|
| 386 |
|
| 387 |
+
LOGGER.info('Similarity metrics (Full image)\n------------------')
|
| 388 |
+
LOGGER.info('SSIM: {:.03f}'.format(ssim))
|
| 389 |
+
LOGGER.info('NCC: {:.03f}'.format(ncc))
|
| 390 |
+
LOGGER.info('MSE: {:.03f}'.format(mse))
|
| 391 |
+
LOGGER.info('MS SSIM: {:.03f}'.format(ms_ssim))
|
| 392 |
|
| 393 |
ssim, ncc, mse, ms_ssim = sess.run([ssim_tf, ncc_tf, mse_tf, ms_ssim_tf],
|
| 394 |
{'fix_img:0': fixed_image[np.newaxis, ...], 'pred_img:0': p})
|
| 395 |
ssim = np.mean(ssim)
|
| 396 |
ms_ssim = ms_ssim[0]
|
| 397 |
+
LOGGER.info('\nSimilarity metrics (ROI)\n------------------')
|
| 398 |
+
LOGGER.info('SSIM: {:.03f}'.format(ssim))
|
| 399 |
+
LOGGER.info('NCC: {:.03f}'.format(ncc))
|
| 400 |
+
LOGGER.info('MSE: {:.03f}'.format(mse))
|
| 401 |
+
LOGGER.info('MS SSIM: {:.03f}'.format(ms_ssim))
|
| 402 |
|
| 403 |
del registration_model
|
| 404 |
+
LOGGER.info('Done')
|
| 405 |
+
exit(0)
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
if __name__ == '__main__':
|
| 409 |
+
main()
|
DeepDeformationMapRegistration/utils/constants.py
CHANGED
|
@@ -523,3 +523,11 @@ GAMMA_AUGMENTATION = True
|
|
| 523 |
BRIGHTNESS_AUGMENTATION = False
|
| 524 |
NUM_CONTROL_PTS_AUG = 10
|
| 525 |
NUM_AUGMENTATIONS = 1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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-S': '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/model_downloader.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
# taken from: https://lenon.dev/blog/downloading-and-caching-large-files-using-python/
|
| 9 |
+
def download(url, destination_file):
|
| 10 |
+
headers = {}
|
| 11 |
+
|
| 12 |
+
if os.path.exists(destination_file):
|
| 13 |
+
mtime = os.path.getmtime(destination_file)
|
| 14 |
+
headers["if-modified-since"] = formatdate(mtime, usegmt=True)
|
| 15 |
+
|
| 16 |
+
response = requests.get(url, headers=headers, stream=True)
|
| 17 |
+
response.raise_for_status()
|
| 18 |
+
|
| 19 |
+
if response.status_code == requests.codes.not_modified:
|
| 20 |
+
return
|
| 21 |
+
|
| 22 |
+
if response.status_code == requests.codes.ok:
|
| 23 |
+
with open(destination_file, "wb") as f:
|
| 24 |
+
for chunk in response.iter_content(chunk_size=1048576):
|
| 25 |
+
f.write(chunk)
|
| 26 |
+
|
| 27 |
+
last_modified = response.headers.get("last-modified")
|
| 28 |
+
if last_modified:
|
| 29 |
+
new_mtime = parsedate_to_datetime(last_modified).timestamp()
|
| 30 |
+
os.utime(destination_file, times=(datetime.now().timestamp(), new_mtime))
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def get_models_path(anatomy: str, model_type: str, output_root_dir: str):
|
| 34 |
+
assert anatomy in ANATOMIES.keys(), 'Invalid anatomy'
|
| 35 |
+
assert model_type in MODEL_TYPES.keys(), 'Invalid model type'
|
| 36 |
+
anatomy = ANATOMIES[anatomy]
|
| 37 |
+
model_type = MODEL_TYPES[model_type]
|
| 38 |
+
url = 'https://github.com/jpdefrutos/DDMR/releases/download/trained-models/' + anatomy + '/' + model_type + '.h5'
|
| 39 |
+
file_path = os.path.join(output_root_dir, 'models', anatomy, model_type + '.h5')
|
| 40 |
+
if not os.path.exists(file_path):
|
| 41 |
+
os.makedirs(os.path.split(file_path)[0], exist_ok=True)
|
| 42 |
+
download(url, file_path)
|
| 43 |
+
return file_path
|
setup.py
CHANGED
|
@@ -1,14 +1,20 @@
|
|
| 1 |
from setuptools import find_packages, setup
|
| 2 |
import os
|
| 3 |
|
| 4 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
setup(
|
| 7 |
name='DeepDeformationMapRegistration',
|
| 8 |
py_modules=['DeepDeformationMapRegistration'],
|
| 9 |
-
packages=find_packages(include=['DeepDeformationMapRegistration', 'DeepDeformationMapRegistration.*']
|
|
|
|
| 10 |
version='1.0',
|
| 11 |
description='Deep-registration training toolkit',
|
|
|
|
| 12 |
author='Javier Pérez de Frutos',
|
| 13 |
classifiers=[
|
| 14 |
'Programming language :: Python :: 3',
|
|
@@ -17,10 +23,22 @@ setup(
|
|
| 17 |
],
|
| 18 |
python_requires='>=3.6',
|
| 19 |
install_requires=[
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
'tensorflow-gpu==1.14.0',
|
|
|
|
|
|
|
|
|
|
| 21 |
'tensorboard==1.14.0',
|
| 22 |
'nibabel==3.2.1',
|
| 23 |
'numpy==1.18.5',
|
| 24 |
-
|
| 25 |
-
|
|
|
|
|
|
|
| 26 |
)
|
|
|
|
| 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',
|
|
|
|
| 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 |
+
],
|
| 41 |
+
entry_points={
|
| 42 |
+
'console_scripts': ['ddmr=DeepDeformationMapRegistration.main:main']
|
| 43 |
+
}
|
| 44 |
)
|