def createSampleVolume( outputfile ): ''' Create a sample volume which has a different value for each voxel. Then, save the volume. ''' print Colors.PURPLE + 'Creating a sample volume (d:' + Colors.CYAN + str( SAMPLE_VOLUME_DIMENSION_X ) + ',' + str( SAMPLE_VOLUME_DIMENSION_Y ) + ',' + str( SAMPLE_VOLUME_DIMENSION_Z ) + Colors.PURPLE + ' s:' + Colors.CYAN + str( SAMPLE_VOLUME_SPACING_X ) + ',' + str( SAMPLE_VOLUME_SPACING_Y ) + ',' + str( SAMPLE_VOLUME_SPACING_Z ) + '): ' + Colors.ORANGE + outputfile + Colors.PURPLE + '..' + Colors._CLEAR testArr = numpy.zeros( ( SAMPLE_VOLUME_DIMENSION_X, SAMPLE_VOLUME_DIMENSION_Y, SAMPLE_VOLUME_DIMENSION_Z ) ) r = 0 for i in range( testArr.shape[0] ): for j in range( testArr.shape[1] ): for k in range( testArr.shape[2] ): r += 1 testArr[i, j, k] = r img = Nifti1Image( testArr, None ) hdr = img.get_header() hdr.set_zooms( [SAMPLE_VOLUME_SPACING_X, SAMPLE_VOLUME_SPACING_Y, SAMPLE_VOLUME_SPACING_Z] ); hdr.set_xyzt_units( 1.0, 1.0 ) save( img, outputfile ) return testArr
def atlas_from_freesurfer_masks(sub, mask_dir, roi_ids, rh_constant=200, overwrite=False): ''' Create atlas from individual binary masks produced by freesurfer's 'mri_label2vol' tool Args: sub (int): subject number mask_dir (str): path to subject's folder with freesurfer output roi_ids (dict): {target_ROI: Left Hemisphere ROI index} rh_constant (int): Right Hemisphere ROI index := Left Hemisphere ROI index + rh_constant overwrite (bool): If true: delete old atlas and create new one Returns: atlas (Nifti1Image): T1w Atlas with voxel values indicative of ROI identity (as defined in 'roi_ids') ''' atlas_path = os.path.join( mask_dir, "sub-" + str(sub).zfill(2) + "_Mask_T1w_Glasser.nii.gz") if os.path.isfile(atlas_path) and not overwrite: atlas = nifti1.load(atlas_path) else: # create atlas hemi_dict = {'L': 'lh.L_', 'R': 'rh.R_'} hemi_add = {'L': 0, 'R': rh_constant} mask_array = [] mask_array_tmp = [] for roi in roi_ids.keys(): for hemi in ['L', 'R']: mask_raw = nifti1.load( os.path.join(mask_dir, hemi_dict[hemi] + roi + '_ROI.fbr.nii.gz')) if len(mask_array) == 0: mask_array_tmp = mask_raw.get_fdata() mask_array_tmp[ mask_array_tmp == 1] = roi_ids[roi][0] + hemi_add[ hemi] # convert binary mask by assigning roi_id to masked voxels mask_array = mask_array_tmp.copy() freesurfer_affine = mask_raw.affine.copy() else: mask_array_tmp = mask_raw.get_fdata() mask_array[mask_array_tmp == 1] = roi_ids[roi][0] + hemi_add[hemi] atlas = nifti1.Nifti1Image(mask_array, freesurfer_affine) nifti1.save(atlas, atlas_path) return atlas
def rawToNifti(infile, sizefile=None, outfile=None, dimorder=None, diskorder='F', dtype=None, split4=False): """Converts a raw file to a NIfTI file. Arguments: infile: Filename of a raw file. sizefile: Filename of a size_info config file. If None, attempts to find this file in the same directory as infile. outfile: Filename (including .nii) of the NIfTI file to generate. If None, it will be generated from infile. dimorder: Four-character string that is a permutation of "XYZI", indicating the dimension order of the image in "infile". The purpose of this argument is to rearrange the order of the dimensions in the infile to match the NIfTI canonical order of (X, Y, Z, I), where I is the dimension along which multiple acquisitions are concatenated. The default value, None, is equivalent to "XYZI". Note that this argument will be overridden if the size_info file contains a "dimension_order" value. diskorder: A string, 'F' or 'C', representing the order in which the data values are stored in the raw file. dtype: The numpy dtype for the infile. If None, it is inferred from infile's extension. split4: If True, output numbered 3-D images from 4-D input. """ (raw, cfg) = readRawWithSizeInfo(infile, sizefile=sizefile, dtype=dtype, dimorder=dimorder, diskorder=diskorder, memorder='C') vox_sz = cfg['voxel_size_(mm)'] # Rearrange dimensions. try: dimorder = cfg['dimension_order'] except KeyError: if dimorder is None: dimorder = _miraw_helpers.DIM_DEFAULT_ORDER if not _miraw_helpers.isValidDimorder(dimorder): raise ValueError('"%s" is not a valid dimorder argument.'%repr(dimorder)) raw_transp = raw.transpose(_miraw_helpers.dimorderToReverseDimmap(dimorder)) if split4 and len(raw_transp.shape) == 4: raw_stack = [raw_transp[:,:,:,i] for i in range(raw_transp.shape[3])] else: raw_stack = [raw_transp] i = 0 for img in raw_stack: nii = nifti1.Nifti1Pair(img, np.diag(vox_sz + [0.0])) nii.get_header().set_xyzt_units('mm') outfname = outfile if outfname is None: outfname = os.path.splitext(infile)[0] + '.nii' if split4: outfname = os.path.splitext(outfname)[0] + ('_%03i.nii' % i) i += 1 nifti1.save(nii, outfname)
def test_save_load(): shape = (2, 4, 6) npt = np.float32 data = np.arange(np.prod(shape), dtype=npt).reshape(shape) affine = np.diag([1, 2, 3, 1]) affine[:3,3] = [3,2,1] img = ni1.Nifti1Image(data, affine) img.set_data_dtype(npt) with InTemporaryDirectory() as pth: pth = mkdtemp() nifn = pjoin(pth, 'an_image.nii') sifn = pjoin(pth, 'another_image.img') ni1.save(img, nifn) re_img = nils.load(nifn) yield assert_true(isinstance(re_img, ni1.Nifti1Image)) yield assert_array_equal(re_img.get_data(), data) yield assert_array_equal(re_img.get_affine(), affine) # These and subsequent del statements are to prevent confusing # windows errors when trying to open files or delete the # temporary directory. del re_img try: import scipy.io except ImportError: # ignore if there is no matfile reader, and restart pass else: spm2.save(img, sifn) re_img2 = nils.load(sifn) yield assert_true(isinstance(re_img2, spm2.Spm2AnalyzeImage)) yield assert_array_equal(re_img2.get_data(), data) yield assert_array_equal(re_img2.get_affine(), affine) del re_img2 spm99.save(img, sifn) re_img3 = nils.load(sifn) yield assert_true(isinstance(re_img3, spm99.Spm99AnalyzeImage)) yield assert_array_equal(re_img3.get_data(), data) yield assert_array_equal(re_img3.get_affine(), affine) ni1.save(re_img3, nifn) del re_img3 re_img = nils.load(nifn) yield assert_true(isinstance(re_img, ni1.Nifti1Image)) yield assert_array_equal(re_img.get_data(), data) yield assert_array_equal(re_img.get_affine(), affine) del re_img
def test_save_load(): shape = (2, 4, 6) npt = np.float32 data = np.arange(np.prod(shape), dtype=npt).reshape(shape) affine = np.diag([1, 2, 3, 1]) affine[:3, 3] = [3, 2, 1] img = ni1.Nifti1Image(data, affine) img.set_data_dtype(npt) with InTemporaryDirectory() as pth: pth = mkdtemp() nifn = pjoin(pth, 'an_image.nii') sifn = pjoin(pth, 'another_image.img') ni1.save(img, nifn) re_img = nils.load(nifn) yield assert_true(isinstance(re_img, ni1.Nifti1Image)) yield assert_array_equal(re_img.get_data(), data) yield assert_array_equal(re_img.get_affine(), affine) # These and subsequent del statements are to prevent confusing # windows errors when trying to open files or delete the # temporary directory. del re_img try: import scipy.io except ImportError: # ignore if there is no matfile reader, and restart pass else: spm2.save(img, sifn) re_img2 = nils.load(sifn) yield assert_true(isinstance(re_img2, spm2.Spm2AnalyzeImage)) yield assert_array_equal(re_img2.get_data(), data) yield assert_array_equal(re_img2.get_affine(), affine) del re_img2 spm99.save(img, sifn) re_img3 = nils.load(sifn) yield assert_true(isinstance(re_img3, spm99.Spm99AnalyzeImage)) yield assert_array_equal(re_img3.get_data(), data) yield assert_array_equal(re_img3.get_affine(), affine) ni1.save(re_img3, nifn) del re_img3 re_img = nils.load(nifn) yield assert_true(isinstance(re_img, ni1.Nifti1Image)) yield assert_array_equal(re_img.get_data(), data) yield assert_array_equal(re_img.get_affine(), affine) del re_img
def img_transform(img_file_name,save_dir): img_hdr = nitool.load(img_file_name) img_data = img_hdr.get_data() img_shape = img_data.shape t = img_data.flatten() t1 = np.zeros(t.size) t1[np.where(t>100)] = t[np.where(t > 100)]+3000 t1[np.where(np.logical_and(t >= -1000, t <= -100))]=t[np.where(np.logical_and(t >= -1000,t <= -100))]+1000 t1[np.where(np.logical_and(t >= -99, t <= 100))]=(t[np.where(np.logical_and(t >= -99, t <= 100))]+99)*11+911 trans_img = t1.reshape(img_shape) trans_pair = nitool.Nifti1Pair(trans_img,img_hdr.affine) save_name = os.path.join(save_dir, 'itrans'+'.nii.gz') nitool.save(trans_pair, save_name) return save_name
def test_save_load(): shape = (2, 4, 6) npt = np.float32 data = np.arange(np.prod(shape), dtype=npt).reshape(shape) affine = np.diag([1, 2, 3, 1]) affine[:3,3] = [3,2,1] img = ni1.Nifti1Image(data, affine) img.set_data_dtype(npt) with InTemporaryDirectory() as pth: nifn = 'an_image.nii' sifn = 'another_image.img' ni1.save(img, nifn) re_img = nils.load(nifn) yield assert_true(isinstance(re_img, ni1.Nifti1Image)) yield assert_array_equal(re_img.get_data(), data) yield assert_array_equal(re_img.get_affine(), affine) # These and subsequent del statements are to prevent confusing # windows errors when trying to open files or delete the # temporary directory. del re_img if have_scipy: # skip we we cannot read .mat files spm2.save(img, sifn) re_img2 = nils.load(sifn) yield assert_true(isinstance(re_img2, spm2.Spm2AnalyzeImage)) yield assert_array_equal(re_img2.get_data(), data) yield assert_array_equal(re_img2.get_affine(), affine) del re_img2 spm99.save(img, sifn) re_img3 = nils.load(sifn) yield assert_true(isinstance(re_img3, spm99.Spm99AnalyzeImage)) yield assert_array_equal(re_img3.get_data(), data) yield assert_array_equal(re_img3.get_affine(), affine) ni1.save(re_img3, nifn) del re_img3 re_img = nils.load(nifn) yield assert_true(isinstance(re_img, ni1.Nifti1Image)) yield assert_array_equal(re_img.get_data(), data) yield assert_array_equal(re_img.get_affine(), affine) del re_img
def test_save_load(): shape = (2, 4, 6) npt = np.float32 data = np.arange(np.prod(shape), dtype=npt).reshape(shape) affine = np.diag([1, 2, 3, 1]) affine[:3, 3] = [3, 2, 1] img = ni1.Nifti1Image(data, affine) img.set_data_dtype(npt) with InTemporaryDirectory() as pth: nifn = 'an_image.nii' sifn = 'another_image.img' ni1.save(img, nifn) re_img = nils.load(nifn) yield assert_true(isinstance(re_img, ni1.Nifti1Image)) yield assert_array_equal(re_img.get_data(), data) yield assert_array_equal(re_img.get_affine(), affine) # These and subsequent del statements are to prevent confusing # windows errors when trying to open files or delete the # temporary directory. del re_img if have_scipy: # skip we we cannot read .mat files spm2.save(img, sifn) re_img2 = nils.load(sifn) yield assert_true(isinstance(re_img2, spm2.Spm2AnalyzeImage)) yield assert_array_equal(re_img2.get_data(), data) yield assert_array_equal(re_img2.get_affine(), affine) del re_img2 spm99.save(img, sifn) re_img3 = nils.load(sifn) yield assert_true(isinstance(re_img3, spm99.Spm99AnalyzeImage)) yield assert_array_equal(re_img3.get_data(), data) yield assert_array_equal(re_img3.get_affine(), affine) ni1.save(re_img3, nifn) del re_img3 re_img = nils.load(nifn) yield assert_true(isinstance(re_img, ni1.Nifti1Image)) yield assert_array_equal(re_img.get_data(), data) yield assert_array_equal(re_img.get_affine(), affine) del re_img
def createSampleVolumeWithSelectedLabels( outputfile, values ): ''' Create a sample volume which has a randomly chosen value from the values list. Then, save the volume. ''' print Colors.PURPLE + 'Creating a sample volume (d:' + Colors.CYAN + str( SAMPLE_VOLUME_DIMENSION_X ) + ',' + str( SAMPLE_VOLUME_DIMENSION_Y ) + ',' + str( SAMPLE_VOLUME_DIMENSION_Z ) + Colors.PURPLE + ' s:' + Colors.CYAN + str( SAMPLE_VOLUME_SPACING_X ) + ',' + str( SAMPLE_VOLUME_SPACING_Y ) + ',' + str( SAMPLE_VOLUME_SPACING_Z ) + '): ' + Colors.ORANGE + outputfile + Colors.PURPLE + '..' + Colors._CLEAR testArr = numpy.zeros( ( SAMPLE_VOLUME_DIMENSION_X, SAMPLE_VOLUME_DIMENSION_Y, SAMPLE_VOLUME_DIMENSION_Z ) ) for i in range( testArr.shape[0] ): for j in range( testArr.shape[1] ): for k in range( testArr.shape[2] ): testArr[i, j, k] = random.sample( values, 1 )[0] img = Nifti1Image( testArr, None ) hdr = img.get_header() hdr.set_zooms( [SAMPLE_VOLUME_SPACING_X, SAMPLE_VOLUME_SPACING_Y, SAMPLE_VOLUME_SPACING_Z] ); hdr.set_xyzt_units( 1.0, 1.0 ) save( img, outputfile ) return testArr
# Set directories, specify ROIs and load dictionary for labels TR = 3 ds_dir = "/home/alex/Datasets/ds001246/" spm_dir = os.path.join(ds_dir, "derivatives", spm_type) n_subs = len(glob.glob(ds_dir + os.sep + "sub*")) ############################################################################## for sub in range(1, n_subs + 1): img_output_dir = os.path.join(spm_dir, "sub-" + str(sub).zfill(2)) # For each run, get averaged condition-specific residuals pooled_residuals_array, generic_affine, fourth_dimension_descriptors = \ pooled_residuals_pipeline(sub, spm_dir, spm_type, ses_type, TR, drop_first_res) # Make subject-specific nifti image of block-averaged residuals pooled_residuals = nifti1.Nifti1Image(pooled_residuals_array, generic_affine) nifti_filename = os.path.join( img_output_dir, "sub-" + str(sub).zfill(2) + "_V_" + stimulus_set + ".nii.gz") nifti1.save(pooled_residuals, nifti_filename) csv_filename = os.path.join( img_output_dir, "sub-" + str(sub).zfill(2) + "_uq_conditions_" + stimulus_set + ".csv") df = pd.DataFrame({'descriptor': fourth_dimension_descriptors}) df.to_csv(csv_filename, header=False)
def save_nii(self, person, nii, nii_prefix='mri_smoothed_removed/{}.nii'): path = os.path.join(self.file_dir, nii_prefix.format(person.filename)) nifti1.save(nii, path)
data_folder = sys.argv[1] gm_filename = r'c1reg.nii' wm_filename = r'c2reg.nii' csf_filename = r'c3reg.nii' sublist_filename = sys.argv[2] with open(sublist_filename, 'rt') as sublistfile: lines = sublistfile.readlines() sublist = [k.rstrip() for k in lines] #%% for i in sublist: print(i) gm_file = nitool.load(os.path.join(data_folder, i, gm_filename)) gm_img = gm_file.get_data() wm_file = nitool.load(os.path.join(data_folder, i, wm_filename)) wm_img = wm_file.get_data() csf_file = nitool.load(os.path.join(data_folder, i, csf_filename)) csf_img = csf_file.get_data() tiv_img = gm_img + wm_img + csf_img tiv_file = nitool.Nifti1Image(tiv_img, gm_file.affine) tiv_filename = os.path.join(data_folder, i, 'tivmask_image.nii.gz') print(tiv_filename) nitool.save(tiv_file, tiv_filename)
es_array = np.asarray(es.dataobj) p = nib.load(p_path) p_array = np.asarray(p.dataobj) for p in ps: corrected_array = voxelwise_correction(es_array, p_array, voxel_count, thres=p) affine = es.affine header = es.header corrected_niis = nib.Nifti1Image(corrected_array, affine, header) new_f = os.path.join(voxel_path, 'es_bon_{}.nii'.format(str(p)[2:])) print(new_f) print(len(corrected_array[corrected_array != 0])) nifti1.save(corrected_niis, new_f) # %% # ROI GMV correction import numpy as np from meta_analysis import utils def load_nii_array(filepath): nii = nib.load(filepath) return np.asarray(nii.dataobj), nii def roi_correction(value_path, p_path, count, out_path, p=0.001, top=1): v_array, v_nii = load_nii_array(value_path) p_array, _ = load_nii_array(p_path)
import os import sys #%% data_folder = sys.argv[1] gm_filename = r'c1reg.nii' wm_filename = r'c2reg.nii' sublist_filename = sys.argv[2] with open(sublist_filename, 'rt') as sublistfile: lines = sublistfile.readlines() sublist = [k.rstrip() for k in lines] #%% for i in sublist: print(i) gm_file = nitool.load(os.path.join(data_folder, i, gm_filename)) gm_img = gm_file.get_data() wm_file = nitool.load(os.path.join(data_folder, i, wm_filename)) wm_img = wm_file.get_data() tbv_img = gm_img + wm_img tbv_file = nitool.Nifti1Image(tbv_img, gm_file.affine) tbv_filename = os.path.join(data_folder, i, 'tbvmask_image.nii.gz') print(tbv_filename) nitool.save(tbv_file, tbv_filename)