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 |
+
import numpy as np
|
| 4 |
+
import DeepDeformationMapRegistration.utils.constants as C
|
| 5 |
+
import os
|
| 6 |
+
from tqdm import tqdm
|
| 7 |
+
import re
|
| 8 |
+
|
| 9 |
+
from DeepDeformationMapRegistration.losses import StructuralSimilarity_simplified, NCC, GeneralizedDICEScore, HausdorffDistanceErosion, target_registration_error
|
| 10 |
+
from DeepDeformationMapRegistration.ms_ssim_tf import MultiScaleStructuralSimilarity
|
| 11 |
+
from DeepDeformationMapRegistration.utils.misc import DisplacementMapInterpolator, segmentation_ohe_to_cardinal
|
| 12 |
+
|
| 13 |
+
from argparse import ArgumentParser
|
| 14 |
+
|
| 15 |
+
import tensorflow as tf
|
| 16 |
+
|
| 17 |
+
DATASET_LOCATION = '/mnt/EncryptedData1/Users/javier/vessel_registration/3Dirca/dataset/EVAL'
|
| 18 |
+
DATASET_NAMES = 'test_sample_\d{4}.h5'
|
| 19 |
+
DATASET_FILENAME = 'volume'
|
| 20 |
+
IMGS_FOLDER = '/home/jpdefrutos/workspace/DeepDeformationMapRegistration/Centerline/imgs'
|
| 21 |
+
|
| 22 |
+
WARPED_MOV = 'warpedmovout'
|
| 23 |
+
WARPED_FIX = 'warpedfixout'
|
| 24 |
+
FWD_TRFS = 'fwdtransforms'
|
| 25 |
+
INV_TRFS = 'invtransforms'
|
| 26 |
+
|
| 27 |
+
if __name__ == '__main__':
|
| 28 |
+
parser = ArgumentParser()
|
| 29 |
+
parser.add_argument('--dataset', type=str, help='Directory with the images')
|
| 30 |
+
parser.add_argument('--outdir', type=str, help='Output directory')
|
| 31 |
+
args = parser.parse_args()
|
| 32 |
+
|
| 33 |
+
dataset_files = os.listdir(args.dataset)
|
| 34 |
+
dataset_files.sort()
|
| 35 |
+
dataset_files = [os.path.join(args.dataset, f) for f in dataset_files if re.match(DATASET_NAMES, f)]
|
| 36 |
+
|
| 37 |
+
dataset_iterator = tqdm(dataset_files)
|
| 38 |
+
|
| 39 |
+
f = h5py.File(dataset_files[0], 'r')
|
| 40 |
+
image_output_shape = list(f['fix_image'][:].shape[:-1])
|
| 41 |
+
f.close()
|
| 42 |
+
|
| 43 |
+
#### TF prep
|
| 44 |
+
metric_fncs = [StructuralSimilarity_simplified(patch_size=2, dim=3, dynamic_range=1.).metric,
|
| 45 |
+
NCC(image_input_shape).metric,
|
| 46 |
+
vxm.losses.MSE().loss,
|
| 47 |
+
MultiScaleStructuralSimilarity(max_val=1., filter_size=3).metric,
|
| 48 |
+
GeneralizedDICEScore(image_output_shape + [nb_labels], num_labels=nb_labels).metric,
|
| 49 |
+
HausdorffDistanceErosion(3, 10, im_shape=image_output_shape + [nb_labels]).metric,
|
| 50 |
+
GeneralizedDICEScore(image_output_shape + [nb_labels], num_labels=nb_labels).metric_macro]
|
| 51 |
+
|
| 52 |
+
fix_img_ph = tf.placeholder(tf.float32, (1, *image_output_shape, 1), name='fix_img')
|
| 53 |
+
pred_img_ph = tf.placeholder(tf.float32, (1, *image_output_shape, 1), name='pred_img')
|
| 54 |
+
fix_seg_ph = tf.placeholder(tf.float32, (1, *image_output_shape, nb_labels), name='fix_seg')
|
| 55 |
+
pred_seg_ph = tf.placeholder(tf.float32, (1, *image_output_shape, nb_labels), name='pred_seg')
|
| 56 |
+
|
| 57 |
+
ssim_tf = metric_fncs[0](fix_img_ph, pred_img_ph)
|
| 58 |
+
ncc_tf = metric_fncs[1](fix_img_ph, pred_img_ph)
|
| 59 |
+
mse_tf = metric_fncs[2](fix_img_ph, pred_img_ph)
|
| 60 |
+
ms_ssim_tf = metric_fncs[3](fix_img_ph, pred_img_ph)
|
| 61 |
+
dice_tf = metric_fncs[4](fix_seg_ph, pred_seg_ph)
|
| 62 |
+
hd_tf = metric_fncs[5](fix_seg_ph, pred_seg_ph)
|
| 63 |
+
dice_macro_tf = metric_fncs[6](fix_seg_ph, pred_seg_ph)
|
| 64 |
+
|
| 65 |
+
config = tf.compat.v1.ConfigProto() # device_count={'GPU':0})
|
| 66 |
+
config.gpu_options.allow_growth = True
|
| 67 |
+
config.log_device_placement = False ## to log device placement (on which device the operation ran)
|
| 68 |
+
config.allow_soft_placement = True
|
| 69 |
+
|
| 70 |
+
sess = tf.Session(config=config)
|
| 71 |
+
tf.keras.backend.set_session(sess)
|
| 72 |
+
####
|
| 73 |
+
dm_interp = DisplacementMapInterpolator(image_output_shape, 'griddata')
|
| 74 |
+
|
| 75 |
+
metrics_file = os.path.join(output_folder, 'metrics.csv')
|
| 76 |
+
|
| 77 |
+
for file_path in dataset_iterator:
|
| 78 |
+
file_num = int(re.findall('(\d+)', os.path.split(file_path)[-1])[0])
|
| 79 |
+
|
| 80 |
+
dataset_iterator.set_description('{} ({}): laoding data'.format(file_num, dataset_name))
|
| 81 |
+
with h5py.File(file_path, 'r') as vol_file:
|
| 82 |
+
fix_img = vol_file['fix_image'][:]
|
| 83 |
+
mov_img = vol_file['mov_image'][:]
|
| 84 |
+
|
| 85 |
+
fix_seg = vol_file['fix_segmentations'][:]
|
| 86 |
+
mov_seg = vol_file['mov_segmentations'][:]
|
| 87 |
+
|
| 88 |
+
fix_centroid = vol_file['fix_centroids'][:]
|
| 89 |
+
mov_centroid = vol_file['mov_centroids'][:]
|
| 90 |
+
|
| 91 |
+
# ndarray to ANTsImage
|
| 92 |
+
fix_img = ants.make_image(fix_img.shape, fix_img)
|
| 93 |
+
mov_img = ants.make_image(mov_img.shape, mov_img)
|
| 94 |
+
|
| 95 |
+
reg_output_syn = ants.registration(fix_img, mov_img, 'SyN')
|
| 96 |
+
reg_output_syncc = ants.registration(fix_img, mov_img, 'SyNCC')
|
| 97 |
+
mov_to_fix_trf_syn = reg_output_syn[FWD_TRFS]
|
| 98 |
+
mov_to_fix_trf_syncc = reg_output_syn[FWD_TRFS]
|
| 99 |
+
if not len(mov_to_fix_trf_syn) and not len(mov_to_fix_trf_syncc):
|
| 100 |
+
print('ERR: Registration failed for: '+file_path)
|
| 101 |
+
else:
|
| 102 |
+
for reg_output in [reg_output_syn, reg_output_syncc]:
|
| 103 |
+
mov_to_fix_trf = reg_output[FWD_TRFS]
|
| 104 |
+
pred_img = reg_output[WARPED_MOV].numpy()
|
| 105 |
+
pred_seg = mov_to_fix_trf.apply_to_image(ants.make_image(mov_seg.shape, mov_seg)).numpy()
|
| 106 |
+
|
| 107 |
+
with sess.as_default():
|
| 108 |
+
dice, hd, dice_macro = sess.run([dice_tf, hd_tf, dice_macro_tf],
|
| 109 |
+
{'fix_seg:0': fix_seg, 'pred_seg:0': pred_seg})
|
| 110 |
+
|
| 111 |
+
pred_seg_card = segmentation_ohe_to_cardinal(pred_seg).astype(np.float32)
|
| 112 |
+
mov_seg_card = segmentation_ohe_to_cardinal(mov_seg).astype(np.float32)
|
| 113 |
+
fix_seg_card = segmentation_ohe_to_cardinal(fix_seg).astype(np.float32)
|
| 114 |
+
|
| 115 |
+
ssim, ncc, mse, ms_ssim = sess.run([ssim_tf, ncc_tf, mse_tf, ms_ssim_tf],
|
| 116 |
+
{'fix_img:0': fix_img, 'pred_img:0': pred_img})
|
| 117 |
+
ms_ssim = ms_ssim[0]
|
| 118 |
+
tf.keras.backend.clear_session()
|
| 119 |
+
|
| 120 |
+
# TRE
|
| 121 |
+
pred_centroids = dm_interp(mov_to_fix_trf.numpy(), mov_centroid, backwards=True) + mov_centroid
|
| 122 |
+
upsample_scale = 128 / 64
|
| 123 |
+
fix_centroids_isotropic = fix_centroids * upsample_scale
|
| 124 |
+
pred_centroids_isotropic = pred_centroids * upsample_scale
|
| 125 |
+
|
| 126 |
+
fix_centroids_isotropic = np.divide(fix_centroids_isotropic, C.IXI_DATASET_iso_to_cubic_scales)
|
| 127 |
+
pred_centroids_isotropic = np.divide(pred_centroids_isotropic, C.IXI_DATASET_iso_to_cubic_scales)
|
| 128 |
+
tre_array = target_registration_error(fix_centroids_isotropic, pred_centroids_isotropic, False).eval()
|
| 129 |
+
tre = np.mean([v for v in tre_array if not np.isnan(v)])
|
| 130 |
+
|
| 131 |
+
new_line = [step, ssim, ms_ssim, ncc, mse, dice, dice_macro, hd, t1-t0, tre, len(missing_lbls), missing_lbls]
|
| 132 |
+
with open(metrics_file, 'a') as f:
|
| 133 |
+
f.write(';'.join(map(str, new_line))+'\n')
|
| 134 |
+
|
| 135 |
+
save_nifti(fix_img[0, ...], os.path.join(output_folder, '{:03d}_fix_img_ssim_{:.03f}_dice_{:.03f}.nii.gz'.format(step, ssim, dice)), verbose=False)
|
| 136 |
+
save_nifti(mov_img[0, ...], os.path.join(output_folder, '{:03d}_mov_img_ssim_{:.03f}_dice_{:.03f}.nii.gz'.format(step, ssim, dice)), verbose=False)
|
| 137 |
+
save_nifti(pred_img[0, ...], os.path.join(output_folder, '{:03d}_pred_img_ssim_{:.03f}_dice_{:.03f}.nii.gz'.format(step, ssim, dice)), verbose=False)
|
| 138 |
+
save_nifti(fix_seg_card[0, ...], os.path.join(output_folder, '{:03d}_fix_seg_ssim_{:.03f}_dice_{:.03f}.nii.gz'.format(step, ssim, dice)), verbose=False)
|
| 139 |
+
save_nifti(mov_seg_card[0, ...], os.path.join(output_folder, '{:03d}_mov_seg_ssim_{:.03f}_dice_{:.03f}.nii.gz'.format(step, ssim, dice)), verbose=False)
|
| 140 |
+
save_nifti(pred_seg_card[0, ...], os.path.join(output_folder, '{:03d}_pred_seg_ssim_{:.03f}_dice_{:.03f}.nii.gz'.format(step, ssim, dice)), verbose=False)
|
| 141 |
+
|
| 142 |
+
plot_predictions(fix_img, mov_img, disp_map, pred_img, os.path.join(output_folder, '{:03d}_figures_img.png'.format(step)), show=False)
|
| 143 |
+
plot_predictions(fix_seg, mov_seg, disp_map, pred_seg, os.path.join(output_folder, '{:03d}_figures_seg.png'.format(step)), show=False)
|
| 144 |
+
save_disp_map_img(disp_map, 'Displacement map', os.path.join(output_folder, '{:03d}_disp_map_fig.png'.format(step)), show=False)
|
| 145 |
+
|
| 146 |
+
print('Summary\n=======\n')
|
| 147 |
+
print('\nAVG:\n' + str(pd.read_csv(metrics_file, sep=';', header=0).mean(axis=0)) + '\nSTD:\n' + str(
|
| 148 |
+
pd.read_csv(metrics_file, sep=';', header=0).std(axis=0)))
|
| 149 |
+
print('\n=======\n')
|