def createDataset(svmName='',roiName='',labFiles=[],niiFiles=[],lab1='',lab2=''): """ Workhorse... """ if os.path.exists(svmName): print('Overwriting {0}.'.format(svmName)) os.remove(svmName) for labF, niiF in zip(labFiles, niiFiles): print(niiF,labF) ## Get the needed data vtc = nf.NiftiImage(niiF) roi = nf.NiftiImage(roiName) vols, labels = pre.readLabList(labF) ## Preprocess the data reducedRoi = pre.roiReduce(roi,vtc) maskedVtc = pre.maskVtc(vtc,reducedRoi) reference = pre.createRefVtc(maskedVtc) ## Filter labels and vols by trainLab1, trainLab2 ## then change recode the labels as 1 and 2 l1mask = labels == lab1 l2mask = labels == lab2 l1l2mask = l1mask != l2mask labels[l1mask] = 1 labels[l2mask] = 2 vols = vols[l1l2mask] labels = labels[l1l2mask] pre.writeSVM(maskedVtc,reference,labels,vols,svmName) else: print('Z-normalizing the data.') pre.zSparse(svmName)
def test_er_nifti_dataset_mapping(): """Some mapping testing -- more tests is better """ # z,y,x sample_size = (4, 3, 2) # t,z,y,x samples = np.arange(120).reshape((5, ) + sample_size) dsmask = np.arange(24).reshape(sample_size) % 2 if externals.exists('nibabel'): import nibabel tds = fmri_dataset(nibabel.Nifti1Image(samples.T, None), mask=nibabel.Nifti1Image(dsmask.T, None)) else: import nifti tds = fmri_dataset(nifti.NiftiImage(samples), mask=nifti.NiftiImage(dsmask)) ds = eventrelated_dataset(tds, events=[ Event(onset=0, duration=2, label=1, chunk=1, features=[1000, 1001]), Event(onset=1, duration=2, label=2, chunk=1, features=[2000, 2001]) ]) nfeatures = tds.nfeatures mask = np.zeros(dsmask.shape, dtype='bool') mask[0, 0, 0] = mask[1, 0, 1] = mask[0, 0, 1] = 1 fmask = ds.a.mapper.forward1(mask.T) # select using mask in volume and all features in the other part ds_sel = ds[:, fmask] # now tests assert_array_equal(mask.reshape(24).nonzero()[0], [0, 1, 7]) # two events, 2 orig features at 2 timepoints assert_equal(ds_sel.samples.shape, (2, 4)) assert_array_equal(ds_sel.sa.features, [[1000, 1001], [2000, 2001]]) assert_array_equal(ds_sel.samples, [[1, 7, 25, 31], [25, 31, 49, 55]]) # reproducability assert_array_equal(ds_sel.samples, ds_sel.a.mapper.forward(np.rollaxis(samples.T, -1))) # reverse-mapping rmapped = ds_sel.a.mapper.reverse1(np.arange(10, 14)) assert_equal(np.rollaxis(rmapped, 0, 4).T.shape, (2, ) + sample_size) expected = np.zeros((2, ) + sample_size, dtype='int') expected[0, 0, 0, 1] = 10 expected[0, 1, 0, 1] = 11 expected[1, 0, 0, 1] = 12 expected[1, 1, 0, 1] = 13 assert_array_equal(np.rollaxis(rmapped, 0, 4).T, expected)
def maskVtc(roi_vmr,vtc,vol): """ Creates a bool mask everywhere the roi data is greater than 2. Roi needs to a nifti object resulting from imported vmr data. Then uses the roiMask to extract that data at the appropriate voxels from vtc (a 4D nifti object). It should probably be applied to the vtcdata, the labelVtc, and refVtc. - roiVmr and vtc(x,y,z) must have indentical dimensions. - 'vol' is the volumne number of the vtc data you wish to mask - NOTE: To convert a voi to vmr use the ROI window in Brainvoyager. Select Options, then the 'VOI functions' tab, and select 'Create MSK...', give the file a name (it does not matter what as this file is not needed). Once that is done go to the File menu and select 'Save secondary VMR'. The result- ing file is wh)t should be read in with NiftiImage(). - Returns a (t=1,x,y,z) nifit object if roi masked vtc data w/ correct header info. """ roi_data = roiVmr.data # roiData = np.round(roiData) # VMR data contain very small non-zero deicmal entries # (e.g. 235.000011 or 0.0000124) where there should be empty # decimals (235.0000000). masked_vtc = np.zeros(roi_vmr, dtype="uint32") ## create a ref (later upscaled) to find redundant voxels ref = createRef(vtc.data[1,...]) ref_vtc = nf.NiftiImage(ref[np.newaxis,...]) # vtc NiftiImage obj # needed for resizeVtc() ref_resize = resizeVtc(roi_vmr,ref_vtc,1) ## Create roi_mask then falsify redundant ## entries; keep on the the first roi_mask = roi_data > 2 for uni in np.unique(ref_resize.data): ind = np.where(uni == ref_resize.data) ind = (ind[0][1:],ind[1][1:],ind[2][1:]) roi_mask[ind] = False ## rescale the vtc vol to match the vmr ## mask that vols data and store in ## masked_vtc vol_resize = resizeVtc(roi_vmr,vtc,vol) masked_vtc = np.where(roi_mask,vol_resize,0) # create t, set to 1 return nf.NiftiImage(masked_vtc, vtc.header)
def __init__(self, inputDirectory, outputDirectory, **kwargs): # Extend passed properties and invoke uperclass constuctor kwargs.update(atlasparserProperties) bar.barBitmapParser.__init__(self, **kwargs) self.inputDirectory = inputDirectory self.outputDirectory= outputDirectory # Define source dataset location and initialize parser by loading # source dataset sourceFilename = 'canon_labels_r.nii' volumetricFile = os.path.join(inputDirectory,sourceFilename) self._volumeSrc = nifti.NiftiImage(volumetricFile) self._volume = self._volumeSrc.data[0] #Some properties cannot be predefined, adding them now: self.setProperty('outputDirectory', outputDirectory) # set structure name -> structure colour mapping fullnameMappingFile = os.path.join(self.inputDirectory,'fullnames.txt') structureColours = getDictionaryFromFile(fullnameMappingFile, 0, 2) self.setProperty('structureColours', structureColours) self.indexer.colorMapping=structureColours self.slideRange = map(lambda x: 1023 - x, range(0,1024)) self._pathNumber = 0 # Set indexer properties self.indexer.updateProperties(indexerProperties)
def upsampleVtc(vtc, by, vol): """ [9/1/2011]: This function replaces roiReduce(), which has been depricated; input/output data formats are changed between the two; the volume in the vtc data to act on was added. resizeVtc() takes a vmr and vtc NiftiImage() objects (converted to .nii files of course), and alters the x, y, z, dimentions of the vtc to match the vmr by nearest neighbor interpolation. - Requires resize_worker() NOTE: Upscaled vtc data can become VERY large. For example, 270 volumes at 256x256x256 occupies over 18 GBs. Returns: the resolution altered volume for in vtc stored as a NiftiImage object, the header is dropped. """ print("Vol: {0}".format(vol)) intial_dim = vtc.data.shape[1:] final_dim = (intial_dim[0]*by[0], intial_dim[1]*by[1],intial_dim[2]*by[2]) resized_vtc_data = resize3d(vtc.data[vol,:,:,:],intial_dim,final_dim) return nf.NiftiImage(resized_vtc_data,vtc.header)
def create_nii_from_binary(): import nifti np_files = [f for f in os.listdir(np_file_addresses) if f.endswith('.npy')] for np_file in np_files: image = np.load(np_file_addresses + np_file) print image.shape nifti_image = nifti.NiftiImage(image.astype('uint16')) nifti_image.save(nifti_file_base + np_file[:-4] + '.nii')
def Update(self): print "Loading ", self.__filename #read in the data after directory was set self.__nim = nifti.NiftiImage(self.__filename) self.__data = self.__nim.asarray().astype("f") #del self.__nim #XXX the conversion to Numeric could be very expensive #think about it... self.__vtkimport.SetArray(Numeric.array(self.__data)) self.SetDataSpacing(self.__nim.getVoxDims()) #to reverse: [::-1]
def __init__(self, path): """Reads all information from the given MELODIC output path. """ self.__outputpath = path self.__icapath = os.path.join(path, 'filtered_func_data.ica') self.__ic = \ nifti.NiftiImage( os.path.join( self.__icapath, 'melodic_IC' ) ) self.__funcdata = \ nifti.NiftiImage( os.path.join( self.__outputpath, 'filtered_func_data' ) ) self.__tmodes = np.fromfile(os.path.join(self.__icapath, 'melodic_Tmodes'), sep=' ').reshape(self.tr, self.nic) self.__smodes = np.fromfile(os.path.join(self.__icapath, 'melodic_Smodes'), sep=' ') self.__icstats = np.fromfile(os.path.join(self.__icapath, 'melodic_ICstats'), sep=' ').reshape(self.nic, 4)
def __loadVolume(self, volumeFilename): """ Loads volumetric dataset, store header and volume data @type volumeFilename: C{str} @param volumeFilename: full location of volumetric dataset @rtype: C{None} @return: None """ self._volumeSrc = nifti.NiftiImage(volumeFilename) self._volume = self._volumeSrc.data self._volumeHeader = self._volumeSrc.header
def downsampleVmr(vmr, by): """ Uses PIL (python imaging library) to resize the x, y and z dimensions of the given vmr to match that of vtc. -Returns: a the resized vmr in a NiftiImage object. """ intial_dim = vmr.data.shape # TODO test for int? How to deal with fractions here... final_dim = (by[0]/intial_dim[0],by[1]/intial_dim[1],by[2]/intial_dim[0]) resized_vmr_data = resize3d(vmr.data,intial_dim,final_dim) return nf.NiftiImage(resized_vmr_data,vmr.header)
def test_nifti_dataset_from3_d(): """Test NiftiDataset based on 3D volume(s) """ tssrc = os.path.join(pymvpa_dataroot, 'bold.nii.gz') masrc = os.path.join(pymvpa_dataroot, 'mask.nii.gz') # Test loading of 3D volumes # by default we are enforcing 4D, testing here with the demo 3d mask ds = fmri_dataset(masrc, mask=masrc, targets=1) assert_equal(len(ds), 1) if externals.exists('nibabel'): import nibabel plain_data = nibabel.load(masrc).get_data() # Lets check if mapping back works as well assert_array_equal(plain_data, map2nifti(ds).get_data().reshape(plain_data.shape)) else: import nifti plain_data = nifti.NiftiImage(masrc).data # Lets check if mapping back works as well assert_array_equal(plain_data, map2nifti(ds).data.reshape(plain_data.shape)) # test loading from a list of filenames # for now we should fail if trying to load a mix of 4D and 3D volumes assert_raises(ValueError, fmri_dataset, (masrc, tssrc), mask=masrc, targets=1) # Lets prepare some custom NiftiImage dsfull = fmri_dataset(tssrc, mask=masrc, targets=1) ds_selected = dsfull[3] nifti_selected = map2nifti(ds_selected) # Load dataset from a mix of 3D volumes # (given by filenames and NiftiImages) labels = [123, 2, 123] ds2 = fmri_dataset((masrc, masrc, nifti_selected), mask=masrc, targets=labels) assert_equal(ds2.nsamples, 3) assert_array_equal(ds2.samples[0], ds2.samples[1]) assert_array_equal(ds2.samples[2], dsfull.samples[3]) assert_array_equal(ds2.targets, labels)
def exportToNiftii(self, filename): """ Export the reconstructed volume to a Niftii file. @param filename: the name of the file @type filename: str """ vtkVolume = self.vtkVolume.GetOutput() nim = nifti.NiftiImage(VTKtoNumpy(vtkVolume)) nim.setVoxDims(list(vtkVolume.GetSpacing())) h = nim.header h['qoffset'] = list(vtkVolume.GetOrigin()) h['qform_code'] = 1 #Print header in debug mode if __debug__: print sys.stderr, h nim.header = h # http://nifti.nimh.nih.gov/nifti-1/documentation/nifti1fields/nifti1fields_pages/qsform.html nim.save(filename)
def test_fmridataset(): # full-blown fmri dataset testing if externals.exists('nibabel'): import nibabel maskimg = nibabel.load(os.path.join(pymvpa_dataroot, 'mask.nii.gz')) data = maskimg.get_data().copy() data[data > 0] = np.arange(1, np.sum(data) + 1) maskimg = nibabel.Nifti1Image(data, None, maskimg.get_header()) else: import nifti maskimg = nifti.NiftiImage(os.path.join(pymvpa_dataroot, 'mask.nii.gz')) # assign some values we can check later on maskimg.data.T[maskimg.data.T > 0] = np.arange( 1, np.sum(maskimg.data) + 1) attr = SampleAttributes(os.path.join(pymvpa_dataroot, 'attributes.txt')) ds = fmri_dataset(samples=os.path.join(pymvpa_dataroot, 'bold.nii.gz'), targets=attr.targets, chunks=attr.chunks, mask=maskimg, sprefix='subj1', add_fa={'myintmask': maskimg}) # content assert_equal(len(ds), 1452) assert_true(ds.nfeatures, 530) assert_array_equal(sorted(ds.sa.keys()), ['chunks', 'targets', 'time_coords', 'time_indices']) assert_array_equal(sorted(ds.fa.keys()), ['myintmask', 'subj1_indices']) assert_array_equal(sorted(ds.a.keys()), ['imghdr', 'mapper', 'subj1_dim', 'subj1_eldim']) # vol extent assert_equal(ds.a.subj1_dim, (40, 20, 1)) # check time assert_equal(ds.sa.time_coords[-1], 3627.5) # non-zero mask values assert_array_equal(ds.fa.myintmask, np.arange(1, ds.nfeatures + 1))
def preprocessVolume(outputDirectory, outputFilename): """ Process the raw input volume into niftii labelled volume with full information about coordinate system. @type outputDirectory: str @param outputDirectory: Directory containing source dataset. @type outputFilename: str @param outputFilename: Name of the output volume @return: None """ # Load labelled volume from the raw binary file using numpy. The values are # stored as unsigned short integers one after another. After loading all # values, resulting array is reshaped to match the atlas volume shape. annotationVolumeFilename = os.path.join(outputDirectory, ANNOTATION_PATH) fd = open(annotationVolumeFilename, 'rb') read_data = numpy.fromfile(file=fd, dtype=numpy.uint16).reshape(VOLUME_DIMENSIONS) # We are trying to reorient the volume into TODO: RAI orientation, # hope that's correct. read_data = numpy.transpose(read_data, (1, 2, 0)) read_data = read_data[::-1, :, :] # Prepare nifti volume from numpy array. Create proper header and store all # of them into target volume file. annotatedVolume = nifti.NiftiImage(read_data) annotatedVolume.setVoxDims(OUTPUT_VOLUME_SPACING) annotatedVolumeHeader = annotatedVolume.header annotatedVolumeHeader['qoffset'] = OUTPUT_VOLUME_ORIGIN annotatedVolumeHeader['qform_code'] = 1 annotatedVolume.header = annotatedVolumeHeader outputPath = os.path.join(outputDirectory, outputFilename) annotatedVolume.save(outputPath)
def __init__(self, inputDirectory, outputDirectory, **kwargs): # Extend passed properties and invoke uperclass constuctor kwargs.update(atlasparserProperties) bar.barBitmapParser.__init__(self, **kwargs) self.inputDirectory = inputDirectory self.outputDirectory= outputDirectory # Define source dataset location and initialize parser by loading # source dataset sourceFilename = 'segmentation_in_uct_space.nii.gz' volumetricFile = os.path.join(inputDirectory, sourceFilename) self._volumeSrc = nifti.NiftiImage(volumetricFile) self._volumeHeader = self._volumeSrc.header self._volume = self._volumeSrc.data #Some properties cannot be predefined, adding them now: self.setProperty('outputDirectory', outputDirectory) # Assign structure abbreviation --> structure colour mapping # Assign structure abbreviation --> structure fullname mapping fullnameMappingFile = os.path.join(self.inputDirectory,'fullnames.txt') structureColours = getDictionaryFromFile(fullnameMappingFile, 1, 2) imageToStructure = getDictionaryFromFile(fullnameMappingFile, 0, 1) imageToStructure = dict( ('#'+k.lower(), v) for k, v in # small imageToStructure.iteritems()) # correction self.setProperty('structureColours', structureColours) self.setProperty('imageToStructure', imageToStructure) self.indexer.colorMapping = structureColours self._defineSlideRange(antPostAxis=2) self._pathNumber = 0 # Set indexer properties self.indexer.updateProperties(indexerProperties)
#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE *** #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW #log# opts = Struct({'__allownew': True, 'logfile': 'ipython_log.py'}) #log# args = [] #log# It is safe to make manual edits below here. #log#----------------------------------------------------------------------- import nifti as nf _ip.magic("cd /Users/type/Code/mvpa/") import preSVM as pre _ip.magic("cd /Volumes/more!/RWCR/data_mvpa") vmr = nf.NiftiImage('002_ISO_SAG_TAL.nii') vtc = nf.NiftiImage('002_01_SCCAI_3DMCT_THPGLMF2c_TAL.nii') impoty Image as im import Image as im import matplotlib.pyplot as plt plt.imshow(vtc.data[1,:,:,1],cmap=plt.cm.spectral) plt.imshow(vtc.data[1,:,:,20],cmap=plt.cm.spectral) plt.new_figure_manager plt.new_figure_manager() #?plt.new_figure_manager plt.figure() plt.imshow(vmr.data[:,:,80],cmap=plt.cm.Greys) vtc_single = vtc.data[20,:,:,20] plt.imshow(vtc_single) vtc_s_img = im.fromarray(vtc_single) vtc_s_img vtc_s_img.size vtc_i_re = vtc_s_img.resize((40*3,46*3)) vtc_i_re.size plt.imshow(vtc_i_re) plt.imshow(vtc_s_img)
#T1 AND M0 MAP FROM INVERSION-RECOVERY DATA. import nifti as nt import numpy as np import scipy as sp from scipy.optimize import curve_fit np.set_printoptions(threshold='nan') np.set_printoptions(formatter={'float': lambda x: "{0:0.3f}".format(x)}) rd = nt.NiftiImage( '/opt/Stroke Project/rat/IR-HighRes_fatSat/niifti/edited.nii') rd = np.array(rd.data, dtype=float) sz = rd.shape print sz x = np.array([500, 750, 1000, 1500, 2000, 3000, 5000, 7000]) tone = np.zeros((1, sz[2], sz[3]), dtype=float) mzero = np.zeros((1, sz[2], sz[3]), dtype=float) for sl in range(0, sz[1]):
def test_from_nifti(): nim = nifti.NiftiImage(data_file) yield nose.tools.assert_equals, as_volume_img(data_file), \ as_volume_img(nim)
import nifti #import nibabel as nib import os import numpy as np exclude_labels = [76, 44, 42, 41] exclude_names = ['spinal trigeminal tract', 'inner ear', 'optic tract and optic chiasm', 'optic nerve'] old_mask = nifti.NiftiImage(os.path.join("../dti_package/brain_mask.nii.gz")) d = nifti.NiftiImage(os.path.join("../dti_package/brain_atlas.nii.gz")) mask = old_mask.data r = d.data # for ii, label in enumerate(exclude_labels): # print 'Excluding: ', exclude_names[ii] # mask[r == label] = 0 # # mask[r > 0] = 1 # Create new refined mask # save_as = os.path.join("../dti_package/brain_mask_refined.nii.gz") # nifti.NiftiImage(mask, header=d.header).save(save_as) include_hippo_labels = [95, 96, 97, 98, 99, 100] hippo_names = ['cornu ammonis 1', 'dentate gyrus', 'cornu ammonis 2', 'cornu ammonis 3', 'fasciola cinereum', 'subiculum']
from collections import defaultdict import nibabel import nifti # open the file img = nibabel.load('talairach.nii') header = img.get_header() data = img.get_data() # extract labels nim = nifti.NiftiImage('talairach.nii') labels = nim.extensions[0].split('\n') # extract coordinates informations X, Y, Z = img.shape x0, y0, z0 = header.get('qoffset_x'), header.get('qoffset_y'), header.get('qoffset_z') # extract data values = defaultdict(list) for x in range(X): for y in range(Y): for z in range(Z): value = data[x, y, z] if value: values[value].append((x+x0, y+y0, z+z0)) print '%d / %d' % (x+1, X) # write to files i = 1 for value, coordinates in values.items(): label = labels[value]
def convert_nifti_to_numpy(nifti_file_address): import nifti return nifti.NiftiImage(nifti_file_address).getDataArray()
def _loadVolume(self, sourceFilename): volumetricFile = os.path.join(self.inputDirectory, sourceFilename) self._volumeSrc = nifti.NiftiImage(volumetricFile) self._volume = self._volumeSrc.data self._volumeHeader = self._volumeSrc.header
testLabsFiles = wordLab testNiiFiles = wordNii ## ================================================= ## from time import localtime, strftime svmBaseName = strftime("%a%d%b%Y_%H-%M-%S", localtime()) + svmBaseName # Add a timestamp to the SVM file name, preventing accidental # overwriting or modification. print('Creating training data:') for labF, niiF in zip(trainLabsFiles, trainNiiFiles): print(niiF,labF) ## Get the needed datword_a vtc = nf.NiftiImage(niiF) roi = nf.NiftiImage(roiVmr) vols, labels = pre.readLabList(labF) ## Preprocess the data reducedRoi = pre.roiReduce(roi,vtc) maskedVtc = pre.maskVtc(vtc,reducedRoi) reference = pre.createRefVtc(maskedVtc) ## Filter labels and vols by trainLab1, trainLab2 ## then change recode the labels as 1 and 2 l1mask = labels == trainLab1 l2mask = labels == trainLab2 l1l2mask = l1mask != l2mask labels[l1mask] = 1 labels[l2mask] = 2
# pynifti below. if not, we have stored the exception # and raise it below img = None pass else: # assume this is an image already img = src if isinstance(img, nibabel.spatialimages.SpatialImage): # nibabel image, dissect and return pieces return _get_txyz_shaped(img.get_data()), img.get_header() if externals.exists('nifti'): # maybe pynifti can help import nifti if isinstance(src, str): # filename img = nifti.NiftiImage(src) else: # assume this is an image already img = src if isinstance(img, nifti.NiftiImage): if externals.exists('nifti ge 0.20090205.1'): data = img.data else: data = img.asarray() # pynifti provides it transposed return _get_txyz_shaped(data.T), img.header # pending exception? if not excpt is None: raise excpt
import nifti as nt import numpy as np import scipy as sp from scipy.optimize import curve_fit np.set_printoptions(threshold='nan') np.set_printoptions(formatter={'float': lambda x: "{0:0.3f}".format(x)}) rd = nt.NiftiImage( '/opt/ime-157/data/Stroke-Project/rat/T2-SE/niifti/edited.nii') rd = np.array(rd.data, dtype=float) sz = rd.shape print sz x = np.array([10.6, 21.2, 31.8, 42.4, 53, 63.6, 74.2, 84.8, 95.4]) ttwo = np.zeros((1, sz[2], sz[3]), dtype=float) mzero = np.zeros((1, sz[2], sz[3]), dtype=float) for sl in range(4, 5): for cl in range(0, sz[2]):
def get_brainbrowser_image(self): """ Get image information and buffer: formated for BrainBrowser. Returns ------- im_info: dict the image information and buffer. """ # Get post parameters imagefile = self._cw.form["imagefile"] # Load the image im = nibabel.load(imagefile) header = im.get_header() try: data = im.get_data() # Missing bytes intern specific error that can be overcome with # an old lib except: import nifti im = nifti.NiftiImage(imagefile) data = im.getDataArray().T # Change the dynamic of the image intensities data = numpy.cast[numpy.uint16]( (data - data.min()) * 65535. / (data.max() - data.min())) # Format the output dim = header["dim"] order = ["time", "xspace", "yspace", "zspace"] if dim[0] == 3: header = { "order": order[1:], "xspace": { "start": float(header["qoffset_x"]), "space_length": int(dim[1]), "step": float(header["pixdim"][1]), "direction_cosines": [float(x) for x in header["srow_x"][:3]] }, "yspace": { "start": float(header["qoffset_y"]), "space_length": int(dim[2]), "step": float(header["pixdim"][2]), "direction_cosines": [float(x) for x in header["srow_y"][:3]] }, "zspace": { "start": float(header["qoffset_z"]), "space_length": int(dim[3]), "step": float(header["pixdim"][3]), "direction_cosines": [float(x) for x in header["srow_z"][:3]] }, } elif dim[0] == 4: header = { "order": order, "xspace": { "start": float(header["qoffset_x"]), "space_length": int(dim[1]), "step": float(header["pixdim"][1]), "direction_cosines": [float(x) for x in header["srow_x"][:3]] }, "yspace": { "start": float(header["qoffset_y"]), "space_length": int(dim[2]), "step": float(header["pixdim"][2]), "direction_cosines": [float(x) for x in header["srow_y"][:3]] }, "zspace": { "start": float(header["qoffset_z"]), "space_length": int(dim[3]), "step": float(header["pixdim"][3]), "direction_cosines": [float(x) for x in header["srow_z"][:3]] }, "time": { "start": 0, "space_length": int(dim[4]) } } data = numpy.transpose(data, (3, 0, 1, 2)) else: raise Exception("Only 3D or 3D + t images are currently supported!") # Format the output im_info = {"header": json.dumps(header), "data": data.flatten().tolist()} return im_info
import nifti as nt import numpy as np np.set_printoptions(threshold='nan') s1 = nt.NiftiImage('/opt/data/Scanner-Calibration/16-02-12/b.coil/01.nii') s1 = np.array(s1.data, dtype=float) s1[s1 < 40] = 'nan' s2 = nt.NiftiImage('/opt/data/Scanner-Calibration/16-02-12/r.coil/01.nii') s2 = np.array(s2.data, dtype=float) s2[s2 < 40] = 'nan' c = s1 / s2 wr = nt.NiftiImage(c) wr.save( '/opt/data/Scanner-Calibration/16-02-12/AFI/3_db_afi_seql/niifti/flipmap-II.nii' )
#SINGULAR VALUE DECOMPOSITION import nifti as nt import numpy as np import scipy as sp np.set_printoptions(threshold='nan') rd = nt.NiftiImage( '/opt/data/cort_map/Animal/Odd/2016-05-18/IR-TSE/SL-19/results/python_test/edtd.nii' ) rd = np.array(rd.data, dtype=int) sz = rd.shape print sz nvols = sz[0] nslices = sz[1] ncols = sz[2] nrows = sz[3] rd = np.reshape(rd, (nrows * ncols * nslices, nvols)) U, S, V = np.linalg.svd(rd, full_matrices=0)
#B1+ CORRECTION FOR PARAMETRIC MAPS import nifti as nt import numpy as np np.set_printoptions(threshold='nan') rdt1 = nt.NiftiImage('/opt/data/MTransfer/rev-agarMT/results/mt/t1map.nii') rdt1 = np.array(rdt1.data, dtype=float) rdfm = nt.NiftiImage( '/opt/data/MTransfer/rev-agarMT/results/flmap/flipmap.nii') rdfm = np.array(rdfm.data, dtype=float) rdfm[rdfm == 0] = 0.01 rdcor = rdt1 / rdfm img_wrt = nt.NiftiImage(rdcor) img_wrt.save('/opt/data/MTransfer/rev-agarMT/results/mt/fmcor_t1map.nii')
#PRINCIPAL COMPONENT ANALYSIS from matplotlib.mlab import PCA import nifti as nt import numpy as np import scipy as sp np.set_printoptions(threshold='nan') rd = nt.NiftiImage('/opt/ime-157/data/Lekshmi-training/edtd.nii') rd = np.array(rd.data) sz = rd.shape print sz nvols = sz[0] nslices = sz[1] ncols = sz[2] nrows = sz[3] rd = np.reshape(rd, (nrows * ncols * nslices, nvols)) res = PCA(rd)