def denoise(in_scan, out_scan, parameters={}): """Apply patch-based denoising Arguments: in `MriScan` input out `MriScan` output parameters `dict` of parameters """ use_anlm = parameters.get('anlm', False) denoise_beta = parameters.get('beta', 0.7) patch = parameters.get('patch', 2) search = parameters.get('search', 2) regularize = parameters.get('regularize', None) with mincTools() as minc: if use_anlm: minc.anlm(in_scan.scan, out_scan.scan, beta=denoise_beta, patch=patch, search=search) else: minc.nlm(in_scan.scan, out_scan.scan, beta=denoise_beta, patch=patch, search=search)
def pipeline_t1preprocessing(patient, tp): # checking if processing was performed if os.path.exists(patient[tp].qc_jpg['stx_t1']) \ and os.path.exists(patient[tp].clp['t1']) \ and os.path.exists(patient[tp].stx_xfm['t1']) \ and os.path.exists(patient[tp].stx_mnc['t1']) \ and os.path.exists(patient[tp].stx_ns_xfm['t1']) \ and os.path.exists(patient[tp].stx_ns_mnc['t1']): print(' -- pipeline_t1preprocessing was already performed') else: # # Run the appropiate version t1preprocessing_v10(patient, tp) # Writing QC images # ##################### # qc stx registration modeloutline = patient.modeldir + os.sep + patient.modelname + '_outline.mnc' with mincTools() as minc: minc.qc( patient[tp].stx_mnc['t1'], patient[tp].qc_jpg['stx_t1'], title=patient[tp].qc_title, image_range=[0, 120], mask=modeloutline, big=True, clamp=True, ) return True
def pipeline_concat(patient, tp): if os.path.exists(patient[tp].nl_xfm): print ' -- pipeline_concat already done!' ### with mincTools() as minc: # create QC images atlas_outline = patient.modeldir + os.sep + patient.modelname + '_outline.mnc' if not os.path.exists(patient[tp].qc_jpg['nl_t1']): minc.resample_smooth(patient[tp].stx2_mnc['t1'], minc.tmp('nl_stx_t1.mnc'), transform=patient[tp].nl_xfm) minc.qc( minc.tmp('nl_stx_t1.mnc'), patient[tp].qc_jpg['nl_t1'], title=patient[tp].qc_title, image_range=[0, 120], mask=atlas_outline, big=True, clamp=True, ) ### return True concat_v10(patient, tp) # beast by simon fristed
def concat_v10(patient, tp): with mincTools() as minc: tmp_xfm = minc.tmp('tmp_concat.xfm') minc.xfmconcat([patient[tp].lng_xfm['t1'], patient.nl_xfm], tmp_xfm) examplegrid = patient.nl_xfm[:-4] + '_grid_0.mnc' minc.xfm_normalize(tmp_xfm, examplegrid, patient[tp].nl_xfm, exact=True) # create QC images atlas_outline = patient.modeldir + os.sep + patient.modelname + '_outline.mnc' minc.resample_smooth(patient[tp].stx_mnc['t1'], minc.tmp('nl_stx_t1.mnc'), transform=patient[tp].nl_xfm) minc.qc( minc.tmp('nl_stx_t1.mnc'), patient[tp].qc_jpg['nl_t1'], title=patient[tp].qc_title, image_range=[0, 120], mask=atlas_outline, big=True, clamp=True, )
def average_transforms( samples, output, nl=False, symmetric=False, invert=False ): """average given transformations""" try: with mincTools() as m: avg = [] out_xfm=output.xfm for i in samples: avg.append(i.xfm) if symmetric: for i in samples: avg.append(i.xfm_f) if invert: out_xfm=m.tmp("average.xfm") xfmavg(avg, out_xfm) if invert: m.xfminvert(out_xfm, output.xfm) return True except mincError as e: print("Exception in average_transforms:{}".format(str(e)) ) traceback.print_exc(file=sys.stdout) raise except : print("Exception in average_transforms:{}".format(sys.exc_info()[0]) ) traceback.print_exc(file=sys.stdout) raise
def average_transforms_ldd( samples, output, symmetric=False, invert=False ): """average given transformations""" try: with mincTools() as m: avg = [] if not os.path.exists(output.vel): out=output.vel if invert: out=m.tmp('avg.mnc') for i in samples: avg.append(i.vel) if symmetric: for i in samples: avg.append(i.vel_f) m.average(avg, out) if invert: m.calc([out],'-A[0]',output.vel) except mincError as e: print("Exception in average_transforms_ldd:{}".format(str(e))) traceback.print_exc(file=sys.stdout) raise except : print("Exception in average_transforms_ldd:{}".format(sys.exc_info()[0])) traceback.print_exc(file=sys.stdout) raise
def create_grading_map(output_grading, output_map, lin_xfm=None, nl_xfm=None, template=None): try: with mincTools(verbose=2) as m: xfm = None if lin_xfm is not None and nl_xfm is not None: xfm = m.tmp('concat.xfm') m.xfmconcat([lin_xfm, nl_xfm], xfm) elif lin_xfm is not None: xfm = lin_xfm else: xfm = nl_xfm m.resample_smooth(output_grading, output_map, transform=xfm, like=template, order=2, datatype='short') except mincError as e: print("Exception in split_labels:{}".format(str(e))) traceback.print_exc(file=sys.stdout) raise except: print("Exception in split_labels:{}".format(sys.exc_info()[0])) traceback.print_exc(file=sys.stdout) raise
def extract_brain_beast(scan, parameters={}, model=None): """extract brain using BEaST """ with mincTools() as m: # TODO: come up with better default? beast_lib = parameters.get('beastlib', '/opt/minc/share/beast-library-1.1') beast_res = parameters.get('resolution', 2) beast_mask = beast_lib + os.sep + 'union_mask.mnc' if m.checkfiles(inputs=[scan.scan], outputs=[scan.mask]): tmp_in = m.tmp('like_beast.mnc') m.resample_smooth(scan.scan, tmp_in, like=beast_mask) # run additional intensity normalizaton if parameters.get('normalize', True) and model is not None: m.volume_pol(tmp_in, model.scan, m.tmp('like_beast_norm.mnc')) tmp_in = m.tmp('like_beast_norm.mnc') # run beast beast_v10_template = beast_lib + os.sep \ + 'intersection_mask.mnc' beast_v10_margin = beast_lib + os.sep + 'margin_mask.mnc' beast_v10_intersect = beast_lib + os.sep \ + 'intersection_mask.mnc' # perform segmentation m.run_mincbeast(tmp_in, m.tmp('beast_mask.mnc'), beast_lib=beast_lib, beast_res=beast_res) m.resample_labels(m.tmp('beast_mask.mnc'), scan.mask, like=scan.scan)
def nl_registration(scan, model, out_xfm, init_xfm=None, parameters={}): """Perform non-linear registration """ nl_mode = parameters.get('type', 'ants') options = parameters.get('options', None) downsample = parameters.get('downsample', None) level = parameters.get('level', 2) start = parameters.get('start_level', 32) with mincTools() as m: if not m.checkfiles(inputs=[scan.scan, model.scan], outputs=[out_xfm.xfm]): return _init_xfm = None if init_xfm is not None: _init_xfm = init_xfm.xfm if nl_mode == 'ants': ipl.ants_registration.non_linear_register_ants2( scan.scan, model.scan, out_xfm.xfm, source_mask=scan.mask, target_mask=model.mask, init_xfm=_init_xfm, parameters=options, downsample=downsample, level=level, start=start, ) elif nl_mode == 'elx': ipl.elastix_registration.register_elastix(scan.scan, model.scan, output_xfm=out_xfm.xfm, source_mask=scan.mask, target_mask=model.mask, init_xfm=_init_xfm, downsample=downsample, parameters=options, nl=True) else: objective = '-xcorr' if options is not None: objective = options.get('objective') ipl.registration.non_linear_register_full( scan.scan, model.scan, out_xfm.xfm, source_mask=scan.mask, target_mask=model.mask, init_xfm=_init_xfm, downsample=downsample, parameters=options, level=level, start=start, )
def pipeline_stx2_skullstripping(patient, tp): # creation of a structure to pass data to the function class params: pass params.pipeline_version = patient.pipeline_version params.cmdfile = patient.cmdfile params.logfile = patient.logfile params.qc_title = patient[tp].qc_title params.novolpol = True params.final = patient.beastresolution # timepoint files # params.t2=patient[tp].clp["t2"] # params.pd=patient[tp].clp["pd"] params.clpt1 = patient[tp].clp['t1'] params.stxt1 = patient[tp].stx2_mnc['t1'] params.xfmt1 = patient[tp].stx2_xfm['t1'] params.ns_stxt1 = None # patient[tp].stx_ns_mnc["t1"] params.ns_xfmt1 = None # patient[tp].stx_ns_xfm["t1"] params.beastdir = patient.beastdir # output files # ############## clpdir = patient[tp].tpdir + 'clp/' mkdir(clpdir) stx2dir = patient[tp].tpdir + 'stx2/' mkdir(stx2dir) params.stx_mask = patient[tp].stx2_mnc['mask'] params.ns_stx_mask = None # stx2dir+'nsstx_'+patient.id+"_"+tp+"_mask.mnc" params.clp_mask = patient[tp].clp2['mask'] params.qc_stx_mask = patient[tp].qc_jpg['stx2_mask'] if not os.path.exists(params.stx_mask) \ or not os.path.exists(params.qc_stx_mask): runSkullstripping(params) else: print ' -- pipeline_stx2_skullstripping is done' if 't2les' in patient[tp].native: if not os.path.exists(patient[tp].stx2_mnc['masknoles']): # dilate lesions with mincTools() as minc: minc.binary_morphology(patient[tp].stx2_mnc['t2les'], 'D[1]', minc.tmp('dilated.mnc')) # . Remove lesions from mask minc.calc( [patient[tp].stx2_mnc['mask'], minc.tmp('dilated.mnc')], 'if(A[0]>0.5 && A[1]<0.5){1}else{0}', patient[tp].stx2_mnc['masknoles'], labels=True)
def lngtemplate_v11(patient): with mincTools() as minc: biascorr = False atlas = patient.modeldir + os.sep + patient.modelname + '.mnc' atlas_mask = patient.modeldir + os.sep + patient.modelname \ + '_mask.mnc' options={'symmetric':False, 'protocol':[{'iter':1,'level':16}, {'iter':2,'level':8}, {'iter':2,'level':4}, {'iter':2,'level':2}], 'cleanup':True, 'biascorr':biascorr } if patient.fast: # apply fast mode options['protocol']=[{'iter':1,'level':16},{'iter':2,'level':8}] samples= [ [tp.stx2_mnc['t1'], tp.stx2_mnc['masknoles']] for (i, tp) in patient.items()] model = atlas model_mask = atlas_mask work_prefix = patient.workdir+os.sep+'nl' output=generate_nonlinear_model(samples,model=atlas,mask=atlas_mask,work_prefix=work_prefix,options=options) # copy output ... shutil.copyfile(output['model'].scan, patient.template['nl_template']) shutil.copyfile(output['model'].mask, patient.template['nl_template_mask']) shutil.copyfile(output['model_sd'].scan,patient.template['nl_template_sd']) #TODO: #options.output_regu_0 = patient.template['regu_0'] #options.output_regu_1 = patient.template['regu_1'] minc.qc( patient.template['nl_template'], patient.qc_jpg['nl_template'], title=patient.id, image_range=[0, 120], big=True, clamp=True, ) # copy each timepoint images too k=0 for (i, tp) in patient.items(): xfmfile = output['xfm' ][k].xfm corrected_t1 = output['scan'][k].scan # creating lng images shutil.copyfile(corrected_t1, tp.lng_mnc['t1']) # NOT really needed? minc.xfm_normalize(xfmfile,atlas_mask,tp.lng_xfm['t1'], step=1.0) minc.xfm_normalize(xfmfile,atlas_mask,tp.lng_ixfm['t1'],step=1.0,invert=True) k+=1 # cleanup temporary files shutil.rmtree(work_prefix)
def apply_linear_model(lin_model, parameters, output_volume): """build a volume, for a given regression model and parameters""" try: with mincTools() as m: if lin_model.N != len(parameters): raise mincError("Expected: {} parameters, got {}".format( lin_model.N, len(parameters))) # create minccalc expression _exp = [] for i in range(0, lin_model.N): _exp.append('A[{}]*{}'.format(i, parameters[i])) exp = '+'.join(_exp) m.calc(lin_model.volume, exp, output_volume) return True except mincError as e: print("Exception in apply_linear_model:{}".format(str(e))) traceback.print_exc(file=sys.stdout) raise except: print("Exception in apply_linear_model:{}".format(sys.exc_info()[0])) traceback.print_exc(file=sys.stdout) raise
def warp_mask(sample, reference, output_scan, transform=None, parameters={}, corr_xfm=None): with mincTools() as m: xfm = None xfms = [] if corr_xfm is not None: xfms.append(corr_xfm.xfm) if transform is not None: xfms.append(transform.xfm) if len(xfms) == 0: pass if len(xfms) == 1: xfm = transform.xfm else: m.xfmconcat(xfms, m.tmp('concatenated.xfm')) xfm = m.tmp('concatenated.xfm') resample_order = parameters.get('resample_order', 4) m.resample_labels(sample.mask, output_scan.mask, transform=xfm, like=reference.scan, order=resample_order)
def atlasregistration_v10(patient): nl_level = 2 if patient.fast: # fast mode nl_level = 4 with mincTools() as minc: model_t1 = patient.modeldir + os.sep + patient.modelname + '.mnc' model_mask = patient.modeldir + os.sep + patient.modelname + '_mask.mnc' ipl.registration.non_linear_register_full( patient.template['nl_template'], model_t1, patient.nl_xfm, source_mask=patient.template['nl_template_mask'], target_mask=model_mask, level=nl_level, ) # make QC image, similar to linear ones if not os.path.exists(patient.qc_jpg['nl_template_nl']): atlas_outline = patient.modeldir + os.sep + patient.modelname + '_outline.mnc' minc.resample_smooth(patient.template['nl_template'],minc.tmp('nl_atlas.mnc'),transform=patient.nl_xfm) minc.qc( minc.tmp('nl_atlas.mnc'), patient.qc_jpg['nl_template_nl'], title=patient.id, image_range=[0, 120], big=True, clamp=True, mask=atlas_outline )
def seg_to_volumes_grad(seg, output_json, label_map=None, grad=None, median=False): with mincTools(verbose=2) as m: _out = m.label_stats(seg, label_defs=label_map, volume=grad, median=median) # convert to a dictionary # label_id, volume, mx, my, mz,[mean/median] out = { i[0]: { 'volume': i[1], 'x': i[2], 'y': i[3], 'z': i[4], 'grad': i[5] } for i in _out } with open(output_json, 'w') as f: json.dump(out, f, indent=1) return out
def estimate_gco_energy(samples, output, classes=2): with mincTools() as m: files = [f.seg for f in samples] cmd = ['label_interaction_estimate'] cmd.extend(files) cmd.append(output) cmd.extend(['--classes', str(classes)]) m.command(cmd, inputs=files, outputs=[output])
def concat_v10(patient, tp): with mincTools() as minc: tmp_xfm = minc.tmp('tmp_concat.xfm') minc.xfmconcat([patient[tp].lng_xfm['t1'], patient.nl_xfm] , tmp_xfm) examplegrid = patient.nl_xfm[:-4] + '_grid_0.mnc' minc.xfm_normalize(tmp_xfm, examplegrid, patient[tp].nl_xfm, exact=True)
def classify_prior(inputs, output, mask=None, model_dir=None, model_name=None, xfm=None, priors=None, mrf=False): with mincTools() as minc: tags = "{modeldir}/{modelname}_ntags_1000_prob_90_nobg.tag".format( modeldir=model_dir, modelname=model_name) nltags = minc.tmp("nltags.tag") if xfm is not None: argsreg = ['transform_tags', tags, xfm, nltags, 'invert'] minc.command(argsreg) else: nltags = tags cleantags = minc.tmp("clean.tag") argsclean = [ 'cleantag', '-clobber', '-oldtag', nltags, '-newtag', cleantags, '-mode', '101', '-threshold', '0.9', '-difference', '0.5', priors[0], '1', priors[1], '2', priors[2], '3', '-comment', 'clean_apriori' ] minc.command(argsclean) # 3. Bayesian classificationregis ################ tmpcls = minc.tmp("cls.mnc") # NOTE: classify have to have fixed to correctly work with priors argsclass = [ 'classify', '-clobber', '-nocache', '-bayes', '-apriori', '-volume', "{},{},{}".format(priors[0], priors[1], priors[2]), '-tagfile', cleantags ] argsclass.extend(inputs) argsclass.append(tmpcls) if mask is not None: argsclass.extend(['-mask', mask, '-user_mask_value', '0.5']) minc.command(argsclass) ## Adding MRF ################### if mrf: #TODO run PVE! #if len(inputs)>1: # do_cmd('pve3','-image',tmpcls,'-mask',mask,@ARGV,"$tmpdir/pve") #else: # do_cmd('pve','-image',tmpcls,'-mask',mask,@ARGV,"$tmpdir/pve") #do_cmd('minccalc','-express','(A[0]>A[1]?(A[0]>A[2]?1:3):(A[1]>A[2]?2:3))*A[3]','-byte',"$tmpdir/pve_csf.mnc","$tmpdir/pve_gm.mnc","$tmpdir/pve_wm.mnc",$mask_file,$outfile_clean,'-clobber'); pass else: shutil.copyfile(tmpcls, output)
def calc_similarity_stats( input_ground_truth, input_segmentation, output_stats=None, relabel=None, use_labels=None): ''' Calculate similarity stats ''' stats={} stats[ 'sample' ] = input_segmentation stats[ 'ground_truth' ] = input_ground_truth cmd=['volume_gtc_similarity', input_ground_truth, input_segmentation,'--csv'] if use_labels: cmd.extend(['--include', ','.join([str(i) for i in use_labels])]) with mincTools() as m: sim = m.execute_w_output( cmd ).rstrip("\n").split(',') stats['gkappa'] = float(sim[0]) stats['gtc'] = float(sim[1]) stats['akappa'] = float(sim[2]) sim = m.execute_w_output( [ 'volume_similarity', input_ground_truth, input_segmentation,'--csv'] ).split("\n") ka={} se={} sp={} js={} for i in sim: q=i.split(',') if len(q)==5: l=int(q[0]) if relabel is not None: l=relabel[str(l)] ka[l] = float( q[1] ) se[l] = float( q[2] ) sp[l] = float( q[3] ) js[l] = float( q[4] ) stats['ka']=ka stats['se']=se stats['sp']=sp stats['js']=js if output_stats is not None: with open(output_stats,'w') as f: f.write("{},{},{},{}\n".format(stats['sample'],stats['gkappa'],stats['gtc'],stats['akappa'])) return stats
def join_left_right(sample, output_seg, output_grad=None, datatype=None): with mincTools() as m: cmd = ['itk_merge_discrete_labels', sample.seg, sample.seg_f, output] if datatype is not None: cmd.append('--' + datatype) m.command(cmd, inputs=[sample.seg, sample.seg_f], outputs=[output]) if output_grad is not None: # TODO:figure out how to merge gradings print("Can't merge gradings yet!")
def lobe_segmentation_v10(patient, tp): # # doing the processing # ###################### with mincTools() as minc: identity = minc.tmp('identity.xfm') if not os.path.exists(patient[tp].stx2_mnc['lobes']): comm = ['param2xfm', identity] minc.command(comm, [], [identity]) cls = '' # Do lobe segment if patient.dolngcls and len(list(patient.keys())) > 1: cls = patient[tp].stx2_mnc['lng_classification'] else: cls = patient[tp].stx2_mnc['classification'] comm = [ 'lobe_segment', patient[tp].nl_xfm, identity, cls, patient[tp].stx2_mnc['lobes'], '-modeldir', patient.modeldir + os.sep + patient.modelname + '_atlas/', '-template', patient.modeldir + os.sep + patient.modelname + '.mnc', ] minc.command(comm, [patient[tp].nl_xfm, cls], [patient[tp].stx2_mnc['lobes']]) # Compute volumes # Classify brain into 3 classes # TODO: replace with direct call to lobes_to_volumes.pl comm = [ 'pipeline_volumes_nl.pl', patient[tp].stx2_mnc['masknoles'], cls, patient[tp].stx2_mnc['lobes'], patient[tp].stx2_xfm['t1'], patient[tp].vol['lobes'], '--age', str(patient[tp].age), '--t1', patient[tp].native['t1'] ] if len(patient.sex) > 0: comm.extend(['--gender', patient.sex]) if 't2' in patient[tp].native: comm.extend(['--t2', patient[tp].native['t2']]) if 'pd' in patient[tp].native: comm.extend(['--pd', patient[tp].native['pd']]) minc.command(comm, [ patient[tp].stx2_mnc['masknoles'], patient[tp].stx2_mnc['classification'], patient[tp].stx2_mnc['lobes'], patient[tp].stx2_xfm['t1'] ], [patient[tp].vol['lobes']]) return 0
def generate_flip_sample(input): '''generate flipped version of sample''' with mincTools() as m: m.flip_volume_x(input.scan, input.scan_f) if input.mask is not None: m.flip_volume_x(input.mask, input.mask_f, labels=True) return True
def resample_and_correct_bias( sample, transform, avg_bias, output, previous=None, symmetric=False, ): # resample bias field and apply previous estimate try: with mincTools() as m: m.calc([sample.scan, avg_bias.scan], 'A[1]>0.1?A[0]/A[1]:1.0', m.tmp('corr_bias.mnc')) m.resample_smooth(m.tmp('corr_bias.mnc'), m.tmp('corr_bias2.mnc'), like=sample.scan, transform=transform.xfm, invert_transform=True) if previous: m.calc([previous.scan, m.tmp('corr_bias2.mnc')], 'A[0]*A[1]', output.scan, datatype='-float') else: shutil.copy(m.tmp('corr_bias2.mnc'), output.scan) if symmetric: m.calc([sample.scan_f, avg_bias.scan], 'A[1]>0.1?A[0]/A[1]:1.0', m.tmp('corr_bias_f.mnc')) m.resample_smooth(m.tmp('corr_bias_f.mnc'), m.tmp('corr_bias2_f.mnc'), like=sample.scan, transform=transform.xfm, invert_transform=True) if previous: m.calc([previous.scan_f, m.tmp('corr_bias2_f.mnc')], 'A[0]*A[1]', output.scan_f, datatype='-float') else: shutil.copy(m.tmp('corr_bias2_f.mnc'), output.scan) return True except mincError as e: print "Exception in resample_and_correct_bias:{}".format(str(e)) traceback.print_exc(file=sys.stdout) raise except: print "Exception in resample_and_correct_bias:{}".format( sys.exc_info()[0]) traceback.print_exc(file=sys.stdout) raise
def xfm_remove_scale(in_xfm, out_xfm, unscale=None): """remove scaling factors from linear XFM """ _unscale = None if unscale is not None: _unscale = unscale.xfm with mincTools() as minc: minc.xfm_noscale(in_xfm.xfm, out_xfm.xfm, unscale=_unscale)
def xfmavg(inputs, output, verbose=False): # TODO: handle inversion flag correctly all_linear=True all_nonlinear=True input_xfms=[] input_grids=[] for j in inputs: x=minc2_xfm(j) if x.get_n_concat()==1 and x.get_n_type(0)==minc2_xfm.MINC2_XFM_LINEAR: # this is a linear matrix input_xfms.append(np.asmatrix(x.get_linear_transform())) else: all_linear&=False # strip identity matrixes nl=[] _identity=np.asmatrix(np.identity(4)) _eps=1e-6 if x.get_n_type(0)==minc2_xfm.MINC2_XFM_LINEAR and x.get_n_type(1)==minc2_xfm.MINC2_XFM_GRID_TRANSFORM: if scipy.linalg.norm(_identity-np.asmatrix(x.get_linear_transform(0)) )>_eps: # this is non-identity matrix all_nonlinear&=False else: # TODO: if grid have to be inverted! (grid_file,grid_invert)=x.get_grid_transform(1) input_grids.append(grid_file) elif x.get_n_type(1)==minc2_xfm.MINC2_XFM_GRID_TRANSFORM: # TODO: if grid have to be inverted! (grid_file,grid_invert)=x.get_grid_transform(0) input_grids.append(grid_file) if all_linear: acc=np.asmatrix(np.zeros([4,4],dtype=np.complex)) for i in input_xfms: print(i) acc+=scipy.linalg.logm(i) acc/=len(input_xfms) acc=np.asarray(scipy.linalg.expm(acc).real,'float64','C') x=minc2_xfm() x.append_linear_transform(acc) x.save(output) elif all_nonlinear: output_grid=output.rsplit('.xfm',1)[0]+'_grid_0.mnc' with mincTools(verbose=2) as m: m.average(input_grids,output_grid) x=minc2_xfm() x.append_grid_transform(output_grid, False) x.save(output) else: raise Exception("Mixed XFM files provided as input")
def calculate_similarity(sample1, sample2, mask=None, method='MI', flip=False, step=None): try: with mincTools() as m: scan = sample1.scan if flip: scan = sample1.scan_f # figure out step size, minctracc works extremely slow when step size is smaller then file step size info_sample1 = m.mincinfo(sample1.scan) cmds = ['minctracc', scan, sample2.scan, '-identity'] if method == 'MI': cmds.extend(['-nmi', '-blur_pdf', '9']) else: cmds.append('-xcorr') if step is None: step = max(abs(info_sample1['xspace'].step), abs(info_sample1['yspace'].step), abs(info_sample1['zspace'].step)) cmds.extend([ '-step', str(step), str(step), str(step), '-simplex', '1', '-tol', '0.01', '-lsq6', '-est_center', '-clob', m.tmp('similarity.xfm') ]) if mask is not None: cmds.extend(['-source_mask', mask]) output = re.search('^Final objective function value = (\S+)', m.execute_w_output(cmds, verbose=0), flags=re.MULTILINE).group(1) return float(output) except mincError as e: print("Exception in calculate_similarity:{}".format(str(e))) traceback.print_exc(file=sys.stdout) raise except: print("Exception in calculate_similarity:{}".format(sys.exc_info()[0])) traceback.print_exc(file=sys.stdout) raise
def seg_to_volumes(seg, output_json, label_map=None,volume=None): with mincTools( verbose=2 ) as m: _out=m.label_stats(seg,label_defs=label_map,volume=volume) if volume: out={i[0]: { 'volume':i[1], 'x':i[2], 'y':i[3], 'z': i[4], 'mean_v':i[5], 'integral_v':i[5]*i[1] } for i in _out } else: out={i[0]: { 'volume':i[1], 'x':i[2], 'y':i[3], 'z': i[4] } for i in _out } with open(output_json,'w') as f: json.dump(out,f,indent=1) return out
def extract_brain_nlreg(scan, parameters={}, model=None): """extract brain using non-linear registration to the template""" with mincTools() as m: if m.checkfiles(inputs=[scan.scan], outputs=[scan.mask]): tmp_xfm = MriTransform(prefix=m.tempdir, name='nl_' + scan.name) nl_registration(scan, model, tmp_xfm, parameters=parameters) # warp template atlas to subject's scan m.resample_labels(model.mask, scan.mask, transform=tmp_xfm.xfm, invert_transform=True)
def fix_spacing(scan): """make sure all spacing in 3D volume are regular Arguments: `scan` scan to be fixed """ with mincTools() as minc: for s in ['xspace', 'yspace', 'zspace']: spacing = minc.query_attribute(scan, s + ':spacing') if spacing.count('irregular'): minc.set_attribute(scan, s + ':spacing', 'regular__') return scan
def apply_nu(in_scan, field, out_scan, parameters={}): """ Apply non-uniformity correction """ with mincTools() as minc: if not minc.checkfiles(inputs=[field.scan], outputs=[out_scan.scan]): return minc.resample_smooth(field.scan, minc.tmp('fld.mnc'), like=in_scan.scan, order=1) minc.calc([in_scan.scan, minc.tmp('fld.mnc')], 'A[0]/A[1]', out_scan.scan)