bool VolumeFilterErode::Execute() { ::SetProgressCallback(ProgressCallback, 0, 50); MRI* mri_src = CreateMRIFromVolume( m_volumeInput ); if ( !mri_src ) { return false; } ::SetProgressCallback(ProgressCallback, 50, 60); MRI* mri_dest = MRIerode( mri_src, NULL ); if ( !mri_dest ) { return false; } ::SetProgressCallback(ProgressCallback, 60, 100); MapMRIToVolume( mri_dest, m_volumeOutput ); MRIfree( &mri_src ); MRIfree( &mri_dest ); return true; }
int main(int argc, char *argv[]) { char **av, *in_fname, *out_fname ; int ac, nargs, i, label ; MRI *mri_in, *mri_out, *mri_kernel, *mri_smoothed ; /* rkt: check for and handle version tag */ nargs = handle_version_option (argc, argv, "$Id: mri_extract_label.c,v 1.13 2011/03/02 00:04:15 nicks Exp $", "$Name: $"); if (nargs && argc - nargs == 1) exit (0); argc -= nargs; Progname = argv[0] ; ErrorInit(NULL, NULL, NULL) ; DiagInit(NULL, NULL, NULL) ; ac = argc ; av = argv ; for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) { nargs = get_option(argc, argv) ; argc -= nargs ; argv += nargs ; } if (argc < 4) usage_exit() ; in_fname = argv[1] ; out_fname = argv[argc-1] ; printf("reading volume from %s...\n", in_fname) ; mri_in = MRIread(in_fname) ; if (!mri_in) ErrorExit(ERROR_NOFILE, "%s: could not read MRI volume %s", Progname, in_fname) ; if (out_like_fname) { MRI *mri_tmp = MRIread(out_like_fname) ; if (!mri_tmp) ErrorExit (ERROR_NOFILE, "%s: could not read template volume from %s", out_like_fname) ; mri_out = MRIalloc(mri_tmp->width, mri_tmp->height, mri_tmp->depth, mri_tmp->type) ; /* MRIcopyHeader(mri_tmp, mri_out) ;*/ MRIfree(&mri_tmp) ; } else mri_out = MRIclone(mri_in, NULL) ; for (i = 2 ; i < argc-1 ; i++) { label = atoi(argv[i]) ; printf("extracting label %d (%s)\n", label, cma_label_to_name(label)) ; extract_labeled_image(mri_in, transform, label, mri_out) ; } if (!FZERO(sigma)) { printf("smoothing extracted volume...\n") ; mri_kernel = MRIgaussian1d(sigma, 10*sigma) ; mri_smoothed = MRIconvolveGaussian(mri_out, NULL, mri_kernel) ; MRIfree(&mri_out) ; mri_out = mri_smoothed ; } /* removed for gcc3.3 * vsprintf(out_fname, out_fname, (va_list) &label) ; */ if (dilate > 0) { int i ; printf("dilating output volume %d times...\n", dilate) ; for (i = 0 ; i < dilate ; i++) MRIdilate(mri_out, mri_out) ; } if (erode > 0) { int i ; printf("eroding output volume %d times...\n", erode) ; for (i = 0 ; i < erode ; i++) MRIerode(mri_out, mri_out) ; } printf("writing output to %s.\n", out_fname) ; MRIwrite(mri_out, out_fname) ; if (exit_none_found && (nvoxels == 0)) { printf("No voxels with specified label were found!\n"); exit(1); } exit(0) ; return(0) ; /* for ansi */ }
/*---------------------------------------------------------------*/ int main(int argc, char *argv[]) { int nargs, n, Ntp, nsearch, nsearch2=0; double fwhm = 0, nresels, voxelvolume, nvoxperresel, reselvolume; double car1mn, rar1mn,sar1mn,cfwhm,rfwhm,sfwhm, ftmp; double car2mn, rar2mn,sar2mn; double gmean, gstd, gmax; FILE *fp; sprintf(tmpstr, "S%sER%sRONT%sOR", "URF", "_F", "DO") ; setenv(tmpstr,"1",0); nargs = handle_version_option (argc, argv, vcid, "$Name: $"); if (nargs && argc - nargs == 1) exit (0); argc -= nargs; cmdline = argv2cmdline(argc,argv); uname(&uts); getcwd(cwd,2000); Progname = argv[0] ; argc --; argv++; ErrorInit(NULL, NULL, NULL) ; DiagInit(NULL, NULL, NULL) ; if (argc == 0) usage_exit(); parse_commandline(argc, argv); check_options(); if (checkoptsonly) return(0); if (SynthSeed < 0) SynthSeed = PDFtodSeed(); if (debug) dump_options(stdout); // ------------- load or synthesize input --------------------- InVals = MRIreadType(inpath,InValsType); if(InVals == NULL) exit(1); if(SetTR){ printf("Setting TR to %g ms\n",TR); InVals->tr = TR; } if((nframes < 0 && synth) || !synth) nframes = InVals->nframes; if(nframes < nframesmin && !SmoothOnly && !sum2file) { printf("ERROR: nframes = %d, need at least %d\n", nframes,nframesmin); exit(1); } if (InVals->type != MRI_FLOAT) { mritmp = MRISeqchangeType(InVals, MRI_FLOAT, 0, 0, 0); MRIfree(&InVals); InVals = mritmp; } if(synth) { printf("Synthesizing %d frames, Seed = %d\n",nframes,SynthSeed); mritmp = MRIcloneBySpace(InVals,MRI_FLOAT,nframes); MRIfree(&InVals); MRIrandn(mritmp->width, mritmp->height, mritmp->depth, nframes, 0, 1, mritmp); InVals = mritmp; } voxelvolume = InVals->xsize * InVals->ysize * InVals->zsize ; printf("voxelvolume %g mm3\n",voxelvolume); if(DoSqr){ printf("Computing square of input\n"); MRIsquare(InVals,NULL,InVals); } // -------------------- handle masking ------------------------ if (maskpath) { printf("Loading mask %s\n",maskpath); mask = MRIread(maskpath); if(mask==NULL) exit(1); if(MRIdimMismatch(mask,InVals,0)){ printf("ERROR: dimension mismatch between mask and input\n"); exit(1); } MRIbinarize2(mask, mask, maskthresh, 0, 1); } if (automask) { RFglobalStats(InVals, NULL, &gmean, &gstd, &gmax); maskthresh = gmean * automaskthresh; printf("Computing mask, relative threshold = %g, gmean = %g, absthresh = %g\n", automaskthresh,gmean,maskthresh); mritmp = MRIframeMean(InVals,NULL); //MRIwrite(mritmp,"fmean.mgh"); mask = MRIbinarize2(mritmp, NULL, maskthresh, 0, 1); MRIfree(&mritmp); } if (mask) { if (maskinv) { printf("Inverting mask\n"); MRImaskInvert(mask,mask); } nsearch = MRInMask(mask); if (nsearch == 0) { printf("ERROR: no voxels found in mask\n"); exit(1); } // Erode the mask ----------------------------------------------- if (nerode > 0) { printf("Eroding mask %d times\n",nerode); for (n=0; n<nerode; n++) MRIerode(mask,mask); nsearch2 = MRInMask(mask); if (nsearch2 == 0) { printf("ERROR: no voxels found in mask after eroding\n"); exit(1); } printf("%d voxels in mask after eroding\n",nsearch2); } //---- Save mask ----- if (outmaskpath) MRIwrite(mask,outmaskpath); } else nsearch = InVals->width * InVals->height * InVals->depth; printf("Search region is %d voxels = %lf mm3\n",nsearch,nsearch*voxelvolume); if( (infwhm > 0 || infwhmc > 0 || infwhmr > 0 || infwhms > 0) && SmoothOnly) { if(SaveUnmasked) mritmp = NULL; else mritmp = mask; if(infwhm > 0) { printf("Smoothing input by fwhm=%lf, gstd=%lf\n",infwhm,ingstd); MRImaskedGaussianSmooth(InVals, mritmp, ingstd, InVals); } if(infwhmc > 0 || infwhmr > 0 || infwhms > 0) { printf("Smoothing input by fwhm=(%lf,%lf,%lf) gstd=(%lf,%lf,%lf)\n", infwhmc,infwhmr,infwhms,ingstdc,ingstdr,ingstds); MRIgaussianSmoothNI(InVals, ingstdc, ingstdr, ingstds, InVals); } printf("Saving to %s\n",outpath); MRIwrite(InVals,outpath); printf("SmoothOnly requested, so exiting now\n"); exit(0); } // Make a copy, if needed, prior to doing anything to data if(outpath) InValsCopy = MRIcopy(InVals,NULL); // Compute variance reduction factor ------------------- if(sum2file){ ftmp = MRIsum2All(InVals); fp = fopen(sum2file,"w"); if(fp == NULL){ printf("ERROR: opening %s\n",sum2file); exit(1); } printf("sum2all: %20.10lf\n",ftmp); printf("vrf: %20.10lf\n",1/ftmp); fprintf(fp,"%20.10lf\n",ftmp); exit(0); } //------------------------ Detrend ------------------ if(DetrendOrder >= 0) { Ntp = InVals->nframes; printf("Polynomial detrending, order = %d\n",DetrendOrder); X = MatrixAlloc(Ntp,DetrendOrder+1,MATRIX_REAL); for (n=0;n<Ntp;n++) X->rptr[n+1][1] = 1.0; ftmp = Ntp/2.0; if (DetrendOrder >= 1) for (n=0;n<Ntp;n++) X->rptr[n+1][2] = (n-ftmp)/ftmp; if (DetrendOrder >= 2) for (n=0;n<Ntp;n++) X->rptr[n+1][3] = pow((n-ftmp),2.0)/(ftmp*ftmp); } if(X){ printf("Detrending\n"); if (X->rows != InVals->nframes) { printf("ERROR: dimension mismatch between X and input\n"); exit(1); } mritmp = fMRIdetrend(InVals,X); if (mritmp == NULL) exit(1); MRIfree(&InVals); InVals = mritmp; } // ------------ Smooth Input BY infwhm ------------------------- if(infwhm > 0) { printf("Smoothing input by fwhm=%lf, gstd=%lf\n",infwhm,ingstd); MRImaskedGaussianSmooth(InVals, mask, ingstd, InVals); } // ------------ Smooth Input BY infwhm ------------------------- if(infwhmc > 0 || infwhmr > 0 || infwhms > 0) { printf("Smoothing input by fwhm=(%lf,%lf,%lf) gstd=(%lf,%lf,%lf)\n", infwhmc,infwhmr,infwhms,ingstdc,ingstdr,ingstds); MRIgaussianSmoothNI(InVals, ingstdc, ingstdr, ingstds, InVals); } // ------------ Smooth Input TO fwhm ------------------------- if (tofwhm > 0) { printf("Attempting to smooth to %g +/- %g mm fwhm (nitersmax=%d)\n", tofwhm,tofwhmtol,tofwhmnitersmax); mritmp = MRImaskedGaussianSmoothTo(InVals, mask, tofwhm, tofwhmtol, tofwhmnitersmax, &byfwhm, &tofwhmact, &tofwhmniters, InVals); if (mritmp == NULL) exit(1); printf("Smoothed by %g to %g in %d iterations\n", byfwhm,tofwhmact,tofwhmniters); if (tofwhmfile) { fp = fopen(tofwhmfile,"w"); if (!fp) { printf("ERROR: opening %s\n",tofwhmfile); exit(1); } fprintf(fp,"tofwhm %lf\n",tofwhm); fprintf(fp,"tofwhmtol %lf\n",tofwhmtol); fprintf(fp,"tofwhmact %lf\n",tofwhmact); fprintf(fp,"byfwhm %lf\n",byfwhm); fprintf(fp,"niters %d\n",tofwhmniters); fprintf(fp,"nitersmax %d\n",tofwhmnitersmax); fclose(fp); } } // ------ Save smoothed/detrended ------------------------------ if(outpath) { // This is a bit of a hack in order to be able to save undetrended // Operates on InValsCopy, which has not been modified (requires // smoothing twice, which is silly:). printf("Saving to %s\n",outpath); // Smoothed output will not be masked if (SaveDetrended && X) { mritmp = fMRIdetrend(InValsCopy,X); if (mritmp == NULL) exit(1); MRIfree(&InValsCopy); InValsCopy = mritmp; } if (SaveUnmasked) mritmp = NULL; else mritmp = mask; if(infwhm > 0) MRImaskedGaussianSmooth(InValsCopy, mritmp, ingstd, InValsCopy); if(infwhmc > 0 || infwhmr > 0 || infwhms > 0) MRIgaussianSmoothNI(InValsCopy, ingstdc, ingstdr, ingstds, InValsCopy); if(tofwhm > 0) { bygstd = byfwhm/sqrt(log(256.0)); MRImaskedGaussianSmooth(InValsCopy, mritmp, bygstd, InValsCopy); } MRIwrite(InValsCopy,outpath); MRIfree(&InValsCopy); } // ----------- Compute smoothness ----------------------------- printf("Computing spatial AR1 in volume.\n"); ar1 = fMRIspatialAR1(InVals, mask, NULL); if (ar1 == NULL) exit(1); fMRIspatialAR1Mean(ar1, mask, &car1mn, &rar1mn, &sar1mn); cfwhm = RFar1ToFWHM(car1mn, InVals->xsize); rfwhm = RFar1ToFWHM(rar1mn, InVals->ysize); sfwhm = RFar1ToFWHM(sar1mn, InVals->zsize); fwhm = sqrt((cfwhm*cfwhm + rfwhm*rfwhm + sfwhm*sfwhm)/3.0); printf("ar1mn = (%lf,%lf,%lf)\n",car1mn,rar1mn,sar1mn); printf("colfwhm = %lf\n",cfwhm); printf("rowfwhm = %lf\n",rfwhm); printf("slicefwhm = %lf\n",sfwhm); printf("outfwhm = %lf\n",fwhm); reselvolume = cfwhm*rfwhm*sfwhm; nvoxperresel = reselvolume/voxelvolume; nresels = voxelvolume*nsearch/reselvolume; printf("reselvolume %lf\n",reselvolume); printf("nresels %lf\n",nresels); printf("nvoxperresel %lf\n",nvoxperresel); if(DoAR2){ printf("Computing spatial AR2 in volume.\n"); fMRIspatialAR2Mean(InVals, mask, &car2mn, &rar2mn, &sar2mn); printf("ar2mn = (%lf,%lf,%lf)\n",car2mn,rar2mn,sar2mn); } if(ar1path) MRIwrite(ar1,ar1path); fflush(stdout); // ---------- Save summary file --------------------- if(sumfile) { fp = fopen(sumfile,"w"); if (fp == NULL) { printf("ERROR: opening %s\n",sumfile); exit(1); } dump_options(fp); fprintf(fp,"nsearch2 %d\n",nsearch2); fprintf(fp,"searchspace_vox %d\n",nsearch); fprintf(fp,"searchspace_mm3 %lf\n",nsearch*voxelvolume); fprintf(fp,"voxelvolume_mm3 %g\n",voxelvolume); fprintf(fp,"voxelsize_mm %g %g %g\n",InVals->xsize,InVals->ysize,InVals->zsize); fprintf(fp,"ar1mn %lf %lf %lf\n",car1mn,rar1mn,sar1mn); fprintf(fp,"colfwhm_mm %lf\n",cfwhm); fprintf(fp,"rowfwhm_mm %lf\n",rfwhm); fprintf(fp,"slicefwhm_mm %lf\n",sfwhm); fprintf(fp,"outfwhm_mm %lf\n",fwhm); fprintf(fp,"reselvolume_mm3 %lf\n",reselvolume); fprintf(fp,"nresels %lf\n",nresels); fprintf(fp,"nvox_per_resel %lf\n",nvoxperresel); fclose(fp); } if(datfile) { fp = fopen(datfile,"w"); if(fp == NULL) { printf("ERROR: opening %s\n",datfile); exit(1); } fprintf(fp,"%lf\n",fwhm); fclose(fp); } printf("mri_fwhm done\n"); return 0; }
static MRI * MRIcomputeSurfaceDistanceProbabilities(MRI_SURFACE *mris, MRI *mri_ribbon, MRI *mri, MRI *mri_aseg) { MRI *mri_features, *mri_binary, *mri_white_dist, *mri_pial_dist, *mri_mask ; int nwhite_bins, npial_bins, x, y, z, label, i ; HISTOGRAM2D *hw, *hp ; float pdist, wdist, val ; double wval, pval ; mri_features = MRIallocSequence(mri->width, mri->height, mri->depth, MRI_FLOAT, 2) ; MRIcopyHeader(mri, mri_features) ; mri_binary = MRIcopy(mri_ribbon, NULL) ; mri_binary = MRIbinarize(mri_ribbon, NULL, 1, 0, 1) ; mri_pial_dist = MRIdistanceTransform(mri_binary, NULL, 1, max_pial_dist+1, DTRANS_MODE_SIGNED,NULL); if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON) MRIwrite(mri_pial_dist, "pd.mgz") ; MRIclear(mri_binary) ; MRIcopyLabel(mri_ribbon, mri_binary, Left_Cerebral_White_Matter) ; MRIcopyLabel(mri_ribbon, mri_binary, Right_Cerebral_White_Matter) ; MRIbinarize(mri_binary, mri_binary, 1, 0, 1) ; mri_white_dist = MRIdistanceTransform(mri_binary, NULL, 1, max_white_dist+1, DTRANS_MODE_SIGNED,NULL); if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON) MRIwrite(mri_white_dist, "wd.mgz") ; nwhite_bins = ceil((max_white_dist - min_white_dist) / white_bin_size)+1 ; npial_bins = ceil((max_pial_dist - min_pial_dist) / pial_bin_size)+1 ; hw = HISTO2Dalloc(NBINS, nwhite_bins) ; hp = HISTO2Dalloc(NBINS, npial_bins) ; HISTO2Dinit(hw, NBINS, nwhite_bins, 0, NBINS-1, min_white_dist, max_white_dist) ; HISTO2Dinit(hp, NBINS, npial_bins, 0, NBINS-1, min_pial_dist, max_pial_dist) ; for (x = 0 ; x < mri->width ; x++) for (y = 0 ; y < mri->height ; y++) for (z = 0 ; z < mri->depth ; z++) { label = MRIgetVoxVal(mri_aseg, x, y, z, 0) ; if (IS_CEREBELLUM(label) || IS_VENTRICLE(label) || label == Brain_Stem || IS_CC(label)) continue ; pdist = MRIgetVoxVal(mri_pial_dist, x, y, z, 0) ; wdist = MRIgetVoxVal(mri_pial_dist, x, y, z, 0) ; val = MRIgetVoxVal(mri, x, y, z, 0) ; if (pdist >= min_pial_dist && pdist <= max_pial_dist) HISTO2DaddSample(hp, val, pdist, 0, 0, 0, 0) ; if (wdist >= min_white_dist && wdist <= max_white_dist) HISTO2DaddSample(hw, val, wdist, 0, 0, 0, 0) ; } HISTO2DmakePDF(hp, hp) ; HISTO2DmakePDF(hw, hw) ; for (x = 0 ; x < mri->width ; x++) for (y = 0 ; y < mri->height ; y++) for (z = 0 ; z < mri->depth ; z++) { label = MRIgetVoxVal(mri_aseg, x, y, z, 0) ; if (IS_CEREBELLUM(label) || IS_VENTRICLE(label) || label == Brain_Stem || IS_CC(label)) continue ; pdist = MRIgetVoxVal(mri_pial_dist, x, y, z, 0) ; wdist = MRIgetVoxVal(mri_pial_dist, x, y, z, 0) ; val = MRIgetVoxVal(mri, x, y, z, 0) ; wval = HISTO2DgetCount(hw, val, wdist); if (DZERO(wval) == 0) MRIsetVoxVal(mri_features, x, y, z, 1, -log10(wval)) ; pval = HISTO2DgetCount(hp, val, pdist); if (DZERO(pval) == 0) MRIsetVoxVal(mri_features, x, y, z, 0, -log10(pval)) ; } MRIclear(mri_binary) ; MRIbinarize(mri_ribbon, mri_binary, 1, 0, 1) ; mri_mask = MRIcopy(mri_binary, NULL) ; for (i = 0 ; i < close_order ; i++) { MRIdilate(mri_binary, mri_mask) ; MRIcopy(mri_mask, mri_binary) ; } for (i = 0 ; i < close_order ; i++) { MRIerode(mri_binary, mri_mask) ; MRIcopy(mri_mask, mri_binary) ; } MRIwrite(mri_mask, "m.mgz") ; MRImask(mri_features, mri_mask, mri_features, 0, 0) ; HISTO2Dfree(&hw) ; HISTO2Dfree(&hp) ; MRIfree(&mri_white_dist) ; MRIfree(&mri_pial_dist) ; MRIfree(&mri_binary) ; return(mri_features) ; }
static MRI * add_interior_points(MRI *mri_src, MRI *mri_vals, float intensity_above, float intensity_below, MRI_SURFACE *mris_white1, MRI_SURFACE *mris_white2, MRI *mri_aseg, MRI *mri_dst) { int x, y, z, ctrl, label, i ; float val ; MRI *mri_core ; MRI *mri_interior, *mri_tmp ; mri_interior = MRIclone(mri_src, NULL) ; MRISfillInterior(mris_white1, mri_src->xsize, mri_interior) ; mri_tmp = MRIclone(mri_src, NULL) ; MRISfillInterior(mris_white2, mri_src->xsize, mri_tmp) ; MRIcopyLabel(mri_tmp, mri_interior, 1) ; if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON) { MRIwrite(mri_interior, "i.mgz") ; } mri_core = MRIerode(mri_interior, NULL) ; for (i = 1 ; i < nint(1.0/mri_src->xsize) ; i++) { MRIcopy(mri_core, mri_tmp) ; MRIerode(mri_tmp, mri_core) ; } MRIfree(&mri_tmp) ; if (mri_aseg == NULL) { for (x = 0 ; x < mri_src->width ; x++) for (y = 0 ; y < mri_src->height ; y++) for (z = 0 ; z < mri_src->depth ; z++) { if (Gx == x && Gy == y && Gz == z) { DiagBreak() ; } ctrl = MRIgetVoxVal(mri_core, x, y, z, 0) ; if (ctrl > 0) { MRIsetVoxVal(mri_dst, x, y, z, 0, ctrl) ; } } } else { for (x = 0 ; x < mri_src->width ; x++) for (y = 0 ; y < mri_src->height ; y++) for (z = 0 ; z < mri_src->depth ; z++) { if (Gx == x && Gy == y && Gz == z) { DiagBreak() ; } ctrl = MRIgetVoxVal(mri_src, x, y, z, 0) ; if (ctrl == 0) // add in some missed ones that are inside the surface { label = MRIgetVoxVal(mri_aseg, x, y, z, 0) ; if (IS_GM(label) || IS_WM(label)) { val = MRIgetVoxVal(mri_vals, x, y, z, 0) ; if ((val >= 110-intensity_below && val <= 110 + intensity_above)&& MRIgetVoxVal(mri_core, x, y, z, 0) > 0) { ctrl = 1 ; } } } MRIsetVoxVal(mri_dst, x, y, z, 0, ctrl) ; } } MRIfree(&mri_core) ; return(mri_dst) ; }
int main(int argc, char *argv[]) { char **av ; int ac, nargs, n ; MRI *mri_src, *mri_dst = NULL, *mri_bias, *mri_orig, *mri_aseg = NULL ; char *in_fname, *out_fname ; int msec, minutes, seconds ; struct timeb start ; char cmdline[CMD_LINE_LEN] ; make_cmd_version_string (argc, argv, "$Id: mri_normalize.c,v 1.80 2012/10/16 21:38:35 nicks Exp $", "$Name: $", cmdline); /* rkt: check for and handle version tag */ nargs = handle_version_option (argc, argv, "$Id: mri_normalize.c,v 1.80 2012/10/16 21:38:35 nicks Exp $", "$Name: $"); if (nargs && argc - nargs == 1) { exit (0); } argc -= nargs; Progname = argv[0] ; ErrorInit(NULL, NULL, NULL) ; DiagInit(NULL, NULL, NULL) ; mni.max_gradient = MAX_GRADIENT ; ac = argc ; av = argv ; for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) { nargs = get_option(argc, argv) ; argc -= nargs ; argv += nargs ; } if (argc < 3) { usage_exit(0) ; } if (argc < 1) { ErrorExit(ERROR_BADPARM, "%s: no input name specified", Progname) ; } in_fname = argv[1] ; if (argc < 2) { ErrorExit(ERROR_BADPARM, "%s: no output name specified", Progname) ; } out_fname = argv[2] ; if(verbose) { printf( "reading from %s...\n", in_fname) ; } mri_src = MRIread(in_fname) ; if (!mri_src) ErrorExit(ERROR_NO_FILE, "%s: could not open source file %s", Progname, in_fname) ; MRIaddCommandLine(mri_src, cmdline) ; if(nsurfs > 0) { MRI_SURFACE *mris ; MRI *mri_dist=NULL, *mri_dist_sup=NULL, *mri_ctrl, *mri_dist_one ; LTA *lta= NULL ; int i ; TRANSFORM *surface_xform ; if (control_point_fname) // do one pass with only file control points first { MRI3dUseFileControlPoints(mri_src, control_point_fname) ; mri_dst = MRI3dGentleNormalize(mri_src, NULL, DEFAULT_DESIRED_WHITE_MATTER_VALUE, NULL, intensity_above, intensity_below/2,1, bias_sigma, mri_not_control); } else { mri_dst = MRIcopy(mri_src, NULL) ; } for (i = 0 ; i < nsurfs ; i++) { mris = MRISread(surface_fnames[i]) ; if (mris == NULL) ErrorExit(ERROR_NOFILE,"%s: could not surface %s", Progname,surface_fnames[i]); surface_xform = surface_xforms[i] ; TransformInvert(surface_xform, NULL) ; if (surface_xform->type == MNI_TRANSFORM_TYPE || surface_xform->type == TRANSFORM_ARRAY_TYPE || surface_xform->type == REGISTER_DAT) { lta = (LTA *)(surface_xform->xform) ; #if 0 if (invert) { VOL_GEOM vgtmp; LT *lt; MATRIX *m_tmp = lta->xforms[0].m_L ; lta->xforms[0].m_L = MatrixInverse(lta->xforms[0].m_L, NULL) ; MatrixFree(&m_tmp) ; lt = <a->xforms[0]; if (lt->dst.valid == 0 || lt->src.valid == 0) { printf( "WARNING:***************************************************************\n"); printf( "WARNING:dst volume infor is invalid. Most likely produce wrong inverse.\n"); printf( "WARNING:***************************************************************\n"); } copyVolGeom(<->dst, &vgtmp); copyVolGeom(<->src, <->dst); copyVolGeom(&vgtmp, <->src); } #endif } if (stricmp(surface_xform_fnames[i], "identity.nofile") != 0) { MRIStransform(mris, NULL, surface_xform, NULL) ; } mri_dist_one = MRIcloneDifferentType(mri_dst, MRI_FLOAT) ; printf("computing distance transform\n") ; MRIScomputeDistanceToSurface(mris, mri_dist_one, mri_dist_one->xsize) ; if (i == 0) { mri_dist = MRIcopy(mri_dist_one, NULL) ; } else { MRIcombineDistanceTransforms(mri_dist_one, mri_dist, mri_dist) ; } // MRIminAbs(mri_dist_one, mri_dist, mri_dist) ; MRIfree(&mri_dist_one) ; } MRIscalarMul(mri_dist, mri_dist, -1) ; if (nonmax_suppress) { printf("computing nonmaximum suppression\n") ; mri_dist_sup = MRInonMaxSuppress(mri_dist, NULL, 0, 1) ; mri_ctrl = MRIcloneDifferentType(mri_dist_sup, MRI_UCHAR) ; MRIbinarize(mri_dist_sup, mri_ctrl, min_dist, CONTROL_NONE, CONTROL_MARKED) ; } else if (erode) { int i ; mri_ctrl = MRIcloneDifferentType(mri_dist, MRI_UCHAR) ; MRIbinarize(mri_dist, mri_ctrl, min_dist, CONTROL_NONE, CONTROL_MARKED) ; for (i = 0 ; i < erode ; i++) { MRIerode(mri_ctrl, mri_ctrl) ; } } else { mri_ctrl = MRIcloneDifferentType(mri_dist, MRI_UCHAR) ; MRIbinarize(mri_dist, mri_ctrl, min_dist, CONTROL_NONE, CONTROL_MARKED) ; } if (control_point_fname) { MRInormAddFileControlPoints(mri_ctrl, CONTROL_MARKED) ; } if (mask_sigma > 0) { MRI *mri_smooth, *mri_mag, *mri_grad ; mri_smooth = MRIgaussianSmooth(mri_dst, mask_sigma, 1, NULL) ; mri_mag = MRIcloneDifferentType(mri_dst, MRI_FLOAT) ; mri_grad = MRIsobel(mri_smooth, NULL, mri_mag) ; MRIbinarize(mri_mag, mri_mag, mask_thresh, 1, 0) ; MRImask(mri_ctrl, mri_mag, mri_ctrl, 0, CONTROL_NONE) ; MRIfree(&mri_grad) ; MRIfree(&mri_mag) ; MRIfree(&mri_smooth) ; } if (mask_orig_fname) { MRI *mri_orig ; mri_orig = MRIread(mask_orig_fname) ; MRIbinarize(mri_orig, mri_orig, mask_orig_thresh, 0, 1) ; MRImask(mri_ctrl, mri_orig, mri_ctrl, 0, CONTROL_NONE) ; MRIfree(&mri_orig) ; } if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON) { MRIwrite(mri_dist, "d.mgz"); MRIwrite(mri_dist_sup, "dm.mgz"); MRIwrite(mri_ctrl, "c.mgz"); } MRIeraseBorderPlanes(mri_ctrl, 4) ; if (aseg_fname) { mri_aseg = MRIread(aseg_fname) ; if (mri_aseg == NULL) { ErrorExit(ERROR_NOFILE, "%s: could not load aseg from %s", Progname, aseg_fname) ; } remove_nonwm_voxels(mri_ctrl, mri_aseg, mri_ctrl) ; MRIfree(&mri_aseg) ; } else { remove_surface_outliers(mri_ctrl, mri_dist, mri_dst, mri_ctrl) ; } mri_bias = MRIbuildBiasImage(mri_dst, mri_ctrl, NULL, 0.0) ; if (mri_dist) { MRIfree(&mri_dist) ; } if (mri_dist_sup) { MRIfree(&mri_dist_sup) ; } if (bias_sigma> 0) { MRI *mri_kernel = MRIgaussian1d(bias_sigma, -1) ; if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON) { MRIwrite(mri_bias, "b.mgz") ; } printf("smoothing bias field\n") ; MRIconvolveGaussian(mri_bias, mri_bias, mri_kernel) ; if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON) { MRIwrite(mri_bias, "bs.mgz") ; } MRIfree(&mri_kernel); } MRIfree(&mri_ctrl) ; mri_dst = MRIapplyBiasCorrectionSameGeometry (mri_dst, mri_bias, mri_dst, DEFAULT_DESIRED_WHITE_MATTER_VALUE) ; printf("writing normalized volume to %s\n", out_fname) ; MRIwrite(mri_dst, out_fname) ; exit(0) ; } // end if(surface_fname) if (!mriConformed(mri_src) && conform > 0) { printf("unconformed source detected - conforming...\n") ; mri_src = MRIconform(mri_src) ; } if (mask_fname) { MRI *mri_mask ; mri_mask = MRIread(mask_fname) ; if (!mri_mask) ErrorExit(ERROR_NOFILE, "%s: could not open mask volume %s.\n", Progname, mask_fname) ; MRImask(mri_src, mri_mask, mri_src, 0, 0) ; MRIfree(&mri_mask) ; } if (read_flag) { MRI *mri_ctrl ; double scale ; mri_bias = MRIread(bias_volume_fname) ; if (!mri_bias) ErrorExit (ERROR_BADPARM, "%s: could not read bias volume %s", Progname, bias_volume_fname) ; mri_ctrl = MRIread(control_volume_fname) ; if (!mri_ctrl) ErrorExit (ERROR_BADPARM, "%s: could not read control volume %s", Progname, control_volume_fname) ; MRIbinarize(mri_ctrl, mri_ctrl, 1, 0, 128) ; mri_dst = MRImultiply(mri_bias, mri_src, NULL) ; scale = MRImeanInLabel(mri_dst, mri_ctrl, 128) ; printf("mean in wm is %2.0f, scaling by %2.2f\n", scale, 110/scale) ; scale = 110/scale ; MRIscalarMul(mri_dst, mri_dst, scale) ; MRIwrite(mri_dst, out_fname) ; exit(0) ; } if(long_flag) { MRI *mri_ctrl ; double scale ; mri_bias = MRIread(long_bias_volume_fname) ; if (!mri_bias) ErrorExit (ERROR_BADPARM, "%s: could not read bias volume %s", Progname, long_bias_volume_fname) ; mri_ctrl = MRIread(long_control_volume_fname) ; if (!mri_ctrl) ErrorExit (ERROR_BADPARM, "%s: could not read control volume %s", Progname, long_control_volume_fname) ; MRIbinarize(mri_ctrl, mri_ctrl, 1, 0, CONTROL_MARKED) ; if (mri_ctrl->type != MRI_UCHAR) { MRI *mri_tmp ; mri_tmp = MRIchangeType(mri_ctrl, MRI_UCHAR, 0, 1,1); MRIfree(&mri_ctrl) ; mri_ctrl = mri_tmp ; } scale = MRImeanInLabel(mri_src, mri_ctrl, CONTROL_MARKED) ; printf("mean in wm is %2.0f, scaling by %2.2f\n", scale, 110/scale) ; scale = DEFAULT_DESIRED_WHITE_MATTER_VALUE/scale ; mri_dst = MRIscalarMul(mri_src, NULL, scale) ; MRIremoveWMOutliers(mri_dst, mri_ctrl, mri_ctrl, intensity_below/2) ; mri_bias = MRIbuildBiasImage(mri_dst, mri_ctrl, NULL, 0.0) ; MRIsoapBubble(mri_bias, mri_ctrl, mri_bias, 50, 1) ; MRIapplyBiasCorrectionSameGeometry(mri_dst, mri_bias, mri_dst, DEFAULT_DESIRED_WHITE_MATTER_VALUE); // MRIwrite(mri_dst, out_fname) ; // exit(0) ; } // end if(long_flag) if (grad_thresh > 0) { float thresh ; MRI *mri_mag, *mri_grad, *mri_smooth ; MRI *mri_kernel = MRIgaussian1d(.5, -1) ; mri_not_control = MRIcloneDifferentType(mri_src, MRI_UCHAR) ; switch (scan_type) { case MRI_MGH_MPRAGE: thresh = 15 ; break ; case MRI_WASHU_MPRAGE: thresh = 20 ; break ; case MRI_UNKNOWN: default: thresh = 12 ; break ; } mri_smooth = MRIconvolveGaussian(mri_src, NULL, mri_kernel) ; thresh = grad_thresh ; mri_mag = MRIcloneDifferentType(mri_src, MRI_FLOAT) ; mri_grad = MRIsobel(mri_smooth, NULL, mri_mag) ; MRIwrite(mri_mag, "m.mgz") ; MRIbinarize(mri_mag, mri_not_control, thresh, 0, 1) ; MRIwrite(mri_not_control, "nc.mgz") ; MRIfree(&mri_mag) ; MRIfree(&mri_grad) ; MRIfree(&mri_smooth) ; MRIfree(&mri_kernel) ; } #if 0 #if 0 if ((mri_src->type != MRI_UCHAR) || (!(mri_src->xsize == 1 && mri_src->ysize == 1 && mri_src->zsize == 1))) #else if (conform || (mri_src->type != MRI_UCHAR && conform > 0)) #endif { MRI *mri_tmp ; fprintf (stderr, "downsampling to 8 bits and scaling to isotropic voxels...\n") ; mri_tmp = MRIconform(mri_src) ; mri_src = mri_tmp ; } #endif if(aseg_fname) { printf("Reading aseg %s\n",aseg_fname); mri_aseg = MRIread(aseg_fname) ; if (mri_aseg == NULL) ErrorExit (ERROR_NOFILE, "%s: could not read aseg from file %s", Progname, aseg_fname) ; if (!mriConformed(mri_aseg)) { ErrorExit(ERROR_UNSUPPORTED, "%s: aseg volume %s must be conformed", Progname, aseg_fname) ; } } else { mri_aseg = NULL ; } if(verbose) { printf( "normalizing image...\n") ; } fflush(stdout); fflush(stderr); TimerStart(&start) ; if (control_point_fname) { MRI3dUseFileControlPoints(mri_src, control_point_fname) ; } // this just setup writing control-point volume saving if(control_volume_fname) { MRI3dWriteControlPoints(control_volume_fname) ; } /* first do a gentle normalization to get things in the right intensity range */ if(long_flag == 0) // if long, then this will already have been done with base control points { if(control_point_fname != NULL) /* do one pass with only file control points first */ mri_dst = MRI3dGentleNormalize(mri_src, NULL, DEFAULT_DESIRED_WHITE_MATTER_VALUE, NULL, intensity_above, intensity_below/2,1, bias_sigma, mri_not_control); else { mri_dst = MRIcopy(mri_src, NULL) ; } } fflush(stdout); fflush(stderr); if(mri_aseg) { MRI *mri_ctrl, *mri_bias ; int i ; printf("processing with aseg\n"); mri_ctrl = MRIclone(mri_aseg, NULL) ; for (i = 0 ; i < NWM_LABELS ; i++) { MRIcopyLabel(mri_aseg, mri_ctrl, aseg_wm_labels[i]) ; } printf("removing outliers in the aseg WM...\n") ; MRIremoveWMOutliersAndRetainMedialSurface(mri_dst, mri_ctrl, mri_ctrl, intensity_below) ; MRIbinarize(mri_ctrl, mri_ctrl, 1, CONTROL_NONE, CONTROL_MARKED) ; MRInormAddFileControlPoints(mri_ctrl, CONTROL_MARKED) ; if (interior_fname1) { MRIS *mris_interior1, *mris_interior2 ; mris_interior1 = MRISread(interior_fname1) ; if (mris_interior1 == NULL) ErrorExit(ERROR_NOFILE, "%s: could not read white matter surface from %s\n", Progname, interior_fname1) ; mris_interior2 = MRISread(interior_fname2) ; if (mris_interior2 == NULL) ErrorExit(ERROR_NOFILE, "%s: could not read white matter surface from %s\n", Progname, interior_fname2) ; add_interior_points(mri_ctrl, mri_dst, intensity_above, 1.25*intensity_below, mris_interior1, mris_interior2, mri_aseg, mri_ctrl) ; MRISfree(&mris_interior1) ; MRISfree(&mris_interior2) ; } if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON) { MRIwrite(mri_ctrl, "norm_ctrl.mgz") ; } printf("Building bias image\n"); fflush(stdout); fflush(stderr); mri_bias = MRIbuildBiasImage(mri_dst, mri_ctrl, NULL, 0.0) ; fflush(stdout); fflush(stderr); if (bias_sigma> 0) { printf("Smoothing with sigma %g\n",bias_sigma); MRI *mri_kernel = MRIgaussian1d(bias_sigma, -1) ; MRIconvolveGaussian(mri_bias, mri_bias, mri_kernel) ; MRIfree(&mri_kernel); fflush(stdout); fflush(stderr); } MRIfree(&mri_ctrl) ; MRIfree(&mri_aseg) ; printf("Applying bias correction\n"); mri_dst = MRIapplyBiasCorrectionSameGeometry (mri_dst, mri_bias, mri_dst, DEFAULT_DESIRED_WHITE_MATTER_VALUE) ; if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON) { MRIwrite(mri_dst, "norm_1.mgz") ; } fflush(stdout); fflush(stderr); } // if(mri_aseg) else { printf("processing without aseg, no1d=%d\n",no1d); if (!no1d) { printf("MRInormInit(): \n"); MRInormInit(mri_src, &mni, 0, 0, 0, 0, 0.0f) ; printf("MRInormalize(): \n"); mri_dst = MRInormalize(mri_src, NULL, &mni) ; if (!mri_dst) { no1d = 1 ; printf("1d normalization failed - trying no1d...\n") ; // ErrorExit(ERROR_BADPARM, "%s: normalization failed", Progname) ; } } if(no1d) { if ((file_only && nosnr) || ((gentle_flag != 0) && (control_point_fname != NULL))) { if (mri_dst == NULL) { mri_dst = MRIcopy(mri_src, NULL) ; } } else { if (nosnr) { if (interior_fname1) { MRIS *mris_interior1, *mris_interior2 ; MRI *mri_ctrl ; printf("computing initial normalization using surface interiors\n"); mri_ctrl = MRIcloneDifferentType(mri_src, MRI_UCHAR) ; mris_interior1 = MRISread(interior_fname1) ; if (mris_interior1 == NULL) ErrorExit(ERROR_NOFILE, "%s: could not read white matter surface from %s\n", Progname, interior_fname1) ; mris_interior2 = MRISread(interior_fname2) ; if (mris_interior2 == NULL) ErrorExit(ERROR_NOFILE, "%s: could not read white matter surface from %s\n", Progname, interior_fname2) ; add_interior_points(mri_ctrl, mri_dst, intensity_above, 1.25*intensity_below, mris_interior1, mris_interior2, mri_aseg, mri_ctrl) ; MRISfree(&mris_interior1) ; MRISfree(&mris_interior2) ; mri_bias = MRIbuildBiasImage(mri_dst, mri_ctrl, NULL, 0.0) ; if (bias_sigma> 0) { MRI *mri_kernel = MRIgaussian1d(bias_sigma, -1) ; MRIconvolveGaussian(mri_bias, mri_bias, mri_kernel) ; MRIfree(&mri_kernel); } mri_dst = MRIapplyBiasCorrectionSameGeometry (mri_src, mri_bias, mri_dst, DEFAULT_DESIRED_WHITE_MATTER_VALUE) ; MRIfree(&mri_ctrl) ; } else if (long_flag == 0) // no initial normalization specified { mri_dst = MRIcopy(mri_src, NULL) ; } } else { printf("computing initial normalization using SNR...\n") ; mri_dst = MRInormalizeHighSignalLowStd (mri_src, mri_dst, bias_sigma, DEFAULT_DESIRED_WHITE_MATTER_VALUE) ; } } if (!mri_dst) ErrorExit (ERROR_BADPARM, "%s: could not allocate volume", Progname) ; } } // else (not using aseg) fflush(stdout); fflush(stderr); if (file_only == 0) MRI3dGentleNormalize(mri_dst, NULL, DEFAULT_DESIRED_WHITE_MATTER_VALUE, mri_dst, intensity_above, intensity_below/2, file_only, bias_sigma, mri_not_control); mri_orig = MRIcopy(mri_dst, NULL) ; printf("\n"); printf("Iterating %d times\n",num_3d_iter); for (n = 0 ; n < num_3d_iter ; n++) { if(file_only) { break ; } printf( "---------------------------------\n"); printf( "3d normalization pass %d of %d\n", n+1, num_3d_iter) ; if (gentle_flag) MRI3dGentleNormalize(mri_dst, NULL, DEFAULT_DESIRED_WHITE_MATTER_VALUE, mri_dst, intensity_above/2, intensity_below/2, file_only, bias_sigma, mri_not_control); else MRI3dNormalize(mri_orig, mri_dst, DEFAULT_DESIRED_WHITE_MATTER_VALUE, mri_dst, intensity_above, intensity_below, file_only, prune, bias_sigma, scan_type, mri_not_control); } printf( "Done iterating ---------------------------------\n"); // this just setup writing control-point volume saving if(control_volume_fname) { MRI3dWriteControlPoints(control_volume_fname) ; } if(bias_volume_fname) { mri_bias = compute_bias(mri_src, mri_dst, NULL) ; printf("writing bias field to %s....\n", bias_volume_fname) ; MRIwrite(mri_bias, bias_volume_fname) ; MRIfree(&mri_bias) ; } if (verbose) { printf("writing output to %s\n", out_fname) ; } MRIwrite(mri_dst, out_fname) ; msec = TimerStop(&start) ; MRIfree(&mri_src); MRIfree(&mri_dst); seconds = nint((float)msec/1000.0f) ; minutes = seconds / 60 ; seconds = seconds % 60 ; printf( "3D bias adjustment took %d minutes and %d seconds.\n", minutes, seconds) ; exit(0) ; return(0) ; }
static MRI * MRIremoveWMOutliersAndRetainMedialSurface(MRI *mri_src, MRI *mri_src_ctrl, MRI *mri_dst_ctrl, int intensity_below) { MRI *mri_inside, *mri_bin ; HISTOGRAM *histo, *hsmooth ; int wm_peak, x, y, z, nremoved ; float thresh, hi_thresh ; double val, lmean, max ; if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON) { MRIwrite(mri_src_ctrl, "sc.mgz") ; } if (mri_dst_ctrl != mri_src_ctrl) { mri_dst_ctrl = MRIcopy(mri_src_ctrl, mri_dst_ctrl) ; } mri_inside = MRIerode(mri_dst_ctrl, NULL) ; MRIbinarize(mri_inside, mri_inside, 1, 0, 1) ; histo = MRIhistogramLabel(mri_src, mri_inside, 1, 256) ; hsmooth = HISTOcopy(histo, NULL) ; HISTOsmooth(histo, hsmooth, 2) ; if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON) { HISTOplot(histo, "h.plt") ; HISTOplot(hsmooth, "hs.plt") ; } printf("using wm (%d) threshold %2.1f for removing exterior voxels\n", wm_peak, thresh) ; wm_peak = HISTOfindHighestPeakInRegion(hsmooth, 1, hsmooth->nbins-1) ; wm_peak = hsmooth->bins[wm_peak] ; thresh = wm_peak-intensity_below ; hi_thresh = wm_peak-.5*intensity_below ; printf("using wm (%d) threshold %2.1f for removing exterior voxels\n", wm_peak, thresh) ; // now remove stuff that's on the border and is pretty dark for (nremoved = x = 0 ; x < mri_src->width ; x++) { for (y = 0 ; y < mri_src->height ; y++) { for (z = 0 ; z < mri_src->depth ; z++) { if (x == Gx && y == Gy && z == Gz) { DiagBreak() ; } /* if it's a control point, it's not in the interior of the wm, and it's T1 val is too low */ if (MRIgetVoxVal(mri_dst_ctrl, x, y, z, 0) == 0) { continue ; // not a control point } /* if it's way far from the wm mode then remove it even if it's in the interior */ val = MRIgetVoxVal(mri_src, x, y, z, 0) ; if (val < thresh-5) { MRIsetVoxVal(mri_dst_ctrl, x, y, z, 0, 0) ; nremoved++ ; } if (nint(MRIgetVoxVal(mri_inside, x, y, z, 0)) > 0) // don't process interior voxels further { continue ; // in the interior } if (val < thresh) { MRIsetVoxVal(mri_dst_ctrl, x, y, z, 0, 0) ; nremoved++ ; } else { lmean = MRImeanInLabelInRegion(mri_src, mri_inside, 1, x, y, z, 7); if (val < lmean-10) { MRIsetVoxVal(mri_dst_ctrl, x, y, z, 0, 0) ; nremoved++ ; } } } } } #if 0 for (x = 0 ; x < mri_src->width ; x++) { for (y = 0 ; y < mri_src->height ; y++) { for (z = 0 ; z < mri_src->depth ; z++) { if (x == Gx && y == Gy && z == Gz) { DiagBreak() ; } /* if it's a control point, it's not in the interior of the wm, and it's T1 val is too low */ if (MRIgetVoxVal(mri_dst_ctrl, x, y, z, 0) == 0) { continue ; // not a control point } if (MRIcountNonzeroInNbhd(mri_dst_ctrl,3, x, y, z)<=2) { MRIsetVoxVal(mri_dst_ctrl, x, y, z, 0, 0) ; nremoved++ ; } } } } #endif /* now take out voxels that have too big an intensity diff with surrounding ones */ mri_bin = MRIbinarize(mri_dst_ctrl, NULL, 1, 0, 1) ; for (x = 0 ; x < mri_src->width ; x++) { for (y = 0 ; y < mri_src->height ; y++) { for (z = 0 ; z < mri_src->depth ; z++) { if (x == Gx && y == Gy && z == Gz) { DiagBreak() ; } /* if it's a control point, it's not in the interior of the wm, and it's T1 val is too low */ if (MRIgetVoxVal(mri_dst_ctrl, x, y, z, 0) == 0) { continue ; // not a control point } val = MRIgetVoxVal(mri_src, x, y, z, 0) ; max = MRImaxInLabelInRegion(mri_src, mri_bin, 1, x, y, z, 3); if (val+7 < max && val < hi_thresh) { MRIsetVoxVal(mri_dst_ctrl, x, y, z, 0, 0) ; nremoved++ ; } } } } MRIfree(&mri_bin) ; printf( "%d control points removed\n", nremoved) ; if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON) { MRIwrite(mri_dst_ctrl, "dc.mgz") ; } HISTOfree(&histo) ; HISTOfree(&hsmooth) ; MRIfree(&mri_inside) ; return(mri_dst_ctrl) ; }
int main(int argc, char *argv[]) { char **av, *label_name, *vol_name, *out_name ; int ac, nargs ; int msec, minutes, seconds, i ; LABEL *area ; struct timeb start ; MRI *mri, *mri_seg ; Real xw, yw, zw, xv, yv, zv, val; /* rkt: check for and handle version tag */ nargs = handle_version_option (argc, argv, "$Id: mri_label_vals.c,v 1.16 2015/08/24 18:22:05 fischl Exp $", "$Name: $"); if (nargs && argc - nargs == 1) exit (0); argc -= nargs; Progname = argv[0] ; ErrorInit(NULL, NULL, NULL) ; DiagInit(NULL, NULL, NULL) ; TimerStart(&start) ; ac = argc ; av = argv ; for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) { nargs = get_option(argc, argv) ; argc -= nargs ; argv += nargs ; } if (argc < 3) usage_exit(1) ; vol_name = argv[1] ; label_name = argv[2] ; out_name = argv[3] ; mri = MRIread(vol_name) ; if (!mri) ErrorExit(ERROR_NOFILE, "%s: could not read volume from %s",Progname, vol_name) ; if (scaleup_flag) { float scale, fov_x, fov_y, fov_z ; scale = 1.0/MIN(MIN(mri->xsize, mri->ysize),mri->zsize) ; fprintf(stderr, "scaling voxel sizes up by %2.2f\n", scale) ; mri->xsize *= scale ; mri->ysize *= scale ; mri->zsize *= scale ; fov_x = mri->xsize * mri->width; fov_y = mri->ysize * mri->height; fov_z = mri->zsize * mri->depth; mri->xend = fov_x / 2.0; mri->xstart = -mri->xend; mri->yend = fov_y / 2.0; mri->ystart = -mri->yend; mri->zend = fov_z / 2.0; mri->zstart = -mri->zend; mri->fov = (fov_x > fov_y ? (fov_x > fov_z ? fov_x : fov_z) : (fov_y > fov_z ? fov_y : fov_z) ); } if (segmentation_flag >= 0) { int x, y, z ; VECTOR *v_seg, *v_mri ; MATRIX *m_seg_to_mri ; v_seg = VectorAlloc(4, MATRIX_REAL) ; v_mri = VectorAlloc(4, MATRIX_REAL) ; VECTOR_ELT(v_seg, 4) = 1.0 ; VECTOR_ELT(v_mri, 4) = 1.0 ; mri_seg = MRIread(argv[2]) ; if (!mri_seg) ErrorExit(ERROR_NOFILE, "%s: could not read volume from %s",Progname, argv[2]) ; if (erode) { MRI *mri_tmp ; mri_tmp = MRIclone(mri_seg, NULL) ; MRIcopyLabel(mri_seg, mri_tmp, segmentation_flag) ; while (erode-- > 0) MRIerode(mri_tmp, mri_tmp) ; MRIcopy(mri_tmp, mri_seg) ; MRIfree(&mri_tmp) ; } m_seg_to_mri = MRIgetVoxelToVoxelXform(mri_seg, mri) ; for (x = 0 ; x < mri_seg->width ; x++) { V3_X(v_seg) = x ; for (y = 0 ; y < mri_seg->height ; y++) { V3_Y(v_seg) = y ; for (z = 0 ; z < mri_seg->depth ; z++) { V3_Z(v_seg) = z ; if (MRIvox(mri_seg, x, y, z) == segmentation_flag) { MatrixMultiply(m_seg_to_mri, v_seg, v_mri) ; xv = V3_X(v_mri) ; yv = V3_Y(v_mri) ; zv = V3_Z(v_mri) ; MRIsampleVolumeType(mri, xv, yv, zv, &val, SAMPLE_NEAREST); #if 0 if (val < .000001) { val *= 1000000; printf("%f*0.000001\n", val); } else #endif if (coords) printf("%2.1f %2.1f %2.1f %f\n", xv, yv, zv, val); else printf("%f\n", val); } } } } MatrixFree(&m_seg_to_mri) ; VectorFree(&v_seg) ; VectorFree(&v_mri) ; } else { if (cras == 1) fprintf(stderr,"using the label coordinates to be c_(r,a,s) != 0.\n"); if (surface_dir) { MRI_SURFACE *mris ; char fname[STRLEN] ; sprintf(fname, "%s/%s.white", surface_dir, hemi) ; mris = MRISread(fname) ; if (mris == NULL) ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s...\n", Progname,fname) ; sprintf(fname, "%s/%s.thickness", surface_dir, hemi) ; if (MRISreadCurvatureFile(mris, fname) != NO_ERROR) ErrorExit(ERROR_BADPARM, "%s: could not read thickness file %s...\n", Progname,fname) ; if (annot_prefix) /* read an annotation in and print vals in it */ { #define MAX_ANNOT 10000 int vno, annot_counts[MAX_ANNOT], index ; VERTEX *v ; Real xw, yw, zw, xv, yv, zv, val ; float annot_means[MAX_ANNOT] ; FILE *fp ; memset(annot_means, 0, sizeof(annot_means)) ; memset(annot_counts, 0, sizeof(annot_counts)) ; if (MRISreadAnnotation(mris, label_name) != NO_ERROR) ErrorExit(ERROR_BADPARM, "%s: could not read annotation file %s...\n", Progname,fname) ; if (mris->ct == NULL) ErrorExit(ERROR_BADPARM, "%s: annot file does not contain a color table, specifiy one with -t ", Progname); for (vno = 0 ; vno < mris->nvertices ; vno++) { v = &mris->vertices[vno] ; if (v->ripflag) continue ; CTABfindAnnotation(mris->ct, v->annotation, &index) ; if (index >= 0 && index < mris->ct->nentries) { annot_counts[index]++ ; xw = v->x + v->curv*.5*v->nx ; yw = v->y + v->curv*.5*v->ny ; zw = v->z + v->curv*.5*v->nz ; if (cras == 1) MRIworldToVoxel(mri, xw, yw, zw, &xv, &yv, &zv) ; else MRIsurfaceRASToVoxel(mri, xw, yw, zw, &xv, &yv, &zv); MRIsampleVolume(mri, xv, yv, zv, &val) ; annot_means[index] += val ; sprintf(fname, "%s-%s-%s.dat", annot_prefix, hemi, mris->ct->entries[index]->name) ; fp = fopen(fname, "a") ; fprintf(fp, "%f\n", val) ; fclose(fp) ; } } } else /* read label in and print vals in it */ { area = LabelRead(NULL, label_name) ; if (!area) ErrorExit(ERROR_NOFILE, "%s: could not read label from %s",Progname, label_name) ; } } else { area = LabelRead(NULL, label_name) ; if (!area) ErrorExit(ERROR_NOFILE, "%s: could not read label from %s",Progname, label_name) ; for (i = 0 ; i < area->n_points ; i++) { xw = area->lv[i].x ; yw = area->lv[i].y ; zw = area->lv[i].z ; if (cras == 1) MRIworldToVoxel(mri, xw, yw, zw, &xv, &yv, &zv) ; else MRIsurfaceRASToVoxel(mri, xw, yw, zw, &xv, &yv, &zv); MRIsampleVolumeType(mri, xv, yv, zv, &val, SAMPLE_NEAREST); #if 0 if (val < .000001) { val *= 1000000; printf("%f*0.000001\n", val); } else #endif printf("%f\n", val); } } } msec = TimerStop(&start) ; seconds = nint((float)msec/1000.0f) ; minutes = seconds / 60 ; seconds = seconds % 60 ; if (DIAG_VERBOSE_ON) fprintf(stderr, "label value extractiong took %d minutes and %d seconds.\n", minutes, seconds) ; exit(0) ; return(0) ; }
int main(int argc, char *argv[]) { char **av, *cp ; int ac, nargs, i, dof, no_transform, which, sno = 0, nsubjects = 0 ; MRI *mri=0, *mri_mean = NULL, *mri_std=0, *mri_T1=0,*mri_binary=0,*mri_dof=NULL, *mri_priors = NULL ; char *subject_name, *out_fname, fname[STRLEN] ; /* LTA *lta;*/ MRI *mri_tmp=0 ; /* rkt: check for and handle version tag */ nargs = handle_version_option (argc, argv, "$Id: mri_make_template.c,v 1.26 2011/03/02 00:04:22 nicks Exp $", "$Name: stable5 $"); if (nargs && argc - nargs == 1) exit (0); argc -= nargs; Progname = argv[0] ; ErrorInit(NULL, NULL, NULL) ; DiagInit(NULL, NULL, NULL) ; ac = argc ; av = argv ; for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) { nargs = get_option(argc, argv) ; argc -= nargs ; argv += nargs ; } if (!strlen(subjects_dir)) { cp = getenv("SUBJECTS_DIR") ; if (!cp) ErrorExit(ERROR_BADPARM,"%s: SUBJECTS_DIR not defined in environment.\n", Progname) ; strcpy(subjects_dir, cp) ; } if (argc < 3) usage_exit(1) ; out_fname = argv[argc-1] ; no_transform = first_transform ; if (binary_name) /* generate binarized volume with priors and */ { /* separate means and variances */ for (which = BUILD_PRIORS ; which <= OFF_STATS ; which++) { /* for each subject specified on cmd line */ for (dof = 0, i = 1 ; i < argc-1 ; i++) { if (*argv[i] == '-') /* don't do transform for next subject */ { no_transform = 1 ; continue ; } dof++ ; subject_name = argv[i] ; if (which != BUILD_PRIORS) { sprintf(fname, "%s/%s/mri/%s", subjects_dir, subject_name, T1_name); fprintf(stderr, "%d of %d: reading %s...\n", i, argc-2, fname) ; mri_T1 = MRIread(fname) ; if (!mri_T1) ErrorExit(ERROR_NOFILE,"%s: could not open volume %s", Progname,fname); } sprintf(fname, "%s/%s/mri/%s",subjects_dir,subject_name,binary_name); fprintf(stderr, "%d of %d: reading %s...\n", i, argc-2, fname) ; mri_binary = MRIread(fname) ; if (!mri_binary) ErrorExit(ERROR_NOFILE,"%s: could not open volume %s", Progname,fname); /* only count voxels which are mostly labeled */ MRIbinarize(mri_binary, mri_binary, WM_MIN_VAL, 0, 100) ; if (transform_fname && no_transform-- <= 0) { sprintf(fname, "%s/%s/mri/transforms/%s", subjects_dir, subject_name, transform_fname) ; fprintf(stderr, "reading transform %s...\n", fname) ; //////////////////////////////////////////////////////// #if 1 { TRANSFORM *transform ; transform = TransformRead(fname) ; if (transform == NULL) ErrorExit(ERROR_NOFILE, "%s: could not open transform file %s\n",Progname, fname) ; mri_tmp = TransformApply(transform, mri_T1, NULL) ; TransformFree(&transform) ; } #else lta = LTAreadEx(fname); if (lta == NULL) ErrorExit(ERROR_NOFILE, "%s: could not open transform file %s\n", Progname, fname) ; /* LTAtransform() runs either MRIapplyRASlinearTransform() for RAS2RAS or MRIlinearTransform() for Vox2Vox. */ /* MRIlinearTransform() calls MRIlinearTransformInterp() */ mri_tmp = LTAtransform(mri_T1, NULL, lta); MRIfree(&mri_T1) ; mri_T1 = mri_tmp ; LTAfree(<a); lta = NULL; #endif if (DIAG_VERBOSE_ON) fprintf(stderr, "transform application complete.\n") ; } if (which == BUILD_PRIORS) { mri_priors = MRIupdatePriors(mri_binary, mri_priors) ; } else { if (!mri_mean) { mri_dof = MRIalloc(mri_T1->width, mri_T1->height, mri_T1->depth, MRI_UCHAR) ; mri_mean = MRIalloc(mri_T1->width, mri_T1->height,mri_T1->depth,MRI_FLOAT); mri_std = MRIalloc(mri_T1->width,mri_T1->height,mri_T1->depth,MRI_FLOAT); if (!mri_mean || !mri_std) ErrorExit(ERROR_NOMEMORY, "%s: could not allocate templates.\n", Progname) ; } if (DIAG_VERBOSE_ON) fprintf(stderr, "updating mean and variance estimates...\n") ; if (which == ON_STATS) { MRIaccumulateMaskedMeansAndVariances(mri_T1, mri_binary, mri_dof, 90, 100, mri_mean, mri_std) ; fprintf(stderr, "T1 = %d, binary = %d, mean = %2.1f\n", (int)MRIgetVoxVal(mri_T1, 141,100,127,0), MRIvox(mri_binary, 141,100,127), MRIFvox(mri_mean, 141,100,127)) ; } else /* computing means and vars for off */ MRIaccumulateMaskedMeansAndVariances(mri_T1, mri_binary, mri_dof, 0, WM_MIN_VAL-1, mri_mean, mri_std) ; MRIfree(&mri_T1) ; } MRIfree(&mri_binary) ; } if (which == BUILD_PRIORS) { mri = MRIcomputePriors(mri_priors, dof, NULL) ; MRIfree(&mri_priors) ; fprintf(stderr, "writing priors to %s...\n", out_fname) ; } else { MRIcomputeMaskedMeansAndStds(mri_mean, mri_std, mri_dof) ; mri_mean->dof = dof ; fprintf(stderr, "writing T1 means with %d dof to %s...\n", mri_mean->dof, out_fname) ; if (!which) MRIwrite(mri_mean, out_fname) ; else MRIappend(mri_mean, out_fname) ; MRIfree(&mri_mean) ; fprintf(stderr, "writing T1 variances to %s...\n", out_fname); if (dof <= 1) MRIreplaceValues(mri_std, mri_std, 0, 1) ; mri = mri_std ; } if (!which) MRIwrite(mri, out_fname) ; else MRIappend(mri, out_fname) ; MRIfree(&mri) ; } } else { /* for each subject specified on cmd line */ if (xform_mean_fname) { m_xform_mean = MatrixAlloc(4,4,MATRIX_REAL) ; /* m_xform_covariance = MatrixAlloc(12,12,MATRIX_REAL) ;*/ } dof = 0; for (i = 1 ; i < argc-1 ; i++) { if (*argv[i] == '-') { /* don't do transform for next subject */ no_transform = 1 ; continue ; } dof++ ; subject_name = argv[i] ; sprintf(fname, "%s/%s/mri/%s", subjects_dir, subject_name, T1_name); fprintf(stderr, "%d of %d: reading %s...\n", i, argc-2, fname) ; mri_T1 = MRIread(fname) ; if (!mri_T1) ErrorExit(ERROR_NOFILE,"%s: could not open volume %s",Progname,fname); check_mri(mri_T1) ; if (binarize) MRIbinarize(mri_T1, mri_T1, binarize, 0, 1) ; if (erode) { int i ; printf("eroding input %d times\n", erode) ; for (i = 0 ; i < erode ; i++) MRIerode(mri_T1, mri_T1) ; } if (open) { int i ; printf("opening input %d times\n", open) ; for (i = 0 ; i < open ; i++) MRIerode(mri_T1, mri_T1) ; for (i = 0 ; i < open ; i++) MRIdilate(mri_T1, mri_T1) ; } check_mri(mri_T1) ; if (transform_fname) { sprintf(fname, "%s/%s/mri/transforms/%s", subjects_dir, subject_name, transform_fname) ; fprintf(stderr, "reading transform %s...\n", fname) ; //////////////////////////////////////////////////////// #if 1 { TRANSFORM *transform ; transform = TransformRead(fname) ; if (transform == NULL) ErrorExit(ERROR_NOFILE, "%s: could not open transform file %s\n",Progname, fname) ; mri_tmp = TransformApply(transform, mri_T1, NULL) ; if (DIAG_VERBOSE_ON) MRIwrite(mri_tmp, "t1.mgz") ; TransformFree(&transform) ; } #else lta = LTAreadEx(fname); if (lta == NULL) ErrorExit(ERROR_NOFILE, "%s: could not open transform file %s\n", Progname, fname) ; printf("transform matrix -----------------------\n"); MatrixPrint(stdout,lta->xforms[0].m_L); /* LTAtransform() runs either MRIapplyRASlinearTransform() for RAS2RAS or MRIlinearTransform() for Vox2Vox. */ /* MRIlinearTransform() calls MRIlinearTransformInterp() */ mri_tmp = LTAtransform(mri_T1, NULL, lta); printf("----- -----------------------\n"); LTAfree(<a); #endif MRIfree(&mri_T1); mri_T1 = mri_tmp ; // reassign pointers if (DIAG_VERBOSE_ON) fprintf(stderr, "transform application complete.\n") ; } if (!mri_mean) { mri_mean = MRIalloc(mri_T1->width, mri_T1->height, mri_T1->depth, MRI_FLOAT) ; mri_std = MRIalloc(mri_T1->width, mri_T1->height, mri_T1->depth, MRI_FLOAT) ; if (!mri_mean || !mri_std) ErrorExit(ERROR_NOMEMORY, "%s: could not allocate templates.\n", Progname) ; // if(transform_fname == NULL){ if (DIAG_VERBOSE_ON) printf("Copying geometry\n"); MRIcopyHeader(mri_T1,mri_mean); MRIcopyHeader(mri_T1,mri_std); // } } check_mri(mri_mean) ; if (!stats_only) { if (DIAG_VERBOSE_ON) fprintf(stderr, "updating mean and variance estimates...\n") ; MRIaccumulateMeansAndVariances(mri_T1, mri_mean, mri_std) ; } check_mri(mri_mean) ; if (DIAG_VERBOSE_ON) MRIwrite(mri_mean, "t2.mgz") ; MRIfree(&mri_T1) ; no_transform = 0; } /* end loop over subjects */ if (xform_mean_fname) { FILE *fp ; VECTOR *v = NULL, *vT = NULL ; MATRIX *m_vvT = NULL ; int rows, cols ; nsubjects = sno ; fp = fopen(xform_covariance_fname, "w") ; if (!fp) ErrorExit(ERROR_NOFILE, "%s: could not open covariance file %s", Progname, xform_covariance_fname) ; fprintf(fp, "nsubjects=%d\n", nsubjects) ; MatrixScalarMul(m_xform_mean, 1.0/(double)nsubjects, m_xform_mean) ; printf("means:\n") ; MatrixPrint(stdout, m_xform_mean) ; MatrixAsciiWrite(xform_mean_fname, m_xform_mean) ; /* subtract the mean from each transform */ rows = m_xform_mean->rows ; cols = m_xform_mean->cols ; for (sno = 0 ; sno < nsubjects ; sno++) { MatrixSubtract(m_xforms[sno], m_xform_mean, m_xforms[sno]) ; v = MatrixReshape(m_xforms[sno], v, rows*cols, 1) ; vT = MatrixTranspose(v, vT) ; m_vvT = MatrixMultiply(v, vT, m_vvT) ; if (!m_xform_covariance) m_xform_covariance = MatrixAlloc(m_vvT->rows, m_vvT->cols,MATRIX_REAL) ; MatrixAdd(m_vvT, m_xform_covariance, m_xform_covariance) ; MatrixAsciiWriteInto(fp, m_xforms[sno]) ; } MatrixScalarMul(m_xform_covariance, 1.0/(double)nsubjects, m_xform_covariance) ; printf("covariance:\n") ; MatrixPrint(stdout, m_xform_covariance) ; MatrixAsciiWriteInto(fp, m_xform_covariance) ; fclose(fp) ; if (stats_only) exit(0) ; } MRIcomputeMeansAndStds(mri_mean, mri_std, dof) ; check_mri(mri_mean) ; check_mri(mri_std) ; mri_mean->dof = dof ; if (smooth) { MRI *mri_kernel, *mri_smooth ; printf("applying smoothing kernel\n") ; mri_kernel = MRIgaussian1d(smooth, 100) ; mri_smooth = MRIconvolveGaussian(mri_mean, NULL, mri_kernel) ; MRIfree(&mri_kernel) ; MRIfree(&mri_mean) ; mri_mean = mri_smooth ; } fprintf(stderr, "\nwriting T1 means with %d dof to %s...\n", mri_mean->dof, out_fname) ; MRIwrite(mri_mean, out_fname) ; MRIfree(&mri_mean) ; if (dof <= 1) /* can't calculate variances - set them to reasonable val */ { // src dst MRIreplaceValues(mri_std, mri_std, 0, 1) ; } if (!novar) { // mri_std contains the variance here (does it?? I don't think so -- BRF) if (!var_fname) { fprintf(stderr, "\nwriting T1 standard deviations to %s...\n", out_fname); MRIappend(mri_std, out_fname) ; } else { fprintf(stderr, "\nwriting T1 standard deviations to %s...\n", var_fname); MRIwrite(mri_std, var_fname) ; } } MRIfree(&mri_std) ; if (mri) MRIfree(&mri); } /* end if binarize */ return(0) ; }