def resize_image(fileitems, resize_shape=(160, 160, 192)): for item in fileitems: img1 = item + '/normalize/' + 'norm.nii' img2 = item + '/normalize/' + 'nu.nii' img3 = item + '/normalize/' + 'lh.hippoSfLabels-T1.v10.FSvoxelSpace.nii' img4 = item + '/normalize/' + 'rh.hippoSfLabels-T1.v10.FSvoxelSpace.nii' img1 = nib.load(img1) img2 = nib.load(img2) img3 = nib.load(img3) img4 = nib.load(img4) norm_resize = resize(img1, resize_shape) nu_resize = resize(img2, resize_shape) lhip_resize = resize(img3, resize_shape) rhip_resize = resize(img4, resize_shape) norm_resize = affine_register(norm_resize) nu_resize = affine_register(nu_resize) lhip_resize = affine_register(lhip_resize) rhip_resize = affine_register(rhip_resize) norm_data = nib.AnalyzeImage(norm_resize.get_data(), norm_resize.affine) nu_data = nib.AnalyzeImage(nu_resize.get_data(), nu_resize.affine) lhip_data = nib.AnalyzeImage(lhip_resize.get_data(), lhip_resize.affine) rhip_data = nib.AnalyzeImage(rhip_resize.get_data(), rhip_resize.affine) nib.save(norm_data, item + '/resize/' + 'norm_resize.nii') nib.save(nu_data, item + '/resize/' + 'nu_resize.nii') nib.save(lhip_data, item + '/resize/' + 'lhipp_resize.nii') nib.save(rhip_data, item + '/resize/' + 'rhipp_resize.nii')
def operate_single_image(input_image, operation, factor, output_image, logfile): """ Given an input image, multiply or divide it by a numerical factor saving the result as output_image :param input_image: image base operation on :param operation: 1 = multiply, 2 = divide :param factor: operation factor :param output_image: output image file :return: """ img = nib.load(input_image) data = img.get_data()[:, :, :] data = np.nan_to_num(data) if operation == 'mult': data = data * float(factor) elif operation == 'div': data = data / float(factor) else: message = "Error! Invalid operation: " + str(operation) print(message) log_message(logfile, message, 'error') hdr1 = nib.AnalyzeHeader() hdr1.set_data_dtype(img.get_data_dtype()) hdr1.set_data_shape(img.shape) hdr1.set_zooms(abs(np.diag(img.affine))[0:3]) analyze_img = nib.AnalyzeImage(data, hdr1.get_base_affine(), hdr1) nib.save(analyze_img, output_image)
def create_sample_data(self): """ Create sample data files. The files created are: * analyze_image.hdr + .img: plain ANALYZE image * mgh_image.mgh: MGH image * nifti1_image.nii: NIfTI1 image * nifti2_image.nii: NIfTI2 image * spm2_image.hdr + .img + .mat: SPM2 ANALYZE image * spm99_image.hdr + .img + .mat: SPM99 ANALYZE image """ file_name = os.path.join(self.data_dir, "analyze_image") analyze_img = nib.AnalyzeImage(self.get_data(), np.eye(4)) analyze_img.to_filename(file_name) file_name = os.path.join(self.data_dir, "mgh_image") mgh_img = nib.freesurfer.mghformat.MGHImage(self.get_data(), np.eye(4)) mgh_img.to_filename(file_name) file_name = os.path.join(self.data_dir, "nifti1_image") nifti1_img = nib.Nifti1Image(self.get_data(), self.get_affine()) nifti1_img.to_filename(file_name) file_name = os.path.join(self.data_dir, "nifti2_image") nifti2_img = nib.Nifti2Image(self.get_data(), self.get_affine()) nifti2_img.to_filename(file_name) file_name = os.path.join(self.data_dir, "spm2_image") spm2_img = nib.spm2analyze.Spm2AnalyzeImage(self.get_data(), np.eye(4)) spm2_img.to_filename(file_name) file_name = os.path.join(self.data_dir, "spm99_image") spm99_img = nib.spm99analyze.Spm99AnalyzeImage(self.get_data(), np.eye(4)) spm99_img.to_filename(file_name)
def analyze_pair_image_files(outdir, filelist, shape): for f in filename_to_list(filelist): hdr = nb.Nifti1Header() hdr.set_data_shape(shape) img = np.random.random(shape) analyze = nb.AnalyzeImage(img, np.eye(4), hdr) analyze.to_filename(os.path.join(outdir, f))
def create_analyze_from_imgdata(data, out, pix_x, pix_y, pix_z, tx, ty, tz, data_type="fl"): if data_type == "1b": dtype = np.int8 elif data_type == "2b": dtype = np.int16 elif data_type == "db": dtype = np.float64 else: dtype = np.float32 hdr1 = nib.AnalyzeHeader() hdr1.set_data_dtype(dtype) hdr1.set_data_shape((pix_x, pix_y, pix_z)) hdr1.set_zooms((tx, ty, tz)) f = open(data, 'rb') img_data = hdr1.raw_data_from_fileobj(f) analyze_img = nib.AnalyzeImage(img_data, hdr1.get_base_affine(), hdr1) nib.save(analyze_img, out)
def curt_nifti_image(fileitems): for item in fileitems: img1 = item + '/normalize/' + 'norm.nii' img2 = item + '/normalize/' + 'nu.nii' img3 = item + '/normalize/' + 'lh.hippoSfLabels-T1.v10.FSvoxelSpace.nii' img4 = item + '/normalize/' + 'rh.hippoSfLabels-T1.v10.FSvoxelSpace.nii' img_norm = nib.load(img1) data_norm = img_norm.get_data() nozero = np.nonzero(data_norm) center_x = (nozero[0].max() + nozero[0].min()) / 2 center_y = (nozero[1].max() + nozero[1].min()) / 2 center_z = (nozero[2].max() + nozero[2].min()) / 2 box = np.zeros((3, 2), dtype=int) box[0, 0] = int(center_x - 80) box[0, 1] = int(center_x + 80) box[1, 0] = int(center_y - 80) box[1, 1] = int(center_y + 80) box[2, 0] = int(center_z - 96) box[2, 1] = int(center_z + 96) norm_result = data_norm[box[0,0]:box[0,1], box[1,0]:box[1,1], box[2,0]:box[2,1]] img_norm = affine_register(img_norm) norm_result = nib.AnalyzeImage(norm_result, img_norm.affine) nib.save(norm_result, item+'/reaffine/'+'norm_reaffine.nii') img_nu = nib.load(img2) data_nu = img_nu.get_data() nu_result = data_nu[box[0,0]:box[0,1], box[1,0]:box[1,1], box[2,0]:box[2,1]] img_nu = affine_register(img_nu) nu_result = nib.AnalyzeImage(nu_result, img_nu.affine) nib.save(nu_result, item+'/reaffine/'+'nu_reaffine.nii') img_lhip = nib.load(img3) data_lhip = img_lhip.get_data() lhip_result = data_lhip[box[0,0]:box[0,1], box[1,0]:box[1,1], box[2,0]:box[2,1]] img_lhip = affine_register(img_lhip) lhip_result = nib.AnalyzeImage(lhip_result, img_lhip.affine) nib.save(lhip_result, item+'/reaffine/'+'lhipp_reaffine.nii') img_rhip = nib.load(img4) data_rhip = img_rhip.get_data() rhip_result = data_rhip[box[0,0]:box[0,1], box[1,0]:box[1,1], box[2,0]:box[2,1]] img_rhip = affine_register(img_rhip) rhip_result = nib.AnalyzeImage(rhip_result, img_rhip.affine) nib.save(rhip_result, item+'/reaffine/'+'rhipp_reaffine.nii')
def save(self): if self.current: reply = QMessageBox.question( self, 'Save', 'Save will overwrite the current file, whether to save?', QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: img_nib = nib.AnalyzeImage(self.img_data.astype('int16'), None) nib.save(img_nib, self.current)
def saveas(self): if self.current: desktoppath = os.path.join(os.path.expanduser("~"), 'Desktop') file_name = os.path.basename(self.current) full_path = f'{desktoppath}/{file_name}' filename = QFileDialog.getSaveFileName(self, "Save", full_path, 'imge(*.nii.gz *.nii)') if filename[0]: img_nib = nib.AnalyzeImage(self.img_data.astype('int16'), None) nib.save(img_nib, filename[0])
def write_analyze(im,filepath): id1=np.swapaxes(im.img_data,0,2) ps=im.params.pixel_size hdr=nibabel.AnalyzeHeader() hdr.set_data_shape(id1.shape) hdr.set_data_dtype(id1.dtype) hdr.set_zooms([ps,ps,ps,im.params.frame_duration[0]]) analyze_img=nibabel.AnalyzeImage(id1,None,hdr) print('writing Analyze 7.5 image: '+filepath) analyze_img.to_filename(filepath)
def analyze_to_filename(self): """ Use nibabel.analyze.AnalyzeImage.to_filename to save out_analyze_image.hdr + .img. """ file_name = os.path.join(self.data_dir, "out_analyze_image") img = nib.AnalyzeImage(self.get_data(), np.eye(4)) img.to_filename(file_name) os.remove(file_name + ".hdr") os.remove(file_name + ".img")
def augment_image(fileitems): for item in fileitems: img1 = item + '/resize/' + 'norm_resize.nii' img2 = item + '/resize/' + 'nu_resize.nii' img3 = item + '/resize/' + 'lhipp_resize.nii' img4 = item + '/resize/' + 'rhipp_resize.nii' img1 = nib.load(img1) data_1 = img1.get_data() img2 = nib.load(img2) data_2 = img2.get_data() img3 = nib.load(img3) truth_1 = img3.get_data() img4 = nib.load(img4) truth_2 = img4.get_data() data_1, data_2, truth_1, truth_2 = augment_data(data_1, data_2, truth_1, truth_2, img1.affine, scale_deviation=0.25, flip=True) data_1 = affine_register(data_1) data_2 = affine_register(data_2) truth_1 = affine_register(truth_1) truth_2 = affine_register(truth_2) # data_1 = nib.AnalyzeImage(data_1, img1.affine) # data_2 = nib.AnalyzeImage(data_2, img2.affine) # truth_1 = nib.AnalyzeImage(truth_1, img3.affine) # truth_2 = nib.AnalyzeImage(truth_2, img4.affine) nii_data_1 = nib.AnalyzeImage(data_1.get_data(), data_1.affine) nii_data_2 = nib.AnalyzeImage(data_2.get_data(), data_2.affine) nii_truth_1 = nib.AnalyzeImage(truth_1.get_data(), truth_1.affine) nii_truth_2 = nib.AnalyzeImage(truth_2.get_data(), truth_2.affine) nib.save(nii_data_1, item + '/resample/' + 'norm_resample.nii') nib.save(nii_data_2, item + '/resample/' + 'nu_resample.nii') nib.save(nii_truth_1, item + '/resample/' + 'lhipp_resample.nii') nib.save(nii_truth_2, item + '/resample/' + 'rhipp_resample.nii')
def make_random_image(filename=None, dims=(10, 10, 10), xform=None, imgtype=1, pixdims=None, dtype=np.float32): """Convenience function which makes an image containing random data. Saves and returns the nibabel object. imgtype == 0: ANALYZE imgtype == 1: NIFTI1 imgtype == 2: NIFTI2 """ if imgtype == 0: hdr = nib.AnalyzeHeader() elif imgtype == 1: hdr = nib.Nifti1Header() elif imgtype == 2: hdr = nib.Nifti2Header() if pixdims is None: pixdims = [1] * len(dims) pixdims = pixdims[:len(dims)] zooms = [abs(p) for p in pixdims] hdr.set_data_dtype(dtype) hdr.set_data_shape(dims) hdr.set_zooms(zooms) if xform is None: xform = np.eye(4) for i, p in enumerate(pixdims[:3]): xform[i, i] = p data = np.array(np.random.random(dims) * 100, dtype=dtype) if imgtype == 0: img = nib.AnalyzeImage(data, xform, hdr) elif imgtype == 1: img = nib.Nifti1Image( data, xform, hdr) elif imgtype == 2: img = nib.Nifti2Image( data, xform, hdr) if filename is not None: if op.splitext(filename)[1] == '': if imgtype == 0: filename = '{}.img'.format(filename) else: filename = '{}.nii'.format(filename) nib.save(img, filename) return img
def combine_nifti(fileitems): for temp in fileitems: tag = temp.split('/')[-1] lhip_name = temp + '/lhipp_' + tag + '.nii' rhip_name = temp + '/rhipp_' + tag + '.nii' lhip_img = nib.load(lhip_name) rhip_img = nib.load(rhip_name) lhip_data = np.asarray(lhip_img.get_data()) rhip_data = np.asarray(rhip_img.get_data()) hip_data = lhip_data + rhip_data if (lhip_img.affine == rhip_img.affine).all(): lhip_img = affine_register(lhip_img) hip_data = nib.AnalyzeImage(hip_data, lhip_img.affine) nib.save(hip_data, temp + '/hipp_combine_' + tag + '.nii') else: print('affine is not equal')
def nifti_to_analyze(nii): nifti = nb.load(nii) if nii[-3:] == '.gz': nif = gzip.open(nii, 'rb') else: nif = open(nii, 'rb') hdr = nb.nifti1.Nifti1Header.from_fileobj(nif) arr_hdr = nb.analyze.AnalyzeHeader.from_header(hdr) arrb = hdr.raw_data_from_fileobj(nif) img = nb.AnalyzeImage(dataobj=arrb, affine=nifti.get_affine(), header=arr_hdr) _, name, _ = split_filename(nii) nb.analyze.save(img, op.abspath(name + '.img')) return op.abspath(name + '.img'), op.abspath(name + '.hdr')
def operate_images_analyze(image1, image2, out_image, operation='mult'): """ Given the input images, calculate the multiplication image or the ratio between them :param image1: string, path to the first image :param image2: string, path to the second image :param operation: string, multi (default) for multiplication divid for division :param out_image: string (optional), path to the output image :return: """ img1, data1 = nib_load(image1) img2, data2 = nib_load(image2) # TODO CHECK IF NEGATIVE VALUES NEED TO BE REMOVED # Remove NaN and negative values data1 = np.nan_to_num(data1) data2 = np.nan_to_num(data2) if operation == 'mult': res_data = data1 * data2 elif operation == 'div': res_data = data1 / data2 elif operation == 'sum': res_data = data1 + data2 elif operation == 'diff': res_data = data1 - data2 else: message = 'Error! Unknown operation: ' + str(operation) raise TypeError(message) hdr1 = nib.AnalyzeHeader() hdr1.set_data_dtype(img1.get_data_dtype()) hdr1.set_data_shape(img1.shape) hdr1.set_zooms(abs(np.diag(img1.affine))[0:3]) analyze_img = nib.AnalyzeImage(res_data, hdr1.get_base_affine(), hdr1) nib.save(analyze_img, out_image)
def convert_simset_sino_to_stir(input_img, output=False): ## To be continued.... simset_img = nib.load(input_img) simset_img_data = simset_img.get_fdata() shape = simset_img_data.shape n_slices = shape[2] nrings = np.sqrt(n_slices) input_definition = [] for i in range(n_slices): ring1, ring2 = divmod(i, nrings) segment = ring1 - ring2 slice_def = [i, ring1, ring2, segment] input_definition.append(slice_def) output_definition = sorted(input_definition, key=itemgetter(3)) stir_img_data = np.empty(shape, dtype=float, order='C') for i in range(n_slices): output_index = output_definition[i][0] input_slice = simset_img_data[:, :, output_index] stir_img_data[:, :, i] = input_slice stir_img = nib.AnalyzeImage(stir_img_data, simset_img.affine, simset_img.header) if not output: output = input_img[0:-4] + '_stir.hdr' nib.save(stir_img, output)
#!/usr/bin/python import nibabel as nib import scipy.signal import os path_main = '/home/andreabertana/Projects/HCP/results/MNI/mc/' subj = os.listdir('./Projects/HCP/MNI/') for s in subj: path = path_main + s + '_mc.nii.gz' print path print "Loading data" fmri = nib.load(path) data = fmri #.data.astype('float32') #fmri= unload() #detrend. Axis 0 should be time.bp should run detrend taking 12 different parts,each with 121vol (12 steps: 1452/121 = 12) that respect one block in Haxby design. print "Detrending" detrended = scipy.signal.detrend(data.get_data(), axis=3, type='linear', bp=[405]) filename = ('/home/andreabertana/Projects/HCP/results/MNI/detrend/' + s + '_detrend.nii.gz') print 'Store detrended data for later re-use' affine = data.get_affine() img = nib.AnalyzeImage(detrended, affine=affine) nib.save(img, filename) print "Done." print "All Done"
tail='upper', mode='select', sort=False) anova = OneWayAnova() #take only run 1 to calculate ANOVA (avoid overfitting) train = fds[fds.sa.chunks != 2, :] fscores = anova(train) featsels = [StaticFeatureSelection(fselector(fscore)) for fscore in fscores] selected = featsels[0].forward(train) #revtest = np.arange(100,100 + selected.nfeatures) # #img = map2nifti(selected, revtest) # #data = img.get_data() vox = np.array(selected.fa['voxel_indices']) img_nifti = nib.load(path_data) affine = img_nifti.get_affine() mask = np.zeros(shape=(91, 109, 91)) #fill mask with info in voxel_indices for i in np.arange(len(vox)): mask[vox[i, 0], vox[i, 1], vox[i, 2]] = 1 img = nib.AnalyzeImage(mask, affine=affine) nib.save(img, path_save)
#T_test, T_mask = test(T1_list[i], T2_list[i], False) #print T_test.shape, T_mask.shape T_test, T_mask, shape_withZero, zero_index = process_test_data( T1_list[i], T2_list[i], False) T_test = fn.normallize(T_test) probability = M.predict(T_test, batch_size=batch_size, verbose=2) del T_test probability = insert_zeroSlice(probability, shape_withZero, zero_index) probability = fuse_argmax(probability) probability = reshape_brain(probability, T_mask, image_size) * T_mask raw_T2 = nib.load(T2_list[i]).get_data().astype( np.float32) # convert to float32 from int16 raw_T2 = np.reshape(raw_T2, (raw_T2.shape[0], raw_T2.shape[1], raw_T2.shape[2])) raw_T1 = nib.load(T1_list[i]).get_data().astype( np.float32) # convert to float32 from int16 raw_T1.reshape(raw_T1.shape[0], raw_T1.shape[1], raw_T1.shape[2]) brain = brain_attach(raw_T2, probability) brain = np.expand_dims(brain, axis=4) name = 'result.img' print('save ressult as:', name) subject = nib.AnalyzeImage(brain, np.eye(4), header=head) #if not os.path.exists('./iSeg-2017-Testing-Results'): # os.makedirs('./iSeg-2017-Testing-Results') nib.save(subject, name) #np.save('save result as result.npy', brain)
import glob SMOOTHING = 1.5 #Gaussian smoothing sigma value = FWHM. MODE = "2D" #2D if smoothing on a slice-by-slice basis, 3D if smoothing per volume while True: rootdir = tkFileDialog.askdirectory(initialdir="/", title='Please select a directory') if os.path.isdir(rootdir) is True: #Checks if entered dir exists os.chdir(rootdir) root.destroy() break else: print "Pathname invalid. Try again." continue os.chdir(rootdir) filelist = glob.glob("*.nii") for i, f in enumerate(filelist): print "File %s of %s: %s" % (i + 1, len(filelist), f) img = nib.load(f) affine = img.get_affine() data = img.get_data() nif = nib.AnalyzeImage(data, affine) nib.save(nif, f[:-4]) del img #clear memory
InputNameList = niftiName.split('.') InputNameBase = InputNameList[0] nimBabel = nib.load(niftiDir + niftiName) nimBabelData = nimBabel.get_data() nimBabelInfo = nib.get_info() nimBabelAffine = nimBabel.get_affine() nimBabelHeader = nimBabel.get_header().structarr nimBabelPixDim = nimBabelHeader['pixdim'] numpyBabelDataSz = numpy.asarray(nimBabelData.shape) print "Input size: " + str(numpyBabelDataSz) + ' Max: ' + str(numpy.max(nimBabelData.ravel())) + ' Min: ' + str(numpy.min(nimBabelData.ravel())) nipMask = mask.compute_mask(nimBabel.get_data(), reference_volume=None, m=0.4, M=0.8, cc=True, opening=16, exclude_zeros=False) img = nib.AnalyzeImage( nimBabel.get_data(), nimBabel.get_affine() ) img.to_filename(analDir + analName) commandBET = 'resources' +os.sep+ 'bet.exe '+analDir+analName+' '+analDir+analName+ ' -m -s -n' with open(os.devnull, "w") as fnull: subprocBET = subprocess.call( commandBET, stdout = fnull, stderr = fnull ) analBabel = nib.load(analDir + analName + '_mask.hdr') analBabelData = analBabel.get_data() analMaskDataTmp = numpy.asarray(analBabelData, dtype='int') analMaskData = numpy.reshape(analMaskDataTmp, [analMaskDataTmp.shape[0], analMaskDataTmp.shape[1], analMaskDataTmp.shape[2]])
# read the MNI file... #=============================================================================== nibMNI = nib.load(niftiDir + 'MNI152_T1_0.7mm.nii.gz') nibMNIBrain = nib.load(niftiDir + 'MNI152_T1_0.7mm_brain.nii.gz') nibMNIBrainMask = nib.load(niftiDir + 'MNI152_T1_0.7mm_brain_mask.nii.gz') nibMNIData = nibMNI.get_data() nibNMIBrainMaskIdx = numpy.nonzero( nibMNIBrainMask.get_data() > 0 ) nibNMIBrainMaskSize = numpy.asarray(nibNMIBrainMaskIdx).shape standardCentroid = numpy.sum(numpy.asarray(nibNMIBrainMaskIdx, dtype=numpy.float32), axis=1) / nibNMIBrainMaskIdx[0].shape standardXYZ = numpy.subtract(numpy.asarray(nibNMIBrainMaskIdx, dtype=numpy.float32), standardCentroid.reshape(3,1)) print "Standard size: " + str(numpy.asarray(nibMNIData.shape)) + ' Max: ' + str(numpy.max(nibMNIData.ravel())) + ' Min: ' + str(numpy.min(nibMNIData.ravel())) #=============================================================================== # Do BET, save mask to nifti... #=============================================================================== img = nib.AnalyzeImage( nimBabelData, nimBabelAffine ) img.to_filename(niftiDir + niftiFileBaseName) if not os.path.exists(niftiDir + niftiFileBaseName + '_mask.hdr'): commandBET = '%sbet.exe %s%s %s%s -m -s -n' % (betDir, niftiDir, niftiFileBaseName, niftiDir, niftiFileBaseName) with open(os.devnull, "w") as fnull: subprocBET = subprocess.call( commandBET, stdout = fnull, stderr = fnull ) analBabel = nib.load(niftiDir + niftiFileBaseName + '_mask.hdr') analBabelData = analBabel.get_data() analMaskDataTmp = numpy.asarray(analBabelData, dtype='int') analMaskData = numpy.reshape(analMaskDataTmp, [analMaskDataTmp.shape[0], analMaskDataTmp.shape[1], analMaskDataTmp.shape[2]]) maskImg = nib.Nifti1Image(analMaskData, None, nimBabel.get_header()) nib.save(maskImg, niftiDir +niftiFileBaseName + '_mask.nii.gz') nibInputBrainMask = nib.load(niftiDir +niftiFileBaseName + '_mask.nii.gz') inputBrainMaskIdx = numpy.nonzero( analMaskData > 0 )
def run_script(input_dir, output_dir): """ Run the commandline script for GHMM. :param input_dir (str): full path to the data folder output_dir (str): full path to the output folder """ """+++++++++++++++++++++++++++++++++++""" print(""" Step 0. load dataset """) print("+++++++Read the image template file+++++++") template_name = input_dir + 'template.img' temp_img = nib.load(template_name) template = temp_img.get_data() num_vox = len(template[template == 1]) print("The image size of all image data is " + str(temp.shape)) print("+++++++Read the image data+++++++") img_folder_name = input_dir + "image" img_names = glob.glob("%s/*.img" % img_folder_name) num_img = len(img_names) img_data = np.zeros(shape=(num_img, num_vox)) for ii in range(num_img): img_ii = nib.load(img_names[ii]) imgdata_ii = img_ii.get_data() img_data[ii, :] = imgdata_ii[template == 1] print("The matrix dimension of image data is " + str(img_data.shape)) print("+++++++Read the covariate data+++++++") design_data_file_name = input_dir + "design_data.txt" design_data = np.loadtxt( design_data_file_name) # [the subject ID, visit time] (numeric) subject_id = np.unique(design_data[:, 0]) num_sub = len(subject_id) print("The number of subjects is " + str(num_sub)) print("+++++++Read the diagnostic information+++++++") dx_data_file_name = input_dir + "dx_data.txt" dx = np.loadtxt(dx_data_file_name) print("The number of normal subjects is " + str(num_sub[dx == 0])) print("The number of diseased subjects is " + str(num_sub[dx > 0])) """+++++++++++++++++++++++++++++++++++""" print("""Step 1. Preliminary settings""") start_1 = time.time() y_design = np.zeros(shape=(num_sub, num_vox)) visit_data = design_data[:, 1] p = 2 x_design = np.zeros(shape=(num_sub, p)) for i in range(num_sub): sub_i_idx = design_data[:, 1] == subject_id[i] num_visit = len(sub_i_idx) y_design[i, :] = img_data[sub_i_idx[num_visit], :] - img_data[ sub_i_idx[0], :] x_design[i, :] = [ 1, visit_data[sub_i_idx[num_visit], :] - visit_data[sub_i_idx[0], :] ] print( "+++++++Step 1.1: Set up linear mixed model on all voxels from normal subjects+++++++" ) [beta, s2] = lmm_fun(y_design, x_design, dx)[0] print( "+++++++Step 1.2: Initial the diseased regions from patients (k-means)+++++++" ) nclasses = 2 [b_0, mu] = initial_b_fun(y_design, x_design, dx, template, beta, nclasses) stop_1 = time.time() print("The cost time in Step 1 is %(t1) d" % {"t1": stop_1 - start_1}) """+++++++++++++++++++++++++++++++++++""" print("""Step 2. Diseased region detection based on HMRF and EM""") start_2 = time.time() em_iter = 10 map_iter = 10 gamma = 0.2 # smooth parameter for out_it in range(em_iter): # update b via MAP algorithm b_0, mu = map_fun(b_0, x_design, y_design, dx, template, beta, mu, s2, gamma, nclasses, map_iter) b = b_0 stop_2 = time.time() print("The cost time in Step 2 is %(t2) d" % {"t2": stop_2 - start_2}) """+++++++++++++++++++++++++++++++++++""" print("""Step 3. Save the detected regions into image""") for ii in range(b.shape[0]): b_i = np.reshape(b[ii, :], template.shape) ana_img = nib.AnalyzeImage(b_i, np.eye(4)) output_file_name = output_dir + 'b_%s.img' % ii nib.save(ana_img, output_file_name) if __name__ == '__main__': input_dir0 = sys.argv[1] output_dir0 = sys.argv[2] start_all = time.time() run_script(input_dir0, output_dir0) stop_all = time.time() delta_time_all = str(stop_all - start_all) print("The total elapsed time is " + delta_time_all)
for sd in range(len(ds_all)) ] ds_fstre = [featsel[i].forward(sd) for i, sd in enumerate(ds_all)] #save correaltion masks for s in np.arange(len(ds_fs)): mask = nib.load(vt_list[s]) data = mask.get_data() affine = mask.get_affine() idx = ds_fs[s].fa['voxel_indices'] idx = np.array(idx) zero = np.zeros((91, 109, 91)) for i in idx: zero[i[0], i[1], i[2]] = data[i[0], i[1], i[2]] img = nib.AnalyzeImage(zero, affine=affine) nib.save(img, save_list[s]) print nib.save(img, save_list[s]) del (zero) del (img) #BEST 300 for s in np.arange(len(ds_fstre)): mask = nib.load(vt_list[s]) data = mask.get_data() affine = mask.get_affine() idx = ds_fstre[s].fa['voxel_indices'] idx = np.array(idx) zero = np.zeros((91, 109, 91)) for i in idx: zero[i[0], i[1], i[2]] = data[i[0], i[1], i[2]]
self.pdata[:,:,:,i]=self.pdata[:,:,:,i]*self.slopes[i] elif self.dim==2: rslopes=np.reshape(self.slopes,self.shape[2:]) for j in range(self.shape[2]): for i in range(self.shape[3]): self.pdata[:,:,j,i]=self.pdata[:,:,j,i] #self.pdata[:,:,j,i]=self.pdata[:,:,j,i]*rslopes[j,i] print "Enter the scan directory." root = Tkinter.Tk() while True: rootdir = tkFileDialog.askdirectory(initialdir="/",title='Please select a directory') if os.path.isdir(rootdir) is True: #Checks if entered dir exists os.chdir(rootdir) root.destroy() break else: print "Pathname invalid. Try again." continue os.chdir(rootdir) filelist = glob.glob('*.hdr') for f in filelist: i=Bruker2AnalyzeImg(f[:-4]) i.correctSlope() im = nib.AnalyzeImage(i.pdata, i.affine) nib.save(im, f[:-4] + '_RS.hdr')
PipelineScripts = '/home/NRG/jwilso01/dev/Pipelines/PreFreeSurfer/scripts/' GlobalScripts = '/nrgpackages/tools/HCP/scripts/' TemplateDir = '/nrgpackages/atlas/HCP/' ConfigDir = '/nrgpackages/tools/HCP/conf/' #=============================================================================== # build input nifti path and file... #=============================================================================== niftiPath = niftiDir + os.sep + Subject + os.sep + niftiFileType niftiPathName = niftiPath + os.sep + niftiFileName nimBabel = nib.load(niftiPathName) #nimData = nimBabel.get_data() #print nimBabel.header_class.binaryblock, nimBabel.file_map, print nimBabel.get_sform() , nimBabel.get_header(), nimBabel.to_file_map() img = nib.AnalyzeImage( nimBabel, nimBabel.get_sform(), header=nimBabel.get_header(), extra=None, file_map=nimBabel.to_file_map() ) nib.loadsave.save(img, 'foo') #nipNipyData = nip.load_image(niftiFile) #nipNipyDataSz = nipNipyData.shape #=============================================================================== # set up directories... #=============================================================================== xfmsDir = niftiDir + os.sep + Subject + os.sep + niftiFileType + os.sep + 'xfms' if not os.path.exists(xfmsDir): os.makedirs(xfmsDir) ACPCdir = niftiDir + os.sep + Subject + os.sep + niftiFileType + os.sep + 'ACPCAlignment' if not os.path.exists(ACPCdir): os.makedirs(ACPCdir)
def save(t1_path, save_path, segmentation): t1_affine = nib.load(t1_path).get_affine() segmentation = np.array(segmentation, dtype=np.uint8) seg = nib.AnalyzeImage(segmentation, t1_affine) nib.save(seg, save_path)
pt_pixel_data = pt.get_fdata() # apply threshold thres = np.max(pt_pixel_data) * args["thresholdfactor"] # print(np.max(pt_pixel_data), args["thresholdfactor"]) thres_mask = pt_pixel_data < thres # print(thres_mask) pt_pixel_data[thres_mask] = 0 # # get pixel data of filled bb fbb = nib.load(args["filledboundingbox"]) fbb_pixel_data = fbb.get_fdata() fbb_pixel_data = np.squeeze(fbb_pixel_data) # overlayhelper.overlay_helper( # roiData=fbb_pixel_data, imageData=pt_pixel_data, title="pt") # # change this to mask fbb_pixel_mask = np.where(fbb_pixel_data > 0, 1, 0) # print(np.max(fbb_pixel_mask)) # # use mask to intersect pt_roi = pt_pixel_data * fbb_pixel_mask print(np.max(pt_roi)) pt_roi = np.where(pt_roi > 0, 1, 0).astype("int16") overlayhelper.overlay_helper(imageData=pt_roi, title=args["outputname"]) pt_roi_a75 = nib.AnalyzeImage(pt_roi, affine=np.eye(4)) nib.save(pt_roi_a75, args["outputname"]) # # export output as .img .hdr pair