def trace_multib(self, sc=True, mask=True): from PythonDiffusion import rescaleImage from ImProcessing import T2regression_basic if sc: print "Applying slope correction..." rescaleImage(self) shape = list(self.shape) shape[ -1] = self.ndirs + 3 #ndirs+3 volumes: A0, trace_total, trace_average, and ndirs*traces trace = np.zeros(shape) a0 = np.average(self.pdata[:, :, :, :self.nA0], axis=-1) #take mean of all A0s #fit all directions at once self.adc, self.stdevmap, self.si0map, self.adcfig = T2regression_basic( self.pdata, np.array(self.bvals), mask=mask) trace[:, :, :, 1] = 1.0 / self.adc #and separate dirs for i in range(self.ndirs): print "dir", i + 1 bv = list(self.bvals[:self.nA0]) + list( self.bvals[self.nA0 + i * self.ndirs:self.nA0 + (i + 1) * self.nbvals]) si = np.concatenate( (self.pdata[:, :, :, :self.nA0], self.pdata[:, :, :, self.nA0 + i * self.ndirs:self.nA0 + (i + 1) * self.nbvals]), axis=-1) self.adcn, self.stdevmapn, self.si0mapn, self.adcfign = T2regression_basic( si, np.array(bv), mask=mask) trace[:, :, :, 3 + i] = 1.0 / self.adcn trace[:, :, :, 2] = np.average(trace[:, :, :, 3:], axis=-1) trace[:, :, :, 0] = a0 self.trace = trace
def __init__(self, name): #metadata self.name=name self.filetype=checkFileType(self.name) self.img=nib.load(self.name+self.filetype) self.hdr=self.img.get_header() self.protocol=read_line("VisuAcquisitionProtocol=",self.name) self.date=read_line("Subject_date=",self.name) try: self.nrep=int(list_values(read_line("NRepetitions=",self.name))[0]) except IndexError: self.nrep=1 #arrays try: self.data=self.img.get_data() except MemoryError: self.data=None warnings.warn('MemoryError. Image array too large for available memory.') self.affine=self.img.get_affine() #geometric self.resolution=getResolution(self.name) self.dim=int(list_values(read_line("VisuCoreDim=",self.name))[0]) # if self.dim==2: # self.data=scipy.swapaxes(self.data,2,3) self.shape=self.data.shape self.position=list_values(read_line("VisuCorePosition=",self.name)) self.zposition=self.position[2] if self.dim==3: self.zthickness=self.resolution[2] elif self.dim==2: self.zthickness=list_values(read_line("VisuCoreFrameThickness=",self.name))[0] self.slopes=list_values(read_line("VisuCoreDataSlope=",self.name)) self.slicegap=list_values(read_line("SliceGap=",self.name))[0] self.slicedistance=list_values(read_line("SliceDistance=",self.name))[0] #scan parameters self.te=[list_values(read_line("EffectiveEchoTime=",self.name))] if len(self.te)==1: self.te=self.te[0] self.tr=list_values(read_line("RepetitionTime=",self.name)) if len(self.tr)==1: self.tr=self.tr[0] self.flipangle=list_values(read_line("FlipAngle=",self.name)) #processing output self.pdata=np.array(self.data) if self.nrep>1: from PythonDiffusion import rescaleImageC:\Users\s0203524\Desktop\test print "Multiple repetitions. Correcting slope first." rescaleImage(self) print "Averaging across %r repetitions..." %self.nrep interv=self.pdata.shape[3]/self.nrep nz=np.zeros([self.shape[0],self.shape[1],self.shape[2],interv]) for i in range(self.nrep): nz+=self.pdata[:,:,:,i*interv:(i+1)*interv] self.pdata=nz/self.nrep self.shape=self.pdata.shape
def processDiffusion(self,ec=False, bv=None): print "Processing diffusion, full pipeline." from PythonDiffusion import rescaleImage, eddyCorrection from datetime import datetime if self.nrep==1: print "Applying slope correction..." rescaleImage(self) if ec: print "ec=True. Applying eddy current correction." eddyCorrection(self,self.name+'_EC', protocol='eddy_v') self.tensorFit(bv=bv)
def __init__(self, name, repetition_avg=True): #metadata Br2AInfo.__init__(self, name) self.img = nib.load(self.name + self.filetype) #arrays try: self.data = self.img.get_data() except MemoryError: self.data = None warnings.warn( 'MemoryError. Image array too large for available memory.') self.affine = self.img.get_affine() #geometric self.resolution = getResolution(self.name) self.dim = int(list_values(read_line("VisuCoreDim=", self.name))[0]) # if self.dim==2: # self.data=scipy.swapaxes(self.data,2,3) self.shape = self.data.shape self.position = list_values(read_line("VisuCorePosition=", self.name)) self.zposition = self.position[2] if self.dim == 3: self.zthickness = self.resolution[-1] elif self.dim == 2: self.zthickness = list_values( read_line("VisuCoreFrameThickness=", self.name))[0] self.slopes = list_values(read_line("VisuCoreDataSlope=", self.name)) self.slicegap = list_values(read_line("SliceGap=", self.name))[0] self.slicedistance = list_values(read_line("SliceDistance=", self.name))[0] #processing output self.pdata = np.array(self.data) if repetition_avg: if self.nrep > 1: from PythonDiffusion import rescaleImage print "Multiple repetitions. Correcting slope first." rescaleImage(self) print "Averaging across %r repetitions..." % self.nrep interv = self.pdata.shape[3] / self.nrep nz = np.zeros( [self.shape[0], self.shape[1], self.shape[2], interv]) for i in range(self.nrep): nz += self.pdata[:, :, :, i * interv:(i + 1) * interv] self.pdata = nz / self.nrep self.shape = self.pdata.shape
def trace_1b(self, sc=True): '''Calculates diffusion trace. ln(S/S0)=exp(-b*ADC)''' from PythonDiffusion import rescaleImage if sc: print "Applying slope correction..." rescaleImage(self) shape = list(self.shape) shape[ -1] = self.ndirs + 2 #ndirs+2 volumes: A0, trace_average, and ndirs*traces trace = np.zeros(shape) a0 = np.average(self.pdata[:, :, :, :self.nA0], axis=-1) #take mean of all A0s for i in range(self.ndirs): dwi = self.pdata[:, :, :, self.nA0 + i] trace[:, :, :, 2 + i] = -np.log(dwi / a0) / self.bvals[self.nA0 + i] trace[:, :, :, 0] = a0 #to draw rois trace[:, :, :, 1] = np.average(trace[:, :, :, 2:], axis=-1) self.trace = trace
def processDiffusion(self, ec=False, bv=None, mode='dti', removea0=0, mask=True): print "Processing diffusion, full pipeline." from PythonDiffusion import rescaleImage, eddyCorrection from datetime import datetime if self.nrep == 1: print "Applying slope correction..." rescaleImage(self) if ec: print "ec=True. Applying eddy current correction." eddyCorrection(self, self.name + '_EC', protocol='eddy_correct') if mode == 'dti' or mode == 'RESTORE': self.tensorFit(bv=bv, removea0=removea0, m=mode, mask=mask) elif mode == 'dki': self.processKurtosis()
if os.path.isfile(dtimg.name+'_EC.nii.gz') or os.path.isfile(dtimg.name+'_EC.nii'): print "Found EC file. Not running new eddy current correction." if os.path.isfile(dtimg.name+'_EC.nii.gz'): dtimg.pdata=nib.load(dtimg.name+'_EC.nii.gz').get_data() elif os.path.isfile(dtimg.name+'_EC.nii'): dtimg.pdata=nib.load(dtimg.name+'_EC.nii').get_data() try: dtimg.tensorFitAllBvs() except ValueError: print "Matrices not aligned." else: try: from PythonDiffusion import rescaleImage, eddyCorrection if dtimg.nrep==1: print "Applying slope correction..." rescaleImage(dtimg) if ec: print "ec=True. Applying eddy current correction." eddyCorrection(dtimg,dtimg.name+'_EC', protocol='eddy_correct') dtimg.tensorFitAllBvs() except ValueError: print "Matrices not aligned." pl.close() else: print "Can't process this image, sorry." timecomp = datetime.now()-startTime print "Process took %rs to complete." %timecomp.seconds
def main(): print "Enter the scan directory where the diffusion-weighted images are stored." 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) print "Found %r Analyze images in directory." % len(glob.glob('*.img')) print "Scan types found: ", list_scans() filelist = [x.replace('.img', '') for x in glob.glob('*.img') ] #cool list comprehension that gets all files for ind, filen in enumerate(filelist): startTime = datetime.now() print "\nFile %r of %r. Filename: %s" % (ind + 1, len(filelist), filen) try: im = Br2AInfo(filen) except AttributeError: print "Error. No text file found." continue except IOError: warnings.warn("Cannot find .hdr or .img file.") continue print "Scan type: ", im.protocol if ("dti" in im.protocol.lower() or "dki" in im.protocol.lower() or "diff" in im.protocol.lower()) and im.name[-1] == '1': dtimg = DiffusionImg(filen) if not (len(dtimg.bvals) >= 1 and len(dtimg.dwdir) > 1): print "Diffusion image found, but insufficient diffusion dirs or b-vals." continue #eddy current correction step if os.path.isfile(dtimg.name + '_EC.nii.gz') or os.path.isfile(dtimg.name + '_EC.nii'): print "Found EC file. Not running new eddy current correction." if os.path.isfile(dtimg.name + '_EC.nii.gz'): dtimg.pdata = nib.load(dtimg.name + '_EC.nii.gz').get_data() elif os.path.isfile(dtimg.name + '_EC.nii'): dtimg.pdata = nib.load(dtimg.name + '_EC.nii').get_data() else: try: if dtimg.nrep == 1: from PythonDiffusion import rescaleImage print "Applying slope correction..." rescaleImage(dtimg) dtimg.eddyCorrection(FILENAME, REF, PROTOCOL) except ValueError: print "Matrices not aligned." #saving output save_dsi_src(dtimg, SRC_FILENAME, REMOVE_A0) #performing command line stuff if DSI_STUDIO_PROCESS: command = "" subprocess.call(command, shell=True) del dtimg else: print "Can't process this image, sorry."
elif self.dim == 2: rslopes = np.reshape(self.slopes, self.shape[:-3:-1]) rslopes = scipy.swapaxes(rslopes, 0, 1) for j in range(self.shape[2]): for i in range(self.shape[3]): self.pdata[:, :, j, i] = self.pdata[:, :, j, i] * rslopes[j, i] else: print "No b-values found or cannot process slope formatting." 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]) rescaleImage(i) im = nib.AnalyzeImage(i.pdata, i.affine) nib.save(im, f[:-4] + '_RS.hdr')