def test_largest_cc_img(): """ Check the extraction of the largest connected component, for niftis Similiar to smooth_img tests for largest connected_component_img, here also only the added features for largest_connected_component are tested. """ # Test whether dimension of 3Dimg and list of 3Dimgs are kept. shapes = ((10, 11, 12), (13, 14, 15)) regions = [1, 3] img1 = testing.generate_labeled_regions(shape=shapes[0], n_regions=regions[0]) img2 = testing.generate_labeled_regions(shape=shapes[1], n_regions=regions[1]) for create_files in (False, True): with testing.write_tmp_imgs(img1, img2, create_files=create_files) as imgs: # List of images as input out = largest_connected_component_img(imgs) assert_true(isinstance(out, list)) assert_true(len(out) == 2) for o, s in zip(out, shapes): assert_true(o.shape == (s)) # Single image as input out = largest_connected_component_img(imgs[0]) assert_true(isinstance(out, Nifti1Image)) assert_true(out.shape == (shapes[0])) # Test whether 4D Nifti throws the right error. img_4D = testing.generate_fake_fmri(shapes[0], length=17) assert_raises(DimensionError, largest_connected_component_img, img_4D)
def get_largest_two_comps(in_img, out_comps): """ Get the two largest connected components :param in_img: input image :param out_comps: output image with two components """ first_comp = largest_connected_component_img(in_img) residual = math_img('img1 - img2', img1=in_img, img2=first_comp) second_comp = largest_connected_component_img(residual) comb_comps = math_img('img1 + img2', img1=first_comp, img2=second_comp) nib.save(comb_comps, out_comps)
def _run_interface(self, runtime): import os.path as op import nibabel.gifti as ng import numpy as np import skimage.measure as sm import nilearn.image as nimg import slam.io as sio import slam.differential_geometry as sdg from nipype.utils.filemanip import split_filename # Generate output mesh filename from the input image name _, fname, _ = split_filename(self.inputs.image_file) gii_file = op.abspath(op.join(runtime.cwd, fname + ".gii")) # Load the largest connected component of the input image img = nimg.largest_connected_component_img(self.inputs.image_file) # TODO: check if the input image is correct (binary) # Run the marching cube algorithm verts, faces, normals, values = sm.marching_cubes_lewiner( img.get_data(), self.inputs.level) # Convert vertices coordinates to image space # TODO: check that is correct by plotting the mesh on the image x, y, z = nimg.coord_transform(verts[:, 0], verts[:, 1], verts[:, 2], img.affine) mm_verts = np.array([x, y, z]).T # Save the mesh as Gifti # FIXME: FreeView can not open the mesh (but anatomist do) gii = ng.GiftiImage(darrays=[ ng.GiftiDataArray(mm_verts, intent='NIFTI_INTENT_POINTSET'), ng.GiftiDataArray(faces, intent='NIFTI_INTENT_TRIANGLE') ]) gii.meta = ng.GiftiMetaData().from_dict({ "volume_file": self.inputs.image_file, "marching_cube_level": str(self.inputs.level), "smoothing_iterations": str(self.inputs.smoothing_iter), "smoothing_dt": str(self.inputs.smoothing_dt) }) ng.write(gii, gii_file) # Optional: Smooth the marching cube output with SLAM if self.inputs.smoothing_iter > 0: mesh = sdg.laplacian_mesh_smoothing( sio.load_mesh(gii_file), nb_iter=self.inputs.smoothing_iter, dt=self.inputs.smoothing_dt) sio.write_mesh(mesh, gii_file) return runtime
def largest_component(input_image): from nilearn import image from nipype.utils.filemanip import split_filename import os _, fn, ext = split_filename(input_image) output_image = image.largest_connected_component_img(input_image) output_image.to_filename(os.path.abspath('{fn}_largestcomponent{ext}'.format(fn=fn, ext=ext))) return output_image.get_filename()
def test_largest_cc_img(): """ Check the extraction of the largest connected component, for niftis Similiar to smooth_img tests for largest connected_component_img, here also only the added features for largest_connected_component are tested. """ # Test whether dimension of 3Dimg and list of 3Dimgs are kept. shapes = ((10, 11, 12), (13, 14, 15)) regions = [1, 3] img1 = testing.generate_labeled_regions(shape=shapes[0], n_regions=regions[0]) img2 = testing.generate_labeled_regions(shape=shapes[1], n_regions=regions[1]) for create_files in (False, True): with testing.write_tmp_imgs(img1, img2, create_files=create_files) as imgs: # List of images as input out = largest_connected_component_img(imgs) assert_true(isinstance(out, list)) assert_true(len(out) == 2) for o, s in zip(out, shapes): assert_true(o.shape == (s)) # Single image as input out = largest_connected_component_img(imgs[0]) assert_true(isinstance(out, Nifti1Image)) assert_true(out.shape == (shapes[0])) # Test whether 4D Nifti throws the right error. img_4D = testing.generate_fake_fmri(shapes[0], length=17) assert_raises(DimensionError, largest_connected_component_img, img_4D) # tests adapted to non-native endian data dtype img1_change_dtype = nibabel.Nifti1Image(img1.get_data().astype('>f8'), affine=img1.affine) img2_change_dtype = nibabel.Nifti1Image(img2.get_data().astype('>f8'), affine=img2.affine) for create_files in (False, True): with testing.write_tmp_imgs(img1_change_dtype, img2_change_dtype, create_files=create_files) as imgs: # List of images as input out = largest_connected_component_img(imgs) assert_true(isinstance(out, list)) assert_true(len(out) == 2) for o, s in zip(out, shapes): assert_true(o.shape == (s)) # Single image as input out = largest_connected_component_img(imgs[0]) assert_true(isinstance(out, Nifti1Image)) assert_true(out.shape == (shapes[0])) # Test the output with native and without native out_native = largest_connected_component_img(img1) out_non_native = largest_connected_component_img(img1_change_dtype) np.testing.assert_equal(out_native.get_data(), out_non_native.get_data())
def main(args): parser = parsefn() subj_dir, subj, t1, fl, t2, woc, out, bias, num_mc, thresh, ign_ort, force = parse_inputs( parser, args) cp_orient = False if out is None: prediction = '%s/%s_T1acq_nu_HfB_pred.nii.gz' % (subj_dir, subj) \ # if bias is True else '%s/%s_T1acq_HfB_pred.nii.gz' % (subj_dir, subj) prediction_std_orient = '%s/%s_T1acq_nu_HfB_pred_std_orient.nii.gz' % ( subj_dir, subj) else: prediction = out prediction_std_orient = "%s/%s_std_orient.nii.gz" % ( subj_dir, os.path.basename(out).split('.')[0]) if os.path.exists(prediction) and force is False: print("\n %s already exists" % prediction) else: start_time = datetime.now() hfb = os.path.realpath(__file__) hyper_dir = Path(hfb).parents[2] if fl is None and t2 is None: test_seqs = [t1] training_mods = ["t1"] model_name = 'hfb_t1only_mcdp' model_name_woc = 'hfb_t1' print("\n found only t1-w, using the %s model" % model_name) elif t2 is None and fl: test_seqs = [t1, fl] training_mods = ["t1", "flair"] model_name = 'hfb_t1fl_mcdp' model_name_woc = 'hfb_t1fl' print("\n found t1 and fl sequences, using the %s model" % model_name) elif fl is None and t2: test_seqs = [t1, t2] training_mods = ["t1", "t2"] model_name = 'hfb_t1t2_mcdp' model_name_woc = 'hfb_t1t2' print("\n found t1 and t2 sequences, using the %s model" % model_name) else: test_seqs = [t1, fl, t2] training_mods = ["t1", "flair", "t2"] model_name = 'hfb_multi_mcdp' model_name_woc = 'hfb' print("\n found all 3 sequences, using the full %s model" % model_name) model_json = '%s/models/%s_model.json' % (hyper_dir, model_name) model_weights = '%s/models/%s_model_weights.h5' % (hyper_dir, model_name) assert os.path.exists( model_json ), "%s does not exist ... please download and rerun script" % model_json assert os.path.exists( model_weights ), "%s does not exist ... please download and rerun script" % model_weights # pred preprocess dir print( colored("\n pre-processing %s..." % os.path.abspath(subj_dir), 'green')) pred_dir = "%s/pred_process" % os.path.abspath(subj_dir) if not os.path.exists(pred_dir): os.mkdir(pred_dir) ############# # bias correction if requested if bias is True: t1_bias = os.path.join(subj_dir, "%s_T1_nu.nii.gz" % subj) biascorr.main(["-i", "%s" % t1, "-o", "%s" % t1_bias]) in_ort = t1_bias else: in_ort = t1 # std orientations r_orient = 'RPI' l_orient = 'LPI' # check orientation t1_ort = "%s/%s_std_orient.nii.gz" % ( subj_dir, os.path.basename(t1).split('.')[0]) if ign_ort is False: cp_orient = check_orient(in_ort, r_orient, l_orient, t1_ort) # loading t1 in_t1 = t1_ort if os.path.exists(t1_ort) else in_ort t1_img = nib.load(in_t1) ########### c3 = C3d() pred_shape = [128, 128, 128] test_data = np.zeros((1, len(training_mods), pred_shape[0], pred_shape[1], pred_shape[2]), dtype=t1_img.get_data_dtype()) for s, seq in enumerate(test_seqs): print( colored( "\n pre-processing %s" % os.path.basename(seq).split('.')[0], 'green')) seq_ort = "%s/%s_std_orient.nii.gz" % ( subj_dir, os.path.basename(seq).split('.')[0]) if training_mods[s] != 't1': if training_mods[s] == 'flair': seq_bias = os.path.join(subj_dir, "%s_T1acq_nu_FL.nii.gz" % subj) else: seq_bias = os.path.join(subj_dir, "%s_T1acq_nu_T2.nii.gz" % subj) # bias correction if requested if bias is True: biascorr.main(["-i", "%s" % seq, "-o", "%s" % seq_bias]) seq = seq_bias if os.path.exists(seq_bias) else seq # check orientation if ign_ort is False: cp_orient_seq = check_orient(seq, r_orient, l_orient, seq_ort) in_seq = seq_ort if os.path.exists(seq_ort) else seq image = nib.load(in_seq) img = image.get_data() # standardize intensity for data print("\n standardizing ...") std_img = (img - img.mean()) / img.std() std_file = '%s/%s_standardized.nii.gz' % ( pred_dir, os.path.basename(seq).split('.')[0]) nib.save(nib.Nifti1Image(std_img, t1_img.affine), std_file) # cropping if training_mods[s] == 't1': crop_file = '%s/%s_standardized_cropped.nii.gz' % ( pred_dir, os.path.basename(seq).split('.')[0]) trim(std_file, crop_file, voxels=1) else: crop_file = '%s/%s_standardized_cropped.nii.gz' % ( pred_dir, os.path.basename(seq).split('.')[0]) ref_file = '%s/%s_standardized_cropped.nii.gz' % ( pred_dir, os.path.basename(t1).split('.')[0]) trim_like(std_file, ref_file, crop_file, interp=1) #resampling # img = nib.load(crop_file) # res = resample(img, [pred_shape[0], pred_shape[1], pred_shape[2]]) # res_file = '%s/%s_resampled.nii.gz' % (pred_dir, os.path.basename(seq).split('.')[0]) # nib.save(res, res_file) res_file = '%s/%s_resampled.nii.gz' % ( pred_dir, os.path.basename(seq).split('.')[0]) resample(crop_file, pred_shape[0], pred_shape[1], pred_shape[2], res_file, interp=1) if not os.path.exists(res_file): print("\n pre-processing %s" % training_mods[s]) c3.run() res_data = nib.load(res_file) test_data[0, s, :, :, :] = res_data.get_data() print( colored( "\n predicting hfb segmentation using MC Dropout with %s samples" % num_mc, 'green')) res_t1_file = '%s/%s_resampled.nii.gz' % ( pred_dir, os.path.basename(t1).split('.')[0]) res = nib.load(res_t1_file) pred_s = np.zeros( (num_mc, pred_shape[0], pred_shape[1], pred_shape[2]), dtype=res.get_data_dtype()) for sample_id in range(num_mc): print("MC sample # %s" % sample_id) pred = run_test_case(test_data=test_data, model_json=model_json, model_weights=model_weights, affine=res.affine, output_label_map=True, labels=1) pred_s[sample_id, :, :, :] = pred.get_data() # computing mean pred_mean = pred_s.mean(axis=0) pred = nib.Nifti1Image(pred_mean, res.affine) pred_prob = os.path.join(pred_dir, "hfb_prob.nii.gz") nib.save(pred, pred_prob) pred_th_name = os.path.join(pred_dir, "hfb_pred.nii.gz") pred_th = math_img('img > %s' % thresh, img=pred) nib.save(pred_th, pred_th_name) # resample back pred_res = resample_to_img(pred_prob, t1_img) pred_prob_name = os.path.join( pred_dir, "%s_%s_pred_prob.nii.gz" % (subj, model_name)) nib.save(pred_res, pred_prob_name) # sm pred_sm = smooth_img(pred_res, fwhm=3) pred_res_th = math_img('img > %s' % thresh, img=pred_sm) # conn comp pred_comp = largest_connected_component_img(pred_res_th) pred_name = os.path.join(pred_dir, "%s_%s_pred.nii.gz" % (subj, model_name)) nib.save(pred_comp, pred_name) # copy original orientation to final prediction if ign_ort is False and cp_orient: nib.save(pred_comp, prediction_std_orient) fill_holes(prediction_std_orient, prediction_std_orient) copy_orient(pred_name, in_ort, prediction) fill_holes(prediction, prediction) else: nib.save(pred_comp, prediction) fill_holes(prediction, prediction) # mask t1_masked_name = '%s/%s_T1_nu_masked.nii.gz' % (subj_dir, subj) \ if bias is True else '%s/%s_masked.nii.gz' % (subj_dir, os.path.basename(t1).split('.')[0]) masked_t1 = math_img("img1 * img2", img1=nib.load(in_ort), img2=nib.load(prediction)) nib.save(masked_t1, t1_masked_name) if ign_ort is False and cp_orient: t1_masked_name_std = '%s/%s_T1_nu_masked_std_orient.nii.gz' % (subj_dir, subj) \ if bias is True else '%s/%s_masked_std_orient.nii.gz' % (subj_dir, os.path.basename(t1).split('.')[0]) masked_t1_std = math_img("img1 * img2", img1=t1_img, img2=nib.load(prediction_std_orient)) nib.save(masked_t1_std, t1_masked_name_std) # predict cerebellum if woc == 1 and model_name_woc == 'hfb': print("\n predicting approximate cerebellar mask") cereb_prediction = '%s/%s_T1acq_nu_cerebellum_pred.nii.gz' % (subj_dir, subj) \ if bias is True else '%s/%s_T1acq_cerebellum_pred.nii.gz' % (subj_dir, subj) model_json_woc = '%s/models/%s_model.json' % (hyper_dir, model_name_woc) cereb_weights = '%s/models/cereb_model_weights.h5' % hyper_dir cereb_pred = run_test_case(test_data=test_data, model_json=model_json_woc, model_weights=cereb_weights, affine=res.affine, output_label_map=True, labels=1) # resample back cereb_pred_res = resample_to_img(cereb_pred, t1_img) cereb_pred_name = os.path.join("%s/%s_hfb_cereb_pred_prob.nii.gz" % (pred_dir, subj)) nib.save(cereb_pred_res, cereb_pred_name) cereb_sm = smooth_img(cereb_pred_res, fwhm=2) cereb_th = math_img('img > 0.25', img=cereb_sm) nib.save(cereb_th, cereb_prediction) # remove cerebellum woc_img = pred_comp.get_data() - cereb_th.get_data() woc_nii = nib.Nifti1Image(woc_img, t1_img.affine) # conn comp woc_th = math_img('img > 0', img=woc_nii) woc_comp = largest_connected_component_img(woc_th) woc_name = os.path.join( pred_dir, "%s_%s_woc_pred.nii.gz" % (subj, model_name)) nib.save(woc_comp, woc_name) woc_pred = '%s/%s_T1acq_nu_HfB_woc_pred.nii.gz' % (subj_dir, subj) \ if bias is True else '%s/%s_T1acq_HfB_woc_pred.nii.gz' % (subj_dir, subj) woc_pred_std_orient = '%s/%s_T1acq_nu_HfB_woc_pred_std_orient.nii.gz' % ( subj_dir, subj) if ign_ort is False and cp_orient: nib.save(woc_comp, woc_pred_std_orient) fill_holes(woc_pred_std_orient, woc_pred_std_orient) copy_orient(woc_name, in_ort, woc_pred) fill_holes(woc_pred, woc_pred) else: nib.save(woc_comp, woc_pred) fill_holes(woc_pred, woc_pred) # mask t1_woc_name = '%s/%s_T1_nu_masked_woc.nii.gz' % (subj_dir, subj) \ if bias is True else '%s/%s_masked_woc.nii.gz' % (subj_dir, os.path.basename(t1).split('.')[0]) woc_t1 = math_img("img1 * img2", img1=nib.load(in_ort), img2=nib.load(woc_pred)) nib.save(woc_t1, t1_woc_name) if ign_ort is False and cp_orient: t1_woc_name = '%s/%s_T1_nu_masked_woc_std_orient.nii.gz' % (subj_dir, subj) \ if bias is True else '%s/%s_masked_woc_std_orient.nii.gz' % (subj_dir, os.path.basename(t1).split('.')[0]) woc_t1 = math_img("img1 * img2", img1=t1_img, img2=nib.load(woc_pred_std_orient)) nib.save(woc_t1, t1_woc_name) else: print( 'Removing cerebellum is available only when all 3 sequence t1, flair, and t2 have existed.' ) print("\n generating mosaic image for qc") seg_qc.main( ["-i", "%s" % t1, "-s", "%s" % prediction, "-g", "5", "-m", "75"]) endstatement.main('Brain extraction and mosaic generation', '%s' % (datetime.now() - start_time))
def main(sourcedata, derivatives, subject): manual_outside_mask = get_derivative(derivatives, 'manual_segmentation', 'anat', subject, 'mask', description='outside', session='anat', check_exists=True, space='average') manual_inside_mask = get_derivative(derivatives, 'manual_segmentation', 'anat', subject, 'mask', description='gm', session='anat', check_exists=True, space='average') manual_wm_mask = get_derivative(derivatives, 'manual_segmentation', 'anat', subject, 'mask', description='wm', session='anat', check_exists=False, space='average') freesurfer_brainmask_auto = op.join( derivatives, 'freesurfer', 'sub-{subject}', 'mri', 'brainmask.auto.mgz').format(**locals()) freesurfer_brainmask = op.join(derivatives, 'freesurfer', 'sub-{subject}', 'mri', 'brainmask.mgz').format(**locals()) freesurfer_t1w = op.join(derivatives, 'freesurfer', 'sub-{subject}', 'mri', 'T1.mgz').format(**locals()) manual_outside_mask = image.resample_to_img(manual_outside_mask, freesurfer_brainmask_auto, interpolation='nearest') manual_outside_mask = nb.freesurfer.MGHImage( manual_outside_mask.get_data().astype(np.float32), affine=manual_outside_mask.affine) manual_inside_mask = image.resample_to_img(manual_inside_mask, freesurfer_brainmask_auto, interpolation='nearest') manual_inside_mask = nb.freesurfer.MGHImage( manual_inside_mask.get_data().astype(np.float32), affine=manual_inside_mask.affine) if manual_wm_mask: manual_wm_mask = image.resample_to_img(manual_wm_mask, freesurfer_brainmask_auto, interpolation='nearest') manual_wm_mask = nb.freesurfer.MGHImage( manual_wm_mask.get_data().astype(np.float32), affine=manual_wm_mask.affine) manual_inside_mask = image.math_img( '(manual_inside_mask + manual_wm_mask) > 0', manual_inside_mask=manual_inside_mask, manual_wm_mask=manual_wm_mask) freesurfer_wm = op.join(derivatives, 'freesurfer', 'sub-{subject}', 'mri', 'wm.mgz').format(**locals()) freesurfer_wm_new = image.math_img( 'freesurfer_wm * (1-manual_inside_mask) ' '* (1 - manual_outside_mask)' '+ manual_wm_mask * 255', manual_inside_mask=manual_inside_mask, manual_wm_mask=manual_wm_mask, manual_outside_mask=manual_outside_mask, freesurfer_wm=freesurfer_wm) # Get rid of any weird small components freesurfer_wm_new_ = nb.Nifti1Image(freesurfer_wm_new.get_data(), freesurfer_wm_new.affine) largest_component = image.largest_connected_component_img( freesurfer_wm_new_) largest_component = nb.MGHImage(largest_component.get_data(), freesurfer_wm_new.affine, freesurfer_wm_new.header) freesurfer_wm_new = image.math_img('freesurfer_wm * largest_component', freesurfer_wm=freesurfer_wm_new, largest_component=largest_component) freesurfer_wm_new.to_filename(freesurfer_wm) new_brainmask = image.math_img( '(((brain_mask > 0) + inside - outside ) > 0) * t1w', brain_mask=freesurfer_brainmask_auto, outside=manual_outside_mask, t1w=freesurfer_t1w, inside=manual_inside_mask) new_brainmask.to_filename(freesurfer_brainmask) new_brainmask.to_filename( op.join(derivatives, 'freesurfer', 'sub-{subject}', 'mri', 'brain.finalsurfs.manedit.mgz').format(**locals()))
def test_largest_cc_img(): """ Check the extraction of the largest connected component, for niftis Similiar to smooth_img tests for largest connected_component_img, here also only the added features for largest_connected_component are tested. """ # Test whether dimension of 3Dimg and list of 3Dimgs are kept. shapes = ((10, 11, 12), (13, 14, 15)) regions = [1, 3] img1 = data_gen.generate_labeled_regions(shape=shapes[0], n_regions=regions[0]) img2 = data_gen.generate_labeled_regions(shape=shapes[1], n_regions=regions[1]) for create_files in (False, True): with testing.write_tmp_imgs(img1, img2, create_files=create_files) as imgs: # List of images as input out = largest_connected_component_img(imgs) assert_true(isinstance(out, list)) assert_true(len(out) == 2) for o, s in zip(out, shapes): assert_true(o.shape == (s)) # Single image as input out = largest_connected_component_img(imgs[0]) assert_true(isinstance(out, Nifti1Image)) assert_true(out.shape == (shapes[0])) # Test whether 4D Nifti throws the right error. img_4D = data_gen.generate_fake_fmri(shapes[0], length=17) assert_raises(DimensionError, largest_connected_component_img, img_4D) # tests adapted to non-native endian data dtype img1_change_dtype = nibabel.Nifti1Image(img1.get_data().astype('>f8'), affine=img1.affine) img2_change_dtype = nibabel.Nifti1Image(img2.get_data().astype('>f8'), affine=img2.affine) for create_files in (False, True): with testing.write_tmp_imgs(img1_change_dtype, img2_change_dtype, create_files=create_files) as imgs: # List of images as input out = largest_connected_component_img(imgs) assert_true(isinstance(out, list)) assert_true(len(out) == 2) for o, s in zip(out, shapes): assert_true(o.shape == (s)) # Single image as input out = largest_connected_component_img(imgs[0]) assert_true(isinstance(out, Nifti1Image)) assert_true(out.shape == (shapes[0])) # Test the output with native and without native out_native = largest_connected_component_img(img1) out_non_native = largest_connected_component_img(img1_change_dtype) np.testing.assert_equal(out_native.get_data(), out_non_native.get_data())
def main(sourcedata, derivatives, tmp_dir, subject=None): fmriprep_layout = BIDSLayout(os.path.join(derivatives, 'fmriprep')) manual_layout = BIDSLayout(os.path.join(derivatives, 'manual_segmentation')) manual = {} manual['wm'] = get_bids_file(manual_layout, subject, 'manualsegwm') manual['gm'] = get_bids_file(manual_layout, subject, 'manualseggm') fmriprep = {} fmriprep['wm'] = get_bids_file(fmriprep_layout, subject, 'probtissue', 'WM') fmriprep['gm'] = get_bids_file(fmriprep_layout, subject, 'probtissue', 'GM') fmriprep['csf'] = get_bids_file(fmriprep_layout, subject, 'probtissue', 'CSF') extract_layout = BIDSLayout( os.path.join(derivatives, 'nighres', 'extract_brain_regions')) output_dir = os.path.join(derivatives, 'nighres', 'cortex_extraction', 'sub-{}'.format(subject)) freesurfer_seg = get_bids_file(fmriprep_layout, subject, 'roi', 'label-aseg') _regions = ['wm', 'csf', 'gm'] for hemi in ['left', 'right'][::-1]: mgdm = {} for r in _regions: label = {'csf': 'bg', 'wm': 'wm', 'gm': 'gm'}[r] mgdm[r] = get_bids_file(extract_layout, subject, '{}cr{}'.format(hemi[0], label), 'xproba') freesurfer_seg = image.resample_to_img(freesurfer_seg, mgdm['gm'], interpolation='nearest') freesurfer = {} if hemi == 'left': freesurfer['wm'] = image.math_img('(seg == 2).astype(int)', seg=freesurfer_seg) freesurfer['gm'] = image.math_img('(seg == 3).astype(int)', seg=freesurfer_seg) else: freesurfer['wm'] = image.math_img('(seg == 41).astype(int)', seg=freesurfer_seg) freesurfer['gm'] = image.math_img('(seg == 42).astype(int)', seg=freesurfer_seg) for key in freesurfer: freesurfer[key] = image.resample_to_img(freesurfer[key], mgdm['gm'], interpolation='nearest') for key in _regions: fmriprep[key] = image.resample_to_img(fmriprep[key], mgdm[key], interpolation='nearest') wm = image.math_img('fmriprep + mgdm + freesurfer + manual*5', mgdm=mgdm['wm'], fmriprep=fmriprep['wm'], freesurfer=freesurfer['wm'], manual=manual['wm']) gm = image.math_img('fmriprep + mgdm + freesurfer + manual*5', mgdm=mgdm['gm'], fmriprep=fmriprep['gm'], freesurfer=freesurfer['gm'], manual=manual['gm']) csf = image.math_img('3 * mgdm', mgdm=mgdm['csf']) total_prob = image.math_img('wm + gm + csf', wm=wm, gm=gm, csf=csf) wm = image.math_img('wm / total_prob', wm=wm, total_prob=total_prob) gm = image.math_img('gm / total_prob', gm=gm, total_prob=total_prob) csf = image.math_img('csf / total_prob', csf=csf, total_prob=total_prob) wm.to_filename('/derivatives/zooi/wm_mask_{}.nii.gz'.format(hemi)) gm.to_filename('/derivatives/zooi/gm_mask_{}.nii.gz'.format(hemi)) csf.to_filename('/derivatives/zooi/csf_mask_{}.nii.gz'.format(hemi)) inside_mask = image.math_img('wm > 0.45', wm=wm) inside_mask = image.largest_connected_component_img(inside_mask) inside_mask.to_filename( '/derivatives/zooi/inside_mask_{}.nii.gz'.format(hemi)) inside_mask = image.new_img_like( inside_mask, ndimage.binary_closing(inside_mask.get_data(), iterations=3)) cruise = nighres.cortex.cruise_cortex_extraction( init_image=inside_mask, wm_image=wm, gm_image=gm, csf_image=csf, normalize_probabilities=False, file_name='sub-{}_{}'.format(subject, hemi), save_data=True, output_dir=output_dir)
import skimage.measure as sm import nilearn.image as nimg >>>>>>> 02924efd7fd9ff93e10f0e0030a43b878812e288 import slam.io as sio import slam.differential_geometry as sdg from nipype.utils.filemanip import split_filename # Generate output mesh filename from the input image name <<<<<<< HEAD _, fname, _ = split_filename(self.input_spec.image_file) gii_file = op.abspath(op.join(runtime.cwd, fname + ".gii")) # Load the largest connected component of the input image img = nimg.largest_connected_component_img(self.input_spec.image_file) #TODO: check if the input image is correct (binary) # Run the marching cube algorithm verts, faces, normals, values = sm.marching_cubes( img.get_data(), self.input_spec.level) ======= _, fname, _ = split_filename(self.inputs.image_file) gii_file = op.abspath(op.join(runtime.cwd, fname + ".gii")) # Load the largest connected component of the input image img = nimg.largest_connected_component_img(self.inputs.image_file) # TODO: check if the input image is correct (binary)