MapMetricWrapper("L1_map", lambda x, y: torch.abs(x - y), average_method="mean", mask_keys=['mask2']), "L2": MetricWrapper("L2", MSELoss()), #"SSIM": SSIM3D(average_method="mean"), "SSIM_mask": SSIM3D(average_method="mean", mask_keys=["mask", "mask2"]), "SSIM_Wrapped": MetricWrapper("SSIM_wrapped", lambda x, y: functional_ssim(x, y, return_map=False), use_mask=True, mask_key="mask"), "ssim_base": MetricWrapper('SSIM_base', ssim3D) } motion_trsfm = RandomMotionFromTimeCourse(verbose=True, compare_to_original=True, metrics=metrics, oversampling_pct=0.0) dataset.set_transform(motion_trsfm) tf = dataset[0] computed_metrics = tf["T1"]["metrics"] print("Computed metrics: {}".format(computed_metrics)) ov(tf['T1']['data'].squeeze().numpy())
dataset_not = ImagesDataset(paths_dict, transform=None) dataload = torch.utils.data.DataLoader(dataset, num_workers=0, batch_size=1) dataloadnot = torch.utils.data.DataLoader(dataset_not, num_workers=0, batch_size=1) ddd = dataset[0] #next(iter(dataset)) ii = np.squeeze( ddd['image']['data'][0], axis=1) ddno = dataset_not[0] # dd= next(iter(dataload)) ddno = next(iter(dataloadnot)) ii = np.squeeze( dd['image']['data'][0,0,:],axis=1) iio = np.squeeze( ddno['image']['data'][0,0,:],axis=1) ov(ii) ov(iio) #save sample = dataset[0] output = dict(image=Path('/tmp/test_im.nii.gz'),label1=Path('/tmp/test_p1.nii.gz'),label2=Path('/tmp/test_p2.nii.gz')) dataset.save_sample(sample, output) #explore out_dir = '/data/romain/data_exemple/augment/' suj = [[ Image('T1','/data/romain/data_exemple/nifti_proc/PRISMA_MBB_DB/2017_03_07_DEV_236_MBB_DB_Pilote02/anat_S02_t1mpr_SAG_NSel_S176/cat12/s_S02_t1mpr_SAG_NSel_S176.nii.gz',INTENSITY), Image('mask','/data/romain/data_exemple/nifti_proc/PRISMA_MBB_DB/2017_03_07_DEV_236_MBB_DB_Pilote02/anat_S02_t1mpr_SAG_NSel_S176/cat12/mask_brain_erode_dilate.nii.gz',LABEL) ]] transforms = Compose((RandomBiasField(coefficients_range=(-0.5, 0.5),order=3, verbose=True), ))
def display_original_data(self, idx): volume = self.get_volume_nibabel(idx) ov(volume.get_data())
header=None) fpars = np.asarray(mvt) transforms = get_motion_transform() suj = [[ Image( 'T1', '/home/romain/QCcnn/motion_cati_brain_ms/brain_s_S02_Sag_MPRAGE.nii.gz', 'intensity'), ]] dataset = ImagesDataset(suj, transform=transforms) s = dataset[0] ov(s['T1']['data'][0]) tt = dataset.get_transform() plt.figure() plt.plot(tt.fitpars.T) dataset.save_sample( s, dict(T1='/home/romain/QCcnn/motion_cati_brain_ms/toto10.nii')) #look at distribution of metric on simulate motion dir_cache = '/network/lustre/dtlake01/opendata/data/ds000030/rrr/CNN_cache' dd = gdir(dir_cache, 'mask_mv') fr = gfile(dd, 'resul') name_res = get_parent_path(dd)[1] res = [pd.read_csv(ff) for ff in fr] sell_col = res[0].keys() sell_col = [
tmot.nufft_type = '1D_type2' tmot.preserve_center_frequency_pct = 0 tmot.nT = 218 tmot.maxGlobalDisp, tmot.maxGlobalRot = (4, 4), (3, 3) tmot._simulate_random_trajectory() plt.figure() plt.plot(tmot.fitpars.T) fitpar = tmot.fitpars tmot.fitpars = fitpar tmot.simulate_displacement = False # True; # tmot.oversampling_pct = 1 smot = tmot(sdata) fitpar = tmot.fitpars ov(smot.t1.data[0]) #fitpar = interpolate_fitpars(tmot.fitpars, len_output=image.shape[1]) import finufft def nufft_type1(freq_domain, fitpar, trans_last=False): #trans_last=False #weird idea while looking to match tio.Affine ... no more usefull eps = 1E-7 f = np.zeros(image.shape, dtype=np.complex128, order='F') lin_spaces = [ np.linspace(-0.5, 0.5 - 1 / x, x) * 2 * math.pi for x in freq_domain.shape ] # todo it suposes 1 vox = 1mm #remove 1/x to avoid small scaling
trans_torch = np.array(trans)/(image_size/2) mr = create_rotation_matrix_3d(rot) ms = np.diag(scale) center = np.ceil(image_size/2) center = center.T - [email protected] center_mat=np.zeros([4,4]) center_mat[0:3,3] = center[0:3].T maff = np.hstack((ms @ mr,np.expand_dims(trans,0).T)) maff_torch = np.hstack((ms @ mr,trans_torch.T)) maff = np.vstack((maff,[0,0,0,1])) nib_fin = nib.Nifti1Image(ii.numpy()[0], affine) new_aff = affine @ np.linalg.inv(maff+center_mat) #new_aff = maff @ affine # other way round new_aff = affine@maff nib_fin.affine[:] = new_aff[:] fout = nbp.resample_from_to(nib_fin, (nib_fin.shape, affine), cval=-1) #fout = nbp.resample_from_to(nib_fin, (nib_fin.shape, new_aff), cval=-1) ov(fout.get_fdata()) #it gives almost the same, just the scalling is shifted with nibabel (whereas it is centred with torch mafft = maff_torch[np.newaxis,:] mafft = torch.from_numpy(mafft) x = ii.permute(0,3,2,1).unsqueeze(0) grid = F.affine_grid(mafft, x.shape, align_corners=False).float() x = F.grid_sample(x, grid, align_corners=False) xx = x[0,0].numpy().transpose(2,1,0) ov(xx) # make the inverse transform xx=torch.zeros(4,4); xx[3,3]=1 xx[0:3,0:4] = mafft[0] imaf = xx.inverse()