Пример #1
0
int
main(int argc, char *argv[])
{
  char         **av, *source_fname, *target_fname, *out_fname, fname[STRLEN] ;
  int          ac, nargs, new_transform = 0, pad ;
  MRI          *mri_target, *mri_source, *mri_orig_source ;
  MRI_REGION   box ;
  struct timeb start ;
  int          msec, minutes, seconds ;
  GCA_MORPH    *gcam ;
  MATRIX       *m_L/*, *m_I*/ ;
  LTA          *lta ;


  /* initialize the morph params */
  memset(&mp, 0, sizeof(GCA_MORPH_PARMS));
  /* for nonlinear morph */
  mp.l_jacobian = 1 ;
  mp.min_sigma = 0.4 ;
  mp.l_distance = 0 ;
  mp.l_log_likelihood = .025 ;
  mp.dt = 0.005 ;
  mp.noneg = True ;
  mp.exp_k = 20 ;
  mp.diag_write_snapshots = 1 ;
  mp.momentum = 0.9 ;
  if (FZERO(mp.l_smoothness))
    mp.l_smoothness = 2 ;
  mp.sigma = 8 ;
  mp.relabel_avgs = -1 ;
  mp.navgs = 256 ;
  mp.levels = 6 ;
  mp.integration_type = GCAM_INTEGRATE_BOTH ;
  mp.nsmall = 1 ;
  mp.reset_avgs = -1 ;
  mp.npasses = 3 ;
  mp.regrid = regrid? True : False ;
  mp.tol = 0.1 ;
  mp.niterations = 1000 ;
	
  TimerStart(&start) ;
  setRandomSeed(-1L) ;
  DiagInit(NULL, NULL, NULL) ;
  ErrorInit(NULL, NULL, NULL) ;

  Progname = argv[0] ;
  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(1) ;

  source_fname = argv[1] ;
  target_fname = argv[2] ;
  out_fname = argv[3] ;
  FileNameOnly(out_fname, fname) ;
  FileNameRemoveExtension(fname, fname) ;
  strcpy(mp.base_name, fname) ;
  mri_source = MRIread(source_fname) ;
  if (!mri_source)
    ErrorExit(ERROR_NOFILE, "%s: could not read source label volume %s",
	      Progname, source_fname) ;

  if (mri_source->type == MRI_INT)
    {
      MRI *mri_tmp = MRIchangeType(mri_source, MRI_FLOAT, 0, 1, 1) ;
      MRIfree(&mri_source); mri_source = mri_tmp ;
    }
  mri_target = MRIread(target_fname) ;
  if (!mri_target)
    ErrorExit(ERROR_NOFILE, "%s: could not read target label volume %s",
	      Progname, target_fname) ;
  if (mri_target->type == MRI_INT)
    {
      MRI *mri_tmp = MRIchangeType(mri_target, MRI_FLOAT, 0, 1, 1) ;
      MRIfree(&mri_target); mri_target = mri_tmp ;
    }
  if (erosions > 0)
    {
      int n ;
      for (n = 0 ; n < erosions ; n++)
	{
	  MRIerodeZero(mri_target, mri_target) ;
	  MRIerodeZero(mri_source, mri_source) ;
	}
    }
  if (scale_values > 0)
    {
      MRIscalarMul(mri_source, mri_source, scale_values) ;
      MRIscalarMul(mri_target, mri_target, scale_values) ;
    }
  if (transform && transform->type == MORPH_3D_TYPE)
    TransformRas2Vox(transform, mri_source,NULL) ;
  if (use_aseg == 0)
    {
      if (match_peak_intensity_ratio)
	MRImatchIntensityRatio(mri_source, mri_target, mri_source, .8, 1.2, 
			       100, 125) ;
      else if (match_mean_intensity)
	MRImatchMeanIntensity(mri_source, mri_target, mri_source) ;
      MRIboundingBox(mri_source, 0, &box) ;
      pad = (int)ceil(PADVOX * 
		      MAX(mri_target->xsize,MAX(mri_target->ysize,mri_target->zsize)) / 
		      MIN(mri_source->xsize,MIN(mri_source->ysize,mri_source->zsize))); 
#if 0
      { MRI *mri_tmp ;
	if (pad < 1)
	  pad = 1 ;
	printf("padding source with %d voxels...\n", pad) ;
	mri_tmp = MRIextractRegionAndPad(mri_source, NULL, &box, pad) ;
	if ((Gdiag & DIAG_WRITE) && DIAG_VERBOSE_ON)
	  MRIwrite(mri_tmp, "t.mgz") ;
	MRIfree(&mri_source) ;
	mri_source = mri_tmp ;
      }
#endif
    }
  mri_orig_source = MRIcopy(mri_source, NULL) ;

  mp.max_grad = 0.3*mri_source->xsize ;

  if (transform == NULL)
    transform = TransformAlloc(LINEAR_VOXEL_TO_VOXEL, NULL) ;

  if (transform->type != MORPH_3D_TYPE)  // initializing m3d from a linear transform
    {
      new_transform = 1 ;
      lta = ((LTA *)(transform->xform)) ;
      if (lta->type != LINEAR_VOX_TO_VOX)
	{
	  printf("converting ras xform to voxel xform\n") ;
	  m_L = MRIrasXformToVoxelXform(mri_source, mri_target, lta->xforms[0].m_L, NULL) ;
	  MatrixFree(&lta->xforms[0].m_L) ;
	  lta->type = LINEAR_VOX_TO_VOX ;
	}
      else
	{
	  printf("using voxel xform\n") ;
	  m_L = lta->xforms[0].m_L ;
	}
#if 0
      if (Gsx >= 0)   // update debugging coords
	{
	  VECTOR *v1, *v2 ;

	  v1 = VectorAlloc(4, MATRIX_REAL) ;
	  Gsx -= (box.x-pad) ;
	  Gsy -= (box.y-pad) ;
	  Gsz -= (box.z-pad) ;
	  V3_X(v1) = Gsx ; V3_Y(v1) = Gsy ; V3_Z(v1) = Gsz ;
	  VECTOR_ELT(v1,4) = 1.0 ;
	  v2 = MatrixMultiply(m_L, v1, NULL) ;
      
	  Gsx = nint(V3_X(v2)) ; Gsy = nint(V3_Y(v2)) ; Gsz = nint(V3_Z(v2)) ;
	  MatrixFree(&v2) ; MatrixFree(&v1) ;
	  printf("mapping by transform (%d, %d, %d) --> (%d, %d, %d) for rgb writing\n",
		 Gx, Gy, Gz, Gsx, Gsy, Gsz) ;
	}
#endif
      if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
	write_snapshot(mri_target, mri_source, m_L, &mp, 0, 1, "linear_init");

      lta->xforms[0].m_L = m_L ;
      printf("initializing GCAM with vox->vox matrix:\n") ;
      MatrixPrint(stdout, m_L) ;
      gcam = GCAMcreateFromIntensityImage(mri_source, mri_target, transform) ;
#if 0
      gcam->gca = gcaAllocMax(1, 1, 1, 
			      mri_target->width, mri_target->height, 
			      mri_target->depth,
			      0, 0) ;
#endif
      GCAMinitVolGeom(gcam, mri_source, mri_target) ;
      if (use_aseg)
	{
	  if (ribbon_name)
	    {
	      char fname[STRLEN], path[STRLEN], *str, *hemi ;
	      int  h, s, label ;
	      MRI_SURFACE *mris_white, *mris_pial ;
	      MRI         *mri ;

	      for (s = 0 ; s <= 1 ; s++) // source and target
		{
		  if (s == 0)
		    {
		      str = source_surf ;
		      mri = mri_source ;
		      FileNamePath(mri->fname, path) ;
		      strcat(path, "/../surf") ;
		    }
		  else
		    {
		      mri = mri_target ;
		      FileNamePath(mri->fname, path) ;
		      strcat(path, "/../elastic") ;
		      str = target_surf ;
		    }
		  // sorry - these values come from FreeSurferColorLUT.txt
		  MRIreplaceValueRange(mri, mri, 1000, 1034, Left_Cerebral_Cortex) ;
		  MRIreplaceValueRange(mri, mri, 1100, 1180, Left_Cerebral_Cortex) ;
		  MRIreplaceValueRange(mri, mri, 2000, 2034, Right_Cerebral_Cortex) ;
		  MRIreplaceValueRange(mri, mri, 2100, 2180, Right_Cerebral_Cortex) ;
		  for (h = LEFT_HEMISPHERE ; h <= RIGHT_HEMISPHERE ; h++)  
		    {
		      if (h == LEFT_HEMISPHERE)
			{
			  hemi = "lh" ;
			  label = Left_Cerebral_Cortex ;
			}
		      else
			{
			  label = Right_Cerebral_Cortex ;
			  hemi = "rh" ;
			}
		      sprintf(fname, "%s/%s%s.white", path, hemi, str) ;
		      mris_white = MRISread(fname) ;
		      if (mris_white == NULL)
			ErrorExit(ERROR_NOFILE, "%s: could not read surface %s", Progname, fname) ;
		      MRISsaveVertexPositions(mris_white, WHITE_VERTICES) ;
		      sprintf(fname, "%s/%s%s.pial", path, hemi, str) ;
		      mris_pial = MRISread(fname) ;
		      if (mris_pial == NULL)
			ErrorExit(ERROR_NOFILE, "%s: could not read surface %s", Progname, fname) ;
		      MRISsaveVertexPositions(mris_pial, PIAL_VERTICES) ;
		      if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
			{
			  sprintf(fname, "sb.mgz") ;
			  MRIwrite(mri_source, fname) ; 
			  sprintf(fname, "tb.mgz") ;
			  MRIwrite(mri_target, fname) ;
			}

		      insert_ribbon_into_aseg(mri, mri, mris_white, mris_pial, h) ;
		      if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
			{
			  sprintf(fname, "sa.mgz") ;
			  MRIwrite(mri_source, fname) ; 
			  sprintf(fname, "ta.mgz") ;
			  MRIwrite(mri_target, fname) ;
			}
		      MRISfree(&mris_white) ; MRISfree(&mris_pial) ;
		    }
		}
	      if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
		{
		  sprintf(fname, "s.mgz") ;
		  MRIwrite(mri_source, fname) ; 
		  sprintf(fname, "t.mgz") ;
		  MRIwrite(mri_target, fname) ;
		}
	    }
	  GCAMinitLabels(gcam, mri_target) ;
	  GCAMsetVariances(gcam, 1.0) ;
	  mp.mri_dist_map = create_distance_transforms(mri_source, mri_target, NULL, 40.0, gcam) ;
	}
    }
  else  /* use a previously create morph and integrate it some more */
    {
      printf("using previously create gcam...\n") ;
      gcam = (GCA_MORPH *)(transform->xform) ;
      GCAMrasToVox(gcam, mri_source) ;
      if (use_aseg)
	{
	  GCAMinitLabels(gcam, mri_target) ;
	  GCAMsetVariances(gcam, 1.0) ;
	  mp.mri_dist_map = create_distance_transforms(mri_source, mri_target, NULL, 40.0, gcam) ;
	}
      else
	GCAMaddIntensitiesFromImage(gcam, mri_target) ;
    }
  if (gcam->width != mri_source->width ||
      gcam->height != mri_source->height ||
      gcam->depth != mri_source->depth)
    ErrorExit(ERROR_BADPARM, "%s: warning gcam (%d, %d, %d), doesn't match source vol (%d, %d, %d)",
	      Progname, gcam->width, gcam->height, gcam->depth,
	      mri_source->width, mri_source->height, mri_source->depth) ;
	
  mp.mri_diag = mri_source ;
  mp.diag_morph_from_atlas = 0 ;
  mp.diag_write_snapshots = 1 ;
  mp.diag_sample_type = use_aseg ? SAMPLE_NEAREST : SAMPLE_TRILINEAR ;
  mp.diag_volume = use_aseg ? GCAM_LABEL : GCAM_MEANS ;

  if (renormalize)
    GCAMnormalizeIntensities(gcam, mri_target) ;
  if (mp.write_iterations != 0)
    {
      char fname[STRLEN] ;
      MRI  *mri_gca ;
		
      if (getenv("DONT_COMPRESS"))
        sprintf(fname, "%s_target.mgh", mp.base_name) ;
      else
        sprintf(fname, "%s_target.mgz", mp.base_name) ;
      if (mp.diag_morph_from_atlas == 0)
      {
        printf("writing target volume to %s...\n", fname) ;
        MRIwrite(mri_target, fname) ;
        sprintf(fname, "%s_target", mp.base_name) ;
        MRIwriteImageViews(mri_target, fname, IMAGE_SIZE) ;
      }
      else
      {
        if (use_aseg)
          mri_gca = GCAMwriteMRI(gcam, NULL, GCAM_LABEL) ;
        else
        {
          mri_gca = MRIclone(mri_source, NULL) ;
          GCAMbuildMostLikelyVolume(gcam, mri_gca) ;
        }
	  printf("writing target volume to %s...\n", fname) ;
	  MRIwrite(mri_gca, fname) ;
	  sprintf(fname, "%s_target", mp.base_name) ;
	  MRIwriteImageViews(mri_gca, fname, IMAGE_SIZE) ;
	  MRIfree(&mri_gca) ;
	}
    }

  if (nozero)
    {
      printf("disabling zero nodes\n") ;
      GCAMignoreZero(gcam, mri_target) ;
    }
  mp.mri = mri_target ;
  if (mp.regrid == True && new_transform == 0)
    GCAMregrid(gcam, mri_target, PAD, &mp, &mri_source) ;

  mp.write_fname = out_fname ;
  GCAMregister(gcam, mri_source, &mp) ; // atlas is target, morph target into register with it
  if (apply_transform)
    {
      MRI *mri_aligned ;
      char   fname[STRLEN] ;
		
      FileNameRemoveExtension(out_fname, fname) ;
      strcat(fname, ".mgz") ;
      mri_aligned = GCAMmorphToAtlas(mp.mri, gcam, NULL, -1, mp.diag_sample_type) ;
      printf("writing transformed output volume to %s...\n", fname) ;
      MRIwrite(mri_aligned, fname) ;
      MRIfree(&mri_aligned) ;
    }
  printf("writing warp vector field to %s\n", out_fname) ;
  GCAMvoxToRas(gcam) ;
  GCAMwrite(gcam, out_fname) ;
  GCAMrasToVox(gcam, mri_source) ;

  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  printf("registration took %d minutes and %d seconds.\n", 
	 minutes, seconds) ;
  exit(0) ;
  return(0) ;
}
Пример #2
0
/*---------------------------------------------------------------*/
int main(int argc, char *argv[]) {
  int nargs, n, err;
  char tmpstr[2000], *signstr=NULL,*SUBJECTS_DIR, fname[2000];
  //char *OutDir = NULL;
  RFS *rfs;
  int nSmoothsPrev, nSmoothsDelta;
  MRI *z, *zabs=NULL, *sig=NULL, *p=NULL;
  int FreeMask = 0;
  int nthSign, nthFWHM, nthThresh;
  double sigmax, zmax, threshadj, csize, csizeavg, searchspace,avgvtxarea;
  int csizen;
  int nClusters, cmax,rmax,smax;
  SURFCLUSTERSUM *SurfClustList;
  struct timeb  mytimer;
  LABEL *clabel;
  FILE *fp, *fpLog=NULL;

  nargs = handle_version_option (argc, argv, vcid, "$Name: stable5 $");
  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);
  dump_options(stdout);

  if(LogFile){
    fpLog = fopen(LogFile,"w");
    if(fpLog == NULL){
      printf("ERROR: opening %s\n",LogFile);
      exit(1);
    }
    dump_options(fpLog);
  } 

  if(SynthSeed < 0) SynthSeed = PDFtodSeed();
  srand48(SynthSeed);

  SUBJECTS_DIR = getenv("SUBJECTS_DIR");

  // Create output directory
  printf("Creating %s\n",OutTop);
  err = fio_mkdirp(OutTop,0777);
  if(err) exit(1);
  for(nthFWHM=0; nthFWHM < nFWHMList; nthFWHM++){
    for(nthThresh = 0; nthThresh < nThreshList; nthThresh++){
      for(nthSign = 0; nthSign < nSignList; nthSign++){
	if(SignList[nthSign] ==  0) signstr = "abs"; 
	if(SignList[nthSign] == +1) signstr = "pos"; 
	if(SignList[nthSign] == -1) signstr = "neg"; 
	sprintf(tmpstr,"%s/fwhm%02d/%s/th%02d",
		OutTop,(int)round(FWHMList[nthFWHM]),
		signstr,(int)round(10*ThreshList[nthThresh]));
	sprintf(fname,"%s/%s.csd",tmpstr,csdbase);
	if(fio_FileExistsReadable(fname)){
	  printf("ERROR: output file %s exists\n",fname);
	  if(fpLog) fprintf(fpLog,"ERROR: output file %s exists\n",fname);
          exit(1);
	}
	err = fio_mkdirp(tmpstr,0777);
	if(err) exit(1);
      }
    }
  }

  // Load the target surface
  sprintf(tmpstr,"%s/%s/surf/%s.%s",SUBJECTS_DIR,subject,hemi,surfname);
  printf("Loading %s\n",tmpstr);
  surf = MRISread(tmpstr);
  if(!surf) return(1);

  // Handle masking
  if(LabelFile){
    printf("Loading label file %s\n",LabelFile);
    sprintf(tmpstr,"%s/%s/label/%s.%s.label",
	    SUBJECTS_DIR,subject,hemi,LabelFile);
    if(!fio_FileExistsReadable(tmpstr)){
      printf(" Cannot find label file %s\n",tmpstr);
      sprintf(tmpstr,"%s",LabelFile);
      printf(" Trying label file %s\n",tmpstr);
      if(!fio_FileExistsReadable(tmpstr)){
	printf("  ERROR: cannot read or find label file %s\n",LabelFile);
	exit(1);
      }
    }
    printf("Loading %s\n",tmpstr);
    clabel = LabelRead(NULL, tmpstr);
    mask = MRISlabel2Mask(surf, clabel, NULL);
    FreeMask = 1;
  }
  if(MaskFile){
    printf("Loading %s\n",MaskFile);
    mask = MRIread(MaskFile);
    if(mask == NULL) exit(1);
  }
  if(mask && SaveMask){
    sprintf(tmpstr,"%s/mask.mgh",OutTop);
    printf("Saving mask to %s\n",tmpstr);
    err = MRIwrite(mask,tmpstr);
    if(err) exit(1);
  }

  // Compute search space
  searchspace = 0;
  nmask = 0;
  for(n=0; n < surf->nvertices; n++){
    if(mask && MRIgetVoxVal(mask,n,0,0,0) < 0.5) continue;
    searchspace += surf->vertices[n].area;
    nmask++;
  }
  printf("Found %d voxels in mask\n",nmask);
  if(surf->group_avg_surface_area > 0)
    searchspace *= (surf->group_avg_surface_area/surf->total_area);
  printf("search space %g mm2\n",searchspace);
  avgvtxarea = searchspace/nmask;
  printf("average vertex area %g mm2\n",avgvtxarea);

  // Determine how many iterations are needed for each FWHM
  nSmoothsList = (int *) calloc(sizeof(int),nFWHMList);
  for(nthFWHM=0; nthFWHM < nFWHMList; nthFWHM++){
    nSmoothsList[nthFWHM] = MRISfwhm2niters(FWHMList[nthFWHM], surf);
    printf("%2d %5.1f  %4d\n",nthFWHM,FWHMList[nthFWHM],nSmoothsList[nthFWHM]);
    if(fpLog) fprintf(fpLog,"%2d %5.1f  %4d\n",nthFWHM,FWHMList[nthFWHM],nSmoothsList[nthFWHM]);
  }
  printf("\n");

  // Allocate the CSDs
  for(nthFWHM=0; nthFWHM < nFWHMList; nthFWHM++){
    for(nthThresh = 0; nthThresh < nThreshList; nthThresh++){
      for(nthSign = 0; nthSign < nSignList; nthSign++){
	csd = CSDalloc();
	sprintf(csd->simtype,"%s","null-z");
	sprintf(csd->anattype,"%s","surface");
	sprintf(csd->subject,"%s",subject);
	sprintf(csd->hemi,"%s",hemi);
	sprintf(csd->contrast,"%s","NA");
	csd->seed = SynthSeed;
	csd->nreps = nRepetitions;
	csd->thresh = ThreshList[nthThresh];
	csd->threshsign = SignList[nthSign];
	csd->nullfwhm = FWHMList[nthFWHM];
	csd->varfwhm = -1;
	csd->searchspace = searchspace;
	CSDallocData(csd);
	csdList[nthFWHM][nthThresh][nthSign] = csd;
      }
    }
  }

  // Alloc the z map
  z = MRIallocSequence(surf->nvertices, 1,1, MRI_FLOAT, 1);

  // Set up the random field specification
  rfs = RFspecInit(SynthSeed,NULL);
  rfs->name = strcpyalloc("gaussian");
  rfs->params[0] = 0;
  rfs->params[1] = 1;

  printf("Thresholds (%d): ",nThreshList);
  for(n=0; n < nThreshList; n++) printf("%5.2f ",ThreshList[n]);
  printf("\n");
  printf("Signs (%d): ",nSignList);
  for(n=0; n < nSignList; n++)  printf("%2d ",SignList[n]);
  printf("\n");
  printf("FWHM (%d): ",nFWHMList);
  for(n=0; n < nFWHMList; n++) printf("%5.2f ",FWHMList[n]);
  printf("\n");

  // Start the simulation loop
  printf("\n\nStarting Simulation over %d Repetitions\n",nRepetitions);
  if(fpLog) fprintf(fpLog,"\n\nStarting Simulation over %d Repetitions\n",nRepetitions);
  TimerStart(&mytimer) ;
  for(nthRep = 0; nthRep < nRepetitions; nthRep++){
    msecTime = TimerStop(&mytimer) ;
    printf("%5d %7.1f ",nthRep,(msecTime/1000.0)/60);
    if(fpLog) {
      fprintf(fpLog,"%5d %7.1f ",nthRep,(msecTime/1000.0)/60);
      fflush(fpLog);
    }
    // Synthesize an unsmoothed z map
    RFsynth(z,rfs,mask); 
    nSmoothsPrev = 0;
    
    // Loop through FWHMs
    for(nthFWHM=0; nthFWHM < nFWHMList; nthFWHM++){
      printf("%d ",nthFWHM);
      if(fpLog) {
	fprintf(fpLog,"%d ",nthFWHM);
	fflush(fpLog);
      }
      nSmoothsDelta = nSmoothsList[nthFWHM] - nSmoothsPrev;
      nSmoothsPrev = nSmoothsList[nthFWHM];
      // Incrementally smooth z
      MRISsmoothMRI(surf, z, nSmoothsDelta, mask, z); // smooth z
      // Rescale
      RFrescale(z,rfs,mask,z);
      // Slightly tortured way to get the right p-values because
      //   RFstat2P() computes one-sided, but I handle sidedness
      //   during thresholding.
      // First, use zabs to get a two-sided pval bet 0 and 0.5
      zabs = MRIabs(z,zabs);
      p = RFstat2P(zabs,rfs,mask,0,p);
      // Next, mult pvals by 2 to get two-sided bet 0 and 1
      MRIscalarMul(p,p,2.0);
      sig = MRIlog10(p,NULL,sig,1); // sig = -log10(p)
      for(nthThresh = 0; nthThresh < nThreshList; nthThresh++){
	for(nthSign = 0; nthSign < nSignList; nthSign++){
	  csd = csdList[nthFWHM][nthThresh][nthSign];

	  // If test is not ABS then apply the sign
	  if(csd->threshsign != 0) MRIsetSign(sig,z,0);
	  // Get the max stats
	  sigmax = MRIframeMax(sig,0,mask,csd->threshsign,
			       &cmax,&rmax,&smax);
	  zmax = MRIgetVoxVal(z,cmax,rmax,smax,0);
	  if(csd->threshsign == 0){
	    zmax = fabs(zmax);
	    sigmax = fabs(sigmax);
	  }
	  // Mask
	  if(mask) MRImask(sig,mask,sig,0.0,0.0);

	  // Surface clustering
	  MRIScopyMRI(surf, sig, 0, "val");
	  if(csd->threshsign == 0) threshadj = csd->thresh;
	  else threshadj = csd->thresh - log10(2.0); // one-sided test
	  SurfClustList = sclustMapSurfClusters(surf,threshadj,-1,csd->threshsign,
						0,&nClusters,NULL);
	  // Actual area of cluster with max area
	  csize  = sclustMaxClusterArea(SurfClustList, nClusters);
	  // Number of vertices of cluster with max number of vertices. 
	  // Note: this may be a different cluster from above!
	  csizen = sclustMaxClusterCount(SurfClustList, nClusters);
	  // Area of this cluster based on average vertex area. This just scales
	  // the number of vertices.
	  csizeavg = csizen * avgvtxarea;
	  if(UseAvgVtxArea) csize = csizeavg;
	  // Store results
	  csd->nClusters[nthRep] = nClusters;
	  csd->MaxClusterSize[nthRep] = csize;
	  csd->MaxSig[nthRep] = sigmax;
	  csd->MaxStat[nthRep] = zmax;
	} // Sign
      } // Thresh
    } // FWHM
    printf("\n");
    if(fpLog) fprintf(fpLog,"\n");
    if(SaveEachIter || fio_FileExistsReadable(SaveFile)) SaveOutput();
    if(fio_FileExistsReadable(StopFile)) {
      printf("Found stop file %s\n",StopFile);
      goto finish;
    }
  } // Simulation Repetition

 finish:

  SaveOutput();

  msecTime = TimerStop(&mytimer) ;
  printf("Total Sim Time %g min (%g per rep)\n",
	 msecTime/(1000*60.0),(msecTime/(1000*60.0))/nthRep);
  if(fpLog) fprintf(fpLog,"Total Sim Time %g min (%g per rep)\n",
		    msecTime/(1000*60.0),(msecTime/(1000*60.0))/nthRep);

  if(DoneFile){
    fp = fopen(DoneFile,"w");
    fprintf(fp,"%g\n",msecTime/(1000*60.0));
    fclose(fp);
  }
  printf("mri_mcsim done\n");
  if(fpLog){
    fprintf(fpLog,"mri_mcsim done\n");
    fclose(fpLog);
  }
  exit(0);
}
Пример #3
0
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 = &lta->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(&lt->dst, &vgtmp);
          copyVolGeom(&lt->src, &lt->dst);
          copyVolGeom(&vgtmp, &lt->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) ;
}
Пример #4
0
static MRI *
MRIremoveWMOutliersAndRetainMedialSurface(MRI *mri_src,
                                          MRI *mri_src_ctrl,
                                          MRI *mri_dst_ctrl,
                                          int intensity_below)
{
  MRI       *mri_bin, *mri_dist, *mri_dist_sup, *mri_outliers = NULL ;
  float     max, thresh, val;
  HISTOGRAM *histo, *hsmooth ;
  int       wm_peak, x, y, z, nremoved = 0, whalf = 5 ;

  if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
  {
    MRIwrite(mri_src_ctrl, "sc.mgz") ;
  }

  mri_bin = MRIbinarize(mri_dst_ctrl, NULL, 1, 0, 1) ;
  mri_dist = MRIdistanceTransform(mri_bin, NULL, 1, -1,
                                  DTRANS_MODE_SIGNED, NULL);
  MRIscalarMul(mri_dist, mri_dist, -1) ;
  mri_dist_sup = MRInonMaxSuppress(mri_dist, NULL, 0, 1) ;
  mri_dst_ctrl = MRIbinarize(mri_dist_sup, mri_dst_ctrl, 1, 0, 1) ;
  histo = MRIhistogramLabel(mri_src, mri_src_ctrl, 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") ;
  }
  wm_peak = HISTOfindHighestPeakInRegion(hsmooth, 1, hsmooth->nbins-1) ;
  wm_peak = hsmooth->bins[wm_peak] ;
  thresh = wm_peak-intensity_below ;

  HISTOfree(&histo) ;
  HISTOfree(&hsmooth) ;
  if (Gdiag & DIAG_WRITE)
  {
    mri_outliers = MRIclone(mri_dst_ctrl, 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 (x == Gx && y == Gy && z == Gz)
        {
          DiagBreak() ;
        }
        if (nint(MRIgetVoxVal(mri_dst_ctrl, x, y, z, 0)) == 0)
        {
          continue ;
        }
        max = MRImaxInLabelInRegion(mri_src, mri_dst_ctrl, 1, x, y, z, whalf);
        val = MRIgetVoxVal(mri_src, x, y, z, 0) ;
        if (val+intensity_below < max && val < thresh)
        {
          MRIsetVoxVal(mri_dst_ctrl, x, y, z, 0, 0) ;
          if (mri_outliers)
          {
            MRIsetVoxVal(mri_outliers, x, y, z, 0, 128) ;
          }
          nremoved++ ;
        }
      }
    }
  }

  printf( "%d control points removed\n", nremoved) ;
  if (mri_outliers)
  {
    printf( "writing out.mgz outlier volume\n") ;
    MRIwrite(mri_outliers, "out.mgz") ;
    MRIfree(&mri_outliers) ;
  }
  if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
  {
    MRIwrite(mri_dst_ctrl, "dc.mgz") ;
  }
  MRIfree(&mri_bin) ;
  MRIfree(&mri_dist);
  MRIfree(&mri_dist_sup);
  return(mri_dst_ctrl);
}
Пример #5
0
/*---------------------------------------------------------------*/
int main(int argc, char **argv)
{
  int c,r,s,f;
  double val,rval;
  FILE *fp;
  MRI *mritmp;

  Progname = argv[0] ;
  argc --;
  argv++;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  /* assign default geometry */
  cdircos[0] = 1.0;
  cdircos[1] = 0.0;
  cdircos[2] = 0.0;
  rdircos[0] = 0.0;
  rdircos[1] = 1.0;
  rdircos[2] = 0.0;
  sdircos[0] = 0.0;
  sdircos[1] = 0.0;
  sdircos[2] = 1.0;
  res[0] = 1.0;
  res[1] = 1.0;
  res[2] = 1.0;
  cras[0] = 0.0;
  cras[1] = 0.0;
  cras[2] = 0.0;
  res[3] = 2.0; /* TR */

  if (argc == 0) usage_exit();

  parse_commandline(argc, argv);
  check_options();
  dump_options(stdout);

  if(tempid != NULL) {
    printf("INFO: reading template header\n");
    if(! DoCurv) mritemp = MRIreadHeader(tempid,tempfmtid);
    else         mritemp = MRIread(tempid);
    if (mritemp == NULL) {
      printf("ERROR: reading %s header\n",tempid);
      exit(1);
    }
    if(NewVoxSizeSpeced){
      dim[0] = round(mritemp->width*mritemp->xsize/res[0]);
      dim[1] = round(mritemp->height*mritemp->ysize/res[1]);
      dim[2] = round(mritemp->depth*mritemp->zsize/res[2]);
      dim[3] = mritemp->nframes;
      res[3] = mritemp->tr;
      dimSpeced = 1;
    }
    if(dimSpeced){
      mritmp = MRIallocSequence(dim[0],dim[1],dim[2],MRI_FLOAT,dim[3]);
      MRIcopyHeader(mritemp,mritmp);
      MRIfree(&mritemp);
      mritemp = mritmp;
    }
    if(resSpeced){
      mritemp->xsize = res[0];
      mritemp->ysize = res[1];
      mritemp->zsize = res[2];
      mritemp->tr    = res[3];
    }

    dim[0] = mritemp->width;
    dim[1] = mritemp->height;
    dim[2] = mritemp->depth;
    if (nframes > 0) dim[3] = nframes;
    else             dim[3] = mritemp->nframes;
    mritemp->nframes = dim[3];
  }

  if(mritemp) {
    if(SpikeTP >= mritemp->nframes){
      printf("ERROR: SpikeTP = %d >= mritemp->nframes = %d\n",
             SpikeTP,mritemp->nframes);
      exit(1);
    }
  }

  printf("Synthesizing\n");
  srand48(seed);
  if (strcmp(pdfname,"gaussian")==0)
    mri = MRIrandn(dim[0], dim[1], dim[2], dim[3], gausmean, gausstd, NULL);
  else if (strcmp(pdfname,"uniform")==0)
    mri = MRIdrand48(dim[0], dim[1], dim[2], dim[3], 0, 1, NULL);
  else if (strcmp(pdfname,"const")==0)
    mri = MRIconst(dim[0], dim[1], dim[2], dim[3], ValueA, NULL);
  else if (strcmp(pdfname,"sphere")==0) {
    if(voxradius < 0)
      voxradius =
        sqrt( pow(dim[0]/2.0,2)+pow(dim[1]/2.0,2)+pow(dim[2]/2.0,2) )/2.0;
    printf("voxradius = %lf\n",voxradius);
    mri = MRIsphereMask(dim[0], dim[1], dim[2], dim[3],
                        dim[0]/2.0, dim[1]/2.0, dim[2]/2.0,
                        voxradius, ValueA, NULL);
  } else if (strcmp(pdfname,"delta")==0) {
    mri = MRIconst(dim[0], dim[1], dim[2], dim[3], delta_off_value, NULL);
    if (delta_crsf_speced == 0) {
      delta_crsf[0] = dim[0]/2;
      delta_crsf[1] = dim[1]/2;
      delta_crsf[2] = dim[2]/2;
      delta_crsf[3] = dim[3]/2;
    }
    printf("delta set to %g at %d %d %d %d\n",delta_value,delta_crsf[0],
           delta_crsf[1],delta_crsf[2],delta_crsf[3]);
    MRIFseq_vox(mri,
                delta_crsf[0],
                delta_crsf[1],
                delta_crsf[2],
                delta_crsf[3]) = delta_value;
  } else if (strcmp(pdfname,"chi2")==0) {
    rfs = RFspecInit(seed,NULL);
    rfs->name = strcpyalloc("chi2");
    rfs->params[0] = dendof;
    mri = MRIconst(dim[0], dim[1], dim[2], dim[3], 0, NULL);
    printf("Synthesizing chi2 with dof=%d\n",dendof);
    RFsynth(mri,rfs,NULL);
  } else if (strcmp(pdfname,"z")==0) {
    printf("Synthesizing z \n");
    rfs = RFspecInit(seed,NULL);
    rfs->name = strcpyalloc("gaussian");
    rfs->params[0] = 0; // mean
    rfs->params[1] = 1; // std
    mri = MRIconst(dim[0], dim[1], dim[2], dim[3], 0, NULL);
    RFsynth(mri,rfs,NULL);
  } else if (strcmp(pdfname,"t")==0) {
    printf("Synthesizing t with dof=%d\n",dendof);
    rfs = RFspecInit(seed,NULL);
    rfs->name = strcpyalloc("t");
    rfs->params[0] = dendof;
    mri = MRIconst(dim[0], dim[1], dim[2], dim[3], 0, NULL);
    RFsynth(mri,rfs,NULL);
  } else if (strcmp(pdfname,"tr")==0) {
    printf("Synthesizing t with dof=%d as ratio of z/sqrt(chi2)\n",dendof);
    rfs = RFspecInit(seed,NULL);
    // numerator
    rfs->name = strcpyalloc("gaussian");
    rfs->params[0] = 0; // mean
    rfs->params[1] = 1; // std
    mri = MRIconst(dim[0], dim[1], dim[2], dim[3], 0, NULL);
    RFsynth(mri,rfs,NULL);
    // denominator
    rfs->name = strcpyalloc("chi2");
    rfs->params[0] = dendof;
    mri2 = MRIconst(dim[0], dim[1], dim[2], dim[3], 0, NULL);
    RFsynth(mri2,rfs,NULL);
    fMRIsqrt(mri2,mri2); // sqrt of chi2
    mri = MRIdivide(mri,mri2,mri);
    MRIscalarMul(mri, mri, sqrt(dendof)) ;
    MRIfree(&mri2);
  } else if (strcmp(pdfname,"F")==0) {
    printf("Synthesizing F with num=%d den=%d\n",numdof,dendof);
    rfs = RFspecInit(seed,NULL);
    rfs->name = strcpyalloc("F");
    rfs->params[0] = numdof;
    rfs->params[1] = dendof;
    mri = MRIconst(dim[0], dim[1], dim[2], dim[3], 0, NULL);
    RFsynth(mri,rfs,NULL);
  } else if (strcmp(pdfname,"Fr")==0) {
    printf("Synthesizing F with num=%d den=%d as ratio of two chi2\n",
           numdof,dendof);
    rfs = RFspecInit(seed,NULL);
    rfs->name = strcpyalloc("chi2");
    // numerator
    rfs->params[0] = numdof;
    mri = MRIconst(dim[0], dim[1], dim[2], dim[3], 0, NULL);
    RFsynth(mri,rfs,NULL);
    // denominator
    rfs->params[0] = dendof;
    mri2 = MRIconst(dim[0], dim[1], dim[2], dim[3], 0, NULL);
    RFsynth(mri2,rfs,NULL);
    mri = MRIdivide(mri,mri2,mri);
    MRIscalarMul(mri, mri, (double)dendof/numdof) ;
    MRIfree(&mri2);
  } else if (strcmp(pdfname,"voxcrs")==0) {
    // three frames. 1st=col, 2nd=row, 3rd=slice
    printf("Filling with vox CRS\n");
    mri = MRIconst(dim[0], dim[1], dim[2], 3, 0, NULL);
    for(c=0; c < mri->width; c ++){
      for(r=0; r < mri->height; r ++){
        for(s=0; s < mri->depth; s ++){
          MRIsetVoxVal(mri,c,r,s,0,c);
          MRIsetVoxVal(mri,c,r,s,1,r);
          MRIsetVoxVal(mri,c,r,s,2,s);
        }
      }
    }
  } else if (strcmp(pdfname,"boundingbox")==0) {
    printf("Setting bounding box \n");
    if(mritemp == NULL)
      mritemp = MRIconst(dim[0], dim[1], dim[2], dim[3], 0, NULL);
    mri = MRIsetBoundingBox(mritemp,&boundingbox,ValueA,ValueB);
    if(!mri) exit(1);
  } 
  else if (strcmp(pdfname,"checker")==0) {
    printf("Checker \n");
    mri=MRIchecker(mritemp,NULL);
    if(!mri) exit(1);
  } 
  else if (strcmp(pdfname,"sliceno")==0) {
    printf("SliceNo \n");
    if(mritemp == NULL){
      printf("ERROR: need --temp with sliceno\n");
      exit(1);
    }
    mri=MRIsliceNo(mritemp,NULL);
    if(!mri) exit(1);
  } 
  else if (strcmp(pdfname,"indexno")==0) {
    printf("IndexNo \n");
    if(mritemp == NULL){
      printf("ERROR: need --temp with indexno\n");
      exit(1);
    }
    mri=MRIindexNo(mritemp,NULL);
    if(!mri) exit(1);
  } 
  else if (strcmp(pdfname,"crs")==0) {
    printf("CRS \n");
    if(mritemp == NULL){
      printf("ERROR: need --temp with crs\n");
      exit(1);
    }
    mri=MRIcrs(mritemp,NULL);
    if(!mri) exit(1);
  } 
  else {
    printf("ERROR: pdf %s unrecognized, must be gaussian, uniform,\n"
	   "const, delta, checker\n", pdfname);
    exit(1);
  }
  if (tempid != NULL) {
    MRIcopyHeader(mritemp,mri);
    mri->type = MRI_FLOAT;
    // Override
    if(nframes > 0) mri->nframes = nframes;
    if(TR > 0) mri->tr = TR;
  } else {
    if(mri == NULL) {
      usage_exit();
    }
    mri->xsize = res[0];
    mri->ysize = res[1];
    mri->zsize = res[2];
    mri->tr    = res[3];
    mri->x_r = cdircos[0];
    mri->x_a = cdircos[1];
    mri->x_s = cdircos[2];
    mri->y_r = rdircos[0];
    mri->y_a = rdircos[1];
    mri->y_s = rdircos[2];
    mri->z_r = sdircos[0];
    mri->z_a = sdircos[1];
    mri->z_s = sdircos[2];
    if(!usep0){
      mri->c_r = cras[0];
      mri->c_a = cras[1];
      mri->c_s = cras[2];
    } 
    else MRIp0ToCRAS(mri, p0[0], p0[1], p0[2]);
  }

  if (gstd > 0) {
    if(!UseFFT){
      printf("Smoothing\n");
      MRIgaussianSmooth(mri, gstd, gmnnorm, mri); /* gmnnorm = 1 = normalize */
    }
    else {
      printf("Smoothing with FFT \n");
      mri2 = MRIcopy(mri,NULL);
      mri = MRI_fft_gaussian(mri2, mri,
                             gstd, gmnnorm); /* gmnnorm = 1 = normalize */
    }
    if (rescale) {
      printf("Rescaling\n");
      if (strcmp(pdfname,"z")==0)     RFrescale(mri,rfs,NULL,mri);
      if (strcmp(pdfname,"chi2")==0)  RFrescale(mri,rfs,NULL,mri);
      if (strcmp(pdfname,"t")==0)     RFrescale(mri,rfs,NULL,mri);
      if (strcmp(pdfname,"tr")==0)    RFrescale(mri,rfs,NULL,mri);
      if (strcmp(pdfname,"F")==0)     RFrescale(mri,rfs,NULL,mri);
      if (strcmp(pdfname,"Fr")==0)    RFrescale(mri,rfs,NULL,mri);
    }
  }

  if(DoHSC){
    // This multiplies each frame by a random number
    // between HSCMin HSCMax to simulate heteroscedastisity
    printf("Applying HSC %lf %lf\n",HSCMin,HSCMax);
    for(f=0; f < mri->nframes; f++){
      rval = (HSCMax-HSCMin)*drand48() + HSCMin;
      if(debug) printf("%3d %lf\n",f,rval);
      for(c=0; c < mri->width; c ++){
	for(r=0; r < mri->height; r ++){
	  for(s=0; s < mri->depth; s ++){
	    val = MRIgetVoxVal(mri,c,r,s,f);
	    MRIsetVoxVal(mri,c,r,s,f,rval*val);
	  }
        }
      }
    }
  }

  if(AddOffset) {
    printf("Adding offset\n");
    offset = MRIread(tempid);
    if(offset == NULL) exit(1);
    if(OffsetFrame == -1) OffsetFrame = nint(offset->nframes/2);
    printf("Offset frame %d\n",OffsetFrame);
    mritmp = fMRIframe(offset, OffsetFrame, NULL);
    if(mritmp == NULL) exit(1);
    MRIfree(&offset);
    offset = mritmp;
    fMRIaddOffset(mri, offset, NULL, mri);
  }

  if(SpikeTP > 0){
    printf("Spiking time point %d\n",SpikeTP);
    for(c=0; c < mri->width; c ++){
      for(r=0; r < mri->height; r ++){
        for(s=0; s < mri->depth; s ++){
          MRIsetVoxVal(mri,c,r,s,SpikeTP,1e9);
        }
      }
    }
  }

  if(DoAbs){
    printf("Computing absolute value\n");
    MRIabs(mri,mri);
  }

  if(!NoOutput){
    printf("Saving\n");
    if(!DoCurv)  MRIwriteAnyFormat(mri,volid,volfmt,-1,NULL);
    else {
      printf("Saving in curv format\n");
      MRIScopyMRI(surf, mri, 0, "curv");
      MRISwriteCurvature(surf,volid);
    }
  }

  if(sum2file){
    val = MRIsum2All(mri);
    fp = fopen(sum2file,"w");
    if(fp == NULL){
      printf("ERROR: opening %s\n",sum2file);
      exit(1);
    }
    printf("sum2all: %20.10lf\n",val);
    printf("vrf: %20.10lf\n",1/val);
    fprintf(fp,"%20.10lf\n",val);
  }

  return(0);
}
Пример #6
0
int
main(int argc, char *argv[])
{
  char      **av, *out_fname ;
  int       ac, nargs ;
  GCA_MORPH *gcam ;
  int       msec, minutes, seconds ;
  struct timeb start ;
  MRI       *mri, *mri_jacobian, *mri_area, *mri_orig_area ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mri_jacobian.c,v 1.11 2011/12/10 22:47:57 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 < 4)
    usage_exit(1) ;

  out_fname = argv[argc-1] ;
  gcam = GCAMread(argv[1]) ;
  
  if (gcam == NULL)
    ErrorExit(ERROR_BADPARM, "%s: could not read input morph %s\n", Progname,argv[1]);
  if (Gx >= 0 && atlas == 0)
    find_debug_node(gcam, Gx, Gy, Gz) ;

  mri = MRIread(argv[2]) ;
  if (gcam == NULL)
    ErrorExit(ERROR_BADPARM, "%s: could not read template volume %s\n", Progname,argv[2]);

  GCAMrasToVox(gcam, mri) ;
  if (init || tm3dfile)
    init_gcam_areas(gcam) ;
  if (atlas)
    {
      mri_area = GCAMwriteMRI(gcam, NULL, GCAM_AREA);
      mri_orig_area = GCAMwriteMRI(gcam, NULL, GCAM_ORIG_AREA);
    }
  else
    {
      mri_area = GCAMmorphFieldFromAtlas(gcam, mri, GCAM_AREA, 0, 0);
      mri_orig_area = GCAMmorphFieldFromAtlas(gcam, mri, GCAM_ORIG_AREA, 0, 0);
    }

  if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
    {
      MRIwrite(mri_orig_area, "o.mgz") ;
      MRIwrite(mri_area, "a.mgz") ;
    }
  if (Gx > 0)
    printf("area = %2.3f, orig = %2.3f\n", 
	   MRIgetVoxVal(mri_area, Gx, Gy, Gz,0),MRIgetVoxVal(mri_orig_area,Gx,Gy,Gz,0)) ;
  if (lta)
    {
      double det ;
      if  (lta->type == LINEAR_RAS_TO_RAS)
	LTArasToVoxelXform(lta, mri, mri) ;
      det = MatrixDeterminant(lta->xforms[0].m_L) ;
      printf("correcting transform with det=%2.3f\n", det) ;
      MRIscalarMul(mri_orig_area, mri_orig_area, 1/det) ;
    }
  
  if (! FZERO(sigma))
    {
      MRI *mri_kernel, *mri_smooth ;
      mri_kernel = MRIgaussian1d(sigma, 100) ;
      mri_smooth = MRIconvolveGaussian(mri_area, NULL, mri_kernel) ;
      MRIfree(&mri_area) ; mri_area = mri_smooth ;
      mri_smooth = MRIconvolveGaussian(mri_orig_area, NULL, mri_kernel) ;
      MRIfree(&mri_orig_area) ; mri_orig_area = mri_smooth ;

      MRIfree(&mri_kernel) ; 
    }
  if (Gx > 0)
    printf("after smoothing area = %2.3f, orig = %2.3f\n", 
	   MRIgetVoxVal(mri_area, Gx, Gy, Gz,0),MRIgetVoxVal(mri_orig_area,Gx,Gy,Gz,0)) ;
  mri_jacobian = MRIdivide(mri_area, mri_orig_area, NULL) ;
  if (Gx > 0)
    printf("jacobian = %2.3f\n", MRIgetVoxVal(mri_jacobian, Gx, Gy, Gz,0)) ;
  if (atlas)
    mask_invalid(gcam, mri_jacobian) ;
  if (use_log)
    {
      MRIlog10(mri_jacobian, NULL, mri_jacobian, 0) ;
      if (zero_mean)
	MRIzeroMean(mri_jacobian, mri_jacobian) ;
      if (Gx > 0)
	printf("log jacobian = %2.3f\n", MRIgetVoxVal(mri_jacobian, Gx, Gy, Gz,0)) ;
    }
  fprintf(stderr, "writing to %s...\n", out_fname) ;
  MRIwrite(mri_jacobian, out_fname) ;
  MRIfree(&mri_jacobian) ;
  if (write_areas)
    {
      char fname[STRLEN] ;
      sprintf(fname, "%s_area.mgz", out_fname) ;
      printf("writing area to %s\n", fname) ;
      MRIwrite(mri_area, fname) ;
      sprintf(fname, "%s_orig_area.mgz", out_fname) ;
      printf("writing orig area to %s\n", fname) ;
      MRIwrite(mri_orig_area, fname) ;
    }
  if (atlas && DIAG_WRITE && DIAG_VERBOSE_ON)
    {
      char fname[STRLEN] ;
      FileNameRemoveExtension(out_fname, out_fname) ;
      mri_area = GCAMwriteMRI(gcam, mri_area, GCAM_MEANS);
      sprintf(fname, "%s_means.mgz", out_fname) ;
      printf("writing means to %s\n", fname) ;
      MRIwrite(mri_area, fname) ;
      sprintf(fname, "%s_labels.mgz", out_fname) ;
      mri_area = GCAMwriteMRI(gcam, mri_area, GCAM_LABEL);
      printf("writing labels to %s\n", fname) ;
      MRIwrite(mri_area, fname) ;
    }
  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ; minutes = seconds / 60 ;seconds = seconds % 60 ;
  fprintf(stderr, "jacobian calculation took %d minutes and %d seconds.\n", minutes, seconds) ;
  exit(0) ;
  return(0) ;
}
Пример #7
0
int
main(int argc, char *argv[]) {
  char   **av ;
  int    ac, nargs ;
  char   *training_file_name, source_fname[100], target_fname[100], *cp,
  line[250], *output_file_name ;
  FILE   *fp ;
  int    fno, nfiles ;
  MRI    *mri_src, *mri_target, *mri_wm, *mri_priors = NULL ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mri_build_priors.c,v 1.8 2011/03/02 00:04:13 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 < 2)
    training_file_name = "train.dat" ;
  else
    training_file_name = argv[1] ;

  if (argc < 3)
    output_file_name = "priors.mnc" ;
  else
    output_file_name = argv[2] ;

  fp = fopen(training_file_name, "r") ;
  if (!fp)
    ErrorExit(ERROR_NO_FILE, "%s: could not open file %s",
              Progname, training_file_name) ;

  nfiles = 0 ;
  while ((cp = fgetl(line, 299, fp)) != NULL)
    nfiles++ ;
  fprintf(stderr, "processing %d files\n", nfiles) ;
  rewind(fp) ;

  fno = 0 ;
  while ((cp = fgetl(line, 299, fp)) != NULL) {
    sscanf(cp, "%s %s", source_fname, target_fname) ;
    fprintf(stderr, "file[%d]: %s --> %s\n", fno, source_fname, target_fname);
    mri_src = MRIread(source_fname) ;
    if (!mri_src) {
      fprintf(stderr, "could not read MR image %s\n", source_fname) ;
      continue ;
    }

    mri_wm = MRIread(target_fname) ;
    if (!mri_wm) {
      fprintf(stderr, "could not read MR image %s\n", target_fname) ;
      MRIfree(&mri_src) ;
      continue ;
    }

    mri_target = MRICbuildTargetImage(mri_src, NULL, mri_wm, 0, 0) ;
    MRIfree(&mri_src) ;
    MRIfree(&mri_wm) ;
    fno++ ;

    mri_priors = MRICupdatePriors(mri_target, mri_priors, PRIOR_SCALE) ;
    MRIfree(&mri_target) ;
  }
#if 0
  if (fno > 0)
    MRIscalarMul(mri_priors, mri_priors, 1.0f / (float)fno) ;
#else
  MRInormalizePriors(mri_priors) ;
#endif
  MRIwrite(mri_priors, output_file_name) ;
  fclose(fp) ;
  exit(0) ;
  return(0) ;
}