コード例 #1
0
static RANDOM_FOREST *
train_rforest(MRI *mri_inputs[MAX_SUBJECTS][MAX_TIMEPOINTS], MRI *mri_segs[MAX_SUBJECTS][MAX_TIMEPOINTS], TRANSFORM *transforms[MAX_SUBJECTS][MAX_TIMEPOINTS], 
	      int nsubjects, GCA *gca, RFA_PARMS *parms, float wm_thresh,
	      int wmsa_whalf, int ntp) 
{
  RANDOM_FOREST  *rf ;
  int            nfeatures, x, y, z, ntraining, n, tvoxel_size, width, height, depth, xt, yt, zt ;
  double         xatlas, yatlas, zatlas ;
  MRI            *mri_in, *mri_seg, *mri_training_voxels, *mri_wmsa_possible ;
  TRANSFORM      *transform ;
  double         **training_data ;
  int            *training_classes, i, label, tlabel, nwmsa, nfuture, nnot, correct, label_time1, label_time2;

  nwmsa = nnot = nfuture = 0 ;

/*
  features are:
  t1 intensity (3 vols)
  3 priors
  # of unknown voxels in the nbhd
  # of neighboring wmsa voxels at t1
*/
  nfeatures = parms->wsize*parms->wsize*parms->wsize*parms->nvols + 5 ; 

  rf = RFalloc(parms->ntrees, nfeatures, NCLASSES, parms->max_depth, single_classifier_names, max_steps) ;
  if (rf == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not allocate random forest", Progname) ;
  rf->min_step_size = 1 ; 

  tvoxel_size=1 ;
  width = (int)ceil((float)mri_segs[0][0]->width/tvoxel_size) ;
  height = (int)ceil((float)mri_segs[0][0]->height/tvoxel_size) ;
  depth = (int)ceil((float)mri_segs[0][0]->depth/tvoxel_size) ;
  mri_wmsa_possible = MRIalloc(width, height, depth, MRI_UCHAR) ;
  GCAcopyDCToMRI(gca, mri_wmsa_possible) ;
  mri_in = mri_inputs[0][0] ;
  mri_training_voxels = MRIallocSequence(mri_in->width,mri_in->height, mri_in->depth,MRI_UCHAR,nsubjects) ;

#if 1
  // update time 1 segmentation based on labels at time1 and time2
  for (n = 0 ; n < nsubjects ; n++)
  {
    mri_seg = mri_segs[n][0] ;
    for (x = 0 ; x < mri_in->width ; x++)
      for (y = 0 ; y < mri_in->height ; y++)
	for (z = 0 ; z < mri_in->depth ; z++)
	{
	  label_time1 = MRIgetVoxVal(mri_segs[n][0], x, y, z, 0) ;
	  label_time2 = MRIgetVoxVal(mri_segs[n][1], x, y, z, 0) ;
	  if (IS_WMSA(label_time1))
	    MRIsetVoxVal(mri_segs[n][0], x, y, z, 0, label_time1) ;
	  else if (IS_WMSA(label_time2))
	    MRIsetVoxVal(mri_segs[n][0], x, y, z, 0, future_WMSA) ;
	}
  }
#endif

  // build map of spatial locations that WMSAs can possibly occur in
  for (n = 0 ; n < nsubjects ; n++)
  {
    mri_in = mri_inputs[n][1] ; transform = transforms[n][1] ; 
    for (x = 0 ; x < mri_in->width ; x++)
      for (y = 0 ; y < mri_in->height ; y++)
	for (z = 0 ; z < mri_in->depth ; z++)
	  if (is_possible_wmsa(gca, mri_in, transform, x, y, z, 0))
	  {
	    TransformSourceVoxelToAtlas(transform, mri_in, x, y, z, &xatlas, &yatlas, &zatlas) ;
	    xt = nint(xatlas/tvoxel_size) ;
	    yt = nint(yatlas/tvoxel_size) ;
	    zt = nint(zatlas/tvoxel_size) ;
	    if (xt == Gx && yt == Gy && zt == Gz)
	      DiagBreak() ;
	    MRIsetVoxVal(mri_wmsa_possible, xt, yt, zt, 0, 1) ;
	  }
  }
  for ( ; wmsa_whalf > 0 ; wmsa_whalf--)
    MRIdilate(mri_wmsa_possible, mri_wmsa_possible) ;

  // now build map of all voxels in training set
  for (nnot = nwmsa = nfuture = ntraining = n = 0 ; n < nsubjects ; n++)
  {
    mri_in = mri_inputs[n][0] ; mri_seg = mri_segs[n][0] ; transform = transforms[n][0] ;
    for (x = 0 ; x < mri_in->width ; x++)
      for (y = 0 ; y <  mri_in->height; y++)
	for (z = 0 ; z <  mri_in->depth; z++)
	{
	  label = MRIgetVoxVal(mri_seg, x, y, z, 0) ;
	  
	  TransformSourceVoxelToAtlas(transform, mri_in, x, y, z, &xatlas, &yatlas, &zatlas) ;
	  xt = nint(xatlas/tvoxel_size) ;
	  yt = nint(yatlas/tvoxel_size) ;
	  zt = nint(zatlas/tvoxel_size) ;
	  if (xt == Gx && yt == Gy && zt == Gz)
	    DiagBreak() ;
	  if ((IS_WMSA(label) == 0) &&
	      MRIgetVoxVal(mri_wmsa_possible,xt,yt, zt,0) == 0)
	    continue ;
	  if (NOT_TRAINING_LABEL(label))
	    continue ;
	  ntraining++ ;
	  
	  if (IS_FUTURE_WMSA(label))
	  {
	    label = FUTURE_WMSA;
	    nfuture++ ;
	  }
	  else if (IS_WMSA(label))
	  {
	    label = WMSA ;
	    nwmsa++ ;
	  }
	  else
	  {
	    label = NOT_WMSA ;
	    nnot++ ;
	  }
          // set label to one more than it will be for training so that 0 means this is not a training voxel
	  MRIsetVoxVal(mri_training_voxels, x, y, z, n, label+1) ;
	}
  }

  correct = MRIcountNonzero(mri_training_voxels) ;
  if (correct != ntraining)
    DiagBreak() ;
  printf("total training set size = %2.1fM\n", (float)ntraining/(1024.0f*1024.0f)) ;
  printf("initial training set found with %dK FUTURE WMSA labels, %dK WMSA labels, and %dK non (ratio=%2.1f:%2.1f)\n",
	 nfuture/1000, nwmsa/1000, nnot/1000, (float)nnot/(float)nfuture, (float)nnot/(float)nwmsa) ;

  MRIfree(&mri_wmsa_possible) ;

  if (max_wm_wmsa_ratio*(nfuture+nwmsa) < nnot)   // too many wm labels w.r.t. # of wmsas - remove some wm
  {
    int removed, total_to_remove =  nnot - (max_wm_wmsa_ratio*(nfuture+nwmsa)) ;
    double premove ;

    premove = (double)total_to_remove  / (double)nnot ;
    printf("removing %dK WM indices to reduce training set imbalance (p < %f)\n", total_to_remove/1000, premove) ;

    for (removed = n = 0 ; n < nsubjects ; n++)
      for (x = 0 ; x < mri_in->width ; x++)
	for (y = 0 ; y <  mri_in->height; y++)
	  for (z = 0 ; z <  mri_in->depth; z++)
	  {
	    label = MRIgetVoxVal(mri_training_voxels, x, y, z, n) ;
	    if (label == 1)   // a WM voxel
	    {
	      if (randomNumber(0,1) < premove)
	      {
		removed++ ;
		MRIsetVoxVal(mri_training_voxels, x, y, z, n, 0) ;  // remove it from training set
	      }
	    }
	  }
    ntraining -= removed ;
    printf("%d WM voxels removed, new training set size = %dM (ratio = %2.1f)\n",
	   removed, ntraining/(1024*1024), (double)(nnot-removed)/(double)(nwmsa+nfuture)) ;
  }

  correct = MRIcountNonzero(mri_training_voxels) ;
  if (correct != ntraining)
    DiagBreak() ;
//  if (Gx >= 0)
  {
    int whalf = (parms->wsize-1)/2 ;
    char buf[STRLEN] ;
    rf->feature_names = (char **)calloc(rf->nfeatures, sizeof(char *)) ;
    for (i = 0, x = -whalf ; x <= whalf ; x++)
      for (y = -whalf ; y <= whalf ; y++)
	for (z = -whalf ; z <= whalf ; z++)
	  for (n = 0 ; n < mri_in->nframes ; n++, i++)
	  {
	    switch (n)
	    {
	    default:
	    case 0: sprintf(buf, "T1(%d, %d, %d)", x, y, z) ; break ;
	    case 1: sprintf(buf, "T2(%d, %d, %d)", x, y, z) ; 
	      break ;
	    case 2: sprintf(buf, "FLAIR(%d, %d, %d)", x, y, z) ; 
	      if (x == 0 && y == 0 && z == 0)
		Gdiag_no = i ;
	      break ;
	    }
	    rf->feature_names[i] = (char *)calloc(strlen(buf)+1, sizeof(char)) ;
	    strcpy(rf->feature_names[i], buf) ;
	  }
    printf("FLAIR(0,0,0) = %dth feature\n", Gdiag_no) ;

    sprintf(buf, "CSF voxels in nbhd") ;
    rf->feature_names[i] = (char *)calloc(strlen(buf)+1, sizeof(char)) ;
    strcpy(rf->feature_names[i], buf) ;
    i++ ; sprintf(buf, "gm prior") ;
    rf->feature_names[i] = (char *)calloc(strlen(buf)+1, sizeof(char)) ;
    strcpy(rf->feature_names[i], buf) ;
    i++ ; sprintf(buf, "wm prior") ;
    rf->feature_names[i] = (char *)calloc(strlen(buf)+1, sizeof(char)) ;
    strcpy(rf->feature_names[i], buf) ;
    i++ ; sprintf(buf, "csf prior") ;
    rf->feature_names[i] = (char *)calloc(strlen(buf)+1, sizeof(char)) ;
    strcpy(rf->feature_names[i], buf) ;
    i++ ; sprintf(buf, "WMSA in nbhd") ;
    rf->feature_names[i] = (char *)calloc(strlen(buf)+1, sizeof(char)) ;
    strcpy(rf->feature_names[i], buf) ;

    if (Gdiag & DIAG_WRITE)
    {
      printf("writing training voxels to tv.mgz\n") ;
      MRIwrite(mri_training_voxels, "tv.mgz") ;
    }
  }

  // now build training features and classes
  training_classes = (int *)calloc(ntraining, sizeof(training_classes[0])) ;
  if (training_classes == NULL)
    ErrorExit(ERROR_NOFILE, "train_rforest: could not allocate %d-length training buffers",ntraining);
  training_data = (double **)calloc(ntraining, sizeof(training_data[0])) ;
  if (training_classes == NULL)
    ErrorExit(ERROR_NOFILE, "train_rforest: could not allocate %d-length training buffers",ntraining);
  for (i = n = 0 ; n < nsubjects ; n++)
  {
    mri_in = mri_inputs[n][0] ; mri_seg = mri_segs[n][0] ; transform = transforms[n][0] ;
    for (x = 0 ; x < mri_in->width ; x++)
      for (y = 0 ; y <  mri_in->height; y++)
	for (z = 0 ; z <  mri_in->depth; z++)
	{
	  if ((int)MRIgetVoxVal(mri_training_voxels, x, y, z, n) == 0)
	    continue ;
	  label = MRIgetVoxVal(mri_seg, x, y, z, 0) ;
	  TransformSourceVoxelToAtlas(transform, mri_in, x, y, z, &xatlas, &yatlas, &zatlas) ;
	  xt = nint(xatlas/tvoxel_size) ; yt = nint(yatlas/tvoxel_size) ; zt = nint(zatlas/tvoxel_size) ;
	  if (IS_FUTURE_WMSA(label))
	    tlabel = FUTURE_WMSA ;
	  else if (IS_WMSA(label))
	    tlabel = WMSA ;
	  else
	    tlabel= NOT_WMSA ;
	    
	  training_classes[i] =  tlabel ;
	  training_data[i] = (double *)calloc(nfeatures, sizeof(double)) ;
	  if (training_data[i] == NULL)
	    ErrorExit(ERROR_NOMEMORY, "train_rforest: could not allocate %d-len feature vector #%d",
		      nfeatures, i) ;
	  training_classes[i] = training_classes[i] ;
//	  extract_feature(mri_in, parms->wsize, x, y, z, training_data[i], xatlas, yatlas, zatlas) ;
	  extract_long_features(mri_in, mri_seg, transform, gca, parms->wsize, x, y, z, training_data[i]) ;
	  if (training_data[i][Gdiag_no] < 80 && training_classes[i] == 1)
	    DiagBreak() ;
	  i++ ;
	}
    MRIfree(&mri_in) ; MRIfree(&mri_seg) ; TransformFree(&transform) ;
  }

  if (i < ntraining)
  {
    printf("warning!!!! i (%d) < ntraining (%d)! Setting ntraining=i\n", i, ntraining) ;
    ntraining = i ;
  }
  printf("training random forest with %dK FUTURE WMSA labels, %dK WMSA labels, and %dK non (ratio=%2.1f:%2.1f)\n",
	 nfuture/1000, nwmsa/1000, nnot/1000, (float)nnot/(float)nfuture, (float)nnot/(float)nwmsa) ;
  RFtrain(rf, parms->feature_fraction, parms->training_fraction, training_classes, training_data, ntraining);
  correct = RFcomputeOutOfBagCorrect(rf, training_classes, training_data,ntraining);
  printf("out of bag accuracy: %d of %d = %2.2f%%\n", correct, ntraining,
	 100.0*correct/ntraining) ;
  if (log_file_name)
  {
      struct flock fl;
      int    fd;
      char   line[MAX_LINE_LEN] ;

      printf("writing results to train.log file %s\n", log_file_name) ;
      fd = open(log_file_name, O_WRONLY|O_APPEND|O_CREAT, S_IRWXU|S_IRWXG);
      if (fd < 0)
	ErrorExit(ERROR_NOFILE, "%s: could not open test log file %s", 
		  Progname, log_file_name);
      
      fcntl(fd, F_SETLKW, &fl);  /* F_GETLK, F_SETLK, F_SETLKW */
      sprintf(line, "%f %d %d %f\n", 
	      rf->training_fraction,
	      rf->max_depth,
	      rf->ntrees,
	       100.0*correct/ntraining) ;
      write(fd, line, (strlen(line))*sizeof(char)) ;
      fl.l_type   = F_UNLCK;  /* tell it to unlock the region */
      fcntl(fd, F_SETLK, &fl); /* set the region to unlocked */
      close(fd) ;
  }

  for (i = 0 ; i < ntraining ; i++)  // allow for augmenting with other wmsa examples
    free(training_data[i]) ;
  free(training_data) ;
  free(training_classes) ;
  MRIfree(&mri_training_voxels) ;
  return(rf) ;
}
コード例 #2
0
ファイル: main.c プロジェクト: ewong718/freesurfer
int main ( int argc, char** argv ) {

  MRI* mri = NULL;
  int zX = 256;
  int zY = 256;
  int zZ = 256;
  int err = NO_ERROR;
  int nX = 0;
  int nY = 0;
  int nZ = 0;
  float sizeX = 1.0;
  float sizeY = 1.0;
  float sizeZ = 1.0;
  int setMethod = SET_METHOD_XYZ;
  int setValue = 0;
  char fnVol[256] = "new_volume.mgz";
  int i;
  char* arg = NULL;

  for ( i = 1; i < argc; i++ ) {

    arg = argv[i];

    if ( argv[i] && *argv[i] != '-' ) {
      printf( "ERROR: Unrecognized argument %s\n", argv[i] );
      PrintUsage( NULL );
      exit( 1 );
    }

    while ( arg[0] == '-' )
      arg = arg+1;

    if ( strlen(arg) <= 0 )
      continue;

    if ( strcmp(arg,"h") == 0 ||
         strcmp(arg,"help") == 0 ) {
      PrintUsage( NULL );
      exit( 0 );
    }

    if ( strcmp(arg,"f") == 0 ||
         strcmp(arg,"filename") == 0 ) {
      if ( i+1 >= argc ) {
        PrintUsage( "No argument to filename option." );
        exit( 1 );
      }
      strcpy( fnVol, argv[i+1] );
      i++;
    }

    if ( strcmp(arg,"x") == 0 ||
         strcmp(arg,"width") == 0 ) {
      if ( i+1 >= argc ) {
        PrintUsage( "No argument to width option." );
        exit( 1 );
      }
      zX = atoi(argv[i+1]);
      i++;
    }
    if ( strcmp(arg,"y") == 0 ||
         strcmp(arg,"height") == 0 ) {
      if ( i+1 >= argc ) {
        PrintUsage( "No argument to height option." );
        exit( 1 );
      }
      zY = atoi(argv[i+1]);
      i++;
    }
    if ( strcmp(arg,"z") == 0 ||
         strcmp(arg,"depth") == 0 ) {
      if ( i+1 >= argc ) {
        PrintUsage( "No argument to depth option." );
        exit( 1 );
      }
      zZ = atoi(argv[i+1]);
      i ++;
    }

    if ( strcmp(arg,"sizex") == 0 ) {
      if ( i+1 >= argc ) {
        PrintUsage( "No argument to sizex option." );
        exit( 1 );
      }
      sizeX = atof(argv[i+1]);
      i++;
    }
    if ( strcmp(arg,"sizey") == 0 ) {
      if ( i+1 >= argc ) {
        PrintUsage( "No argument to sizey option." );
        exit( 1 );
      }
      sizeY = atof(argv[i+1]);
      i++;
    }
    if ( strcmp(arg,"sizez") == 0 ) {
      if ( i+1 >= argc ) {
        PrintUsage( "No argument to sizez optoin." );
        exit( 1 );
      }
      sizeZ = atof(argv[i+1]);
      i++;
    }

    if ( strcmp(arg,"set-method") == 0 ) {
      if ( i+1 >= argc ) {
        PrintUsage( "No argument to set-method option." );
        exit( 1 );
      }
      if ( strcmp( argv[i+1], "xyz" ) == 0 ) {
        setMethod = SET_METHOD_XYZ;
        i++;
        printf( "set_method is xyz\n" );
      } else if ( strcmp( argv[i+1], "random" ) == 0 ) {
        setMethod = SET_METHOD_RANDOM;
        i++;
        printf( "set_method is random\n" );
      } else if ( strncmp( argv[i+1], "constant", 9 ) == 0 ) {
        if ( i+2 >= argc ) {
          PrintUsage( "No value argument to constant method option." );
          exit( 1 );
        }
        setMethod = SET_METHOD_CONSTANT;
        setValue = atoi( argv[i+2] );
        i+=2;
        printf( "set_method is constant, %d\n", setValue );
      } else {
        PrintUsage( "Unrecognized argument to set-method option" );
        exit( 1 );
      }
    }
  }

  printf( "Creating volume %s\n"
          "  width = %d height = %d depth = %d\n"
          "  xsize = %f ysize = %f zsize = %f\n"
          "  set method = %s, constant = %d\n",
          fnVol, zX, zY, zZ,
          sizeX, sizeY, sizeZ,
          sSetMethods[setMethod], setValue );

  mri = MRIalloc( zX, zY, zZ, MRI_UCHAR );
  if ( NULL == mri ) {
    fprintf( stderr, "Couldn't create volume.\n" );
    return 1;
  }
  MRIsetResolution( mri, sizeX, sizeY, sizeZ );

  switch ( setMethod ) {
  case SET_METHOD_CONSTANT:
    MRIvalueFill( mri, 0 );
    break;
  case SET_METHOD_RANDOM:
    for ( nZ = 0; nZ < zZ; nZ++ ) {
      for ( nY = 0; nY < zY; nY++ ) {
        for ( nX = 0; nX < zX; nX++ ) {
          MRIvox( mri, nX, nY, nZ ) = (int)((random()/(float)RAND_MAX)*255.0);
        }
      }
    }
    break;
  case SET_METHOD_XYZ:
    for ( nZ = 0; nZ < zZ; nZ++ ) {
      for ( nY = 0; nY < zY; nY++ ) {
        for ( nX = 0; nX < zX; nX++ ) {
          MRIvox( mri, nX, nY, nZ ) =
            (((float)nZ/(float)zZ)*255.0/3.0) +
            (((float)nY/(float)zY)*255.0/3.0) +
            (((float)nX/(float)zX)*255.0/3.0) ;
        }
      }
    }
    break;
  default:
    for ( nZ = (zZ/2) - (zZ/4); nZ < (zZ/2) + (zZ/4); nZ++ ) {
      for ( nY = (zY/2) - (zY/4); nY < (zY/2) + (zY/4); nY++ ) {
        for ( nX = (zX/2) - (zX/4); nX < (zX/2) + (zX/4); nX++ ) {
          MRIvox( mri, nX, nY, nZ ) = 255;
        }
      }
    }
  }

  err = MRIwrite( mri, fnVol );
  if ( NO_ERROR != err ) {
    fprintf( stderr, "Couldn't write volume.\n" );
    return 1;
  }

  MRIfree( &mri );

  return 0;
}
コード例 #3
0
int
main(int argc, char *argv[]) {
  char         **av ;
  int          ac, nargs ;
  MRI          *mri_orig, *mri_norm, *mri_bias ;
  int          msec, minutes, seconds ;
  struct timeb start ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option
          (argc, argv,
           "$Id: mri_apply_bias.c,v 1.5 2011/03/02 00:04:13 nicks Exp $",
           "$Name: stable5 $");
  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) ;

  mri_orig = MRIread(argv[1]) ;
  if (mri_orig == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not read %s",Progname, argv[1]) ;
  mri_bias = MRIread(argv[2]) ;
  if (mri_bias == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not read %s",Progname, argv[2]) ;

  if (xform_fname)
  {
    TRANSFORM    *transform ;
    MRI          *mri ;

    transform = TransformRead(xform_fname) ;
    if (transform == NULL)
      ErrorExit(ERROR_NOFILE, "%s: could not load transform %s", Progname, xform_fname) ;
    mri = MRIcloneDifferentType(mri_orig, MRI_FLOAT) ;
    TransformApplyInverse(transform, mri_bias, mri) ;
    MRIfree(&mri_bias) ; mri_bias = mri ;
    
  }
  mri_norm = apply_bias(mri_orig, NULL, mri_bias);

  fprintf(stderr, "writing to %s...\n", argv[3]) ;
  MRIwrite(mri_norm, argv[3]) ;
  MRIfree(&mri_norm) ;
  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  fprintf(stderr, "bias correction took %d minutes and %d seconds.\n",
          minutes, seconds) ;
  exit(0) ;
  return(0) ;
}
コード例 #4
0
ファイル: mris_diff.c プロジェクト: guo2004131/freesurfer
/*---------------------------------------------------------------*/
int main(int argc, char *argv[]) {
  int nargs, nthvtx, nnbrs1, nnbrs2, nthnbr, nbrvtxno1, nbrvtxno2;
  int nthface, annot1, annot2;
  VERTEX *vtx1, *vtx2;
  FACE *face1, *face2;
  float diff, maxdiff;

  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);

  SUBJECTS_DIR = getenv("SUBJECTS_DIR");
  if (SUBJECTS_DIR == NULL) {
    printf("INFO: SUBJECTS_DIR not defined in environment\n");
    //exit(1);
  }
  if (SUBJECTS_DIR1 == NULL) SUBJECTS_DIR1 = SUBJECTS_DIR;
  if (SUBJECTS_DIR2 == NULL) SUBJECTS_DIR2 = SUBJECTS_DIR;

  if (surf1path == NULL && surfname == NULL) surfname = "orig";

  if (surf1path == NULL) {
    sprintf(tmpstr,"%s/%s/surf/%s.%s",SUBJECTS_DIR1,subject1,hemi,surfname);
    surf1path = strcpyalloc(tmpstr);
  }
  if (surf2path == NULL) {
    sprintf(tmpstr,"%s/%s/surf/%s.%s",SUBJECTS_DIR2,subject2,hemi,surfname);
    surf2path = strcpyalloc(tmpstr);
  }
  dump_options(stdout);

  //read-in each surface.  notice that the random number generator is
  //seeded with the same value prior to each read.  this is because in
  //the routine MRIScomputeNormals, if it finds a zero-length vertex
  //normal, is adds a random value to the x,y,z and recomputes the normal.
  //so if comparing identical surfaces, the seed must be the same so that
  //any zero-length vertex normals appear the same.
  setRandomSeed(seed) ;
  surf1 = MRISread(surf1path);
  if (surf1 == NULL) {
    printf("ERROR: could not read %s\n",surf1path);
    exit(1);
  }
  setRandomSeed(seed) ;
  surf2 = MRISread(surf2path);
  if (surf2 == NULL) {
    printf("ERROR: could not read %s\n",surf2path);
    exit(1);
  }
  printf("Number of vertices %d %d\n",surf1->nvertices,surf2->nvertices);
  printf("Number of faces    %d %d\n",surf1->nfaces,surf2->nfaces);

  //Number of Vertices ----------------------------------------
  if (surf1->nvertices != surf2->nvertices) {
    printf("Surfaces differ in number of vertices %d %d\n",
           surf1->nvertices,surf2->nvertices);
    exit(101);
  }
  //Number of Faces ------------------------------------------
  if (surf1->nfaces != surf2->nfaces) {
    printf("Surfaces differ in number of faces %d %d\n",
           surf1->nfaces,surf2->nfaces);
    exit(101);
  }

  //surf1->faces[10000].area = 100;
  //surf1->vertices[10000].x = 100;

  if (ComputeNormalDist) {
    double dist, dx, dy, dz, dot ;
    MRI    *mri_dist ;

    mri_dist = MRIalloc(surf1->nvertices,1,1,MRI_FLOAT) ;
    MRIScomputeMetricProperties(surf1) ;
    MRIScomputeMetricProperties(surf2) ;
    for (nthvtx=0; nthvtx < surf1->nvertices; nthvtx++) {
      vtx1 = &(surf1->vertices[nthvtx]);
      vtx2 = &(surf2->vertices[nthvtx]);
      dx = vtx2->x-vtx1->x ;
      dy = vtx2->y-vtx1->y ;
      dz = vtx2->z-vtx1->z ;
      dist = sqrt(dx*dx + dy*dy + dz*dz) ;
      dot = dx*vtx1->nx + dy*vtx1->ny + dz*vtx1->nz ;
      dist = dist * dot / fabs(dot) ;
      MRIsetVoxVal(mri_dist, nthvtx, 0, 0, 0, dist) ;
    }
    MRIwrite(mri_dist, out_fname) ;
    MRIfree(&mri_dist) ;
    exit(0);
  }

  maxdiff=0;

  //------------------------------------------------------------
  if (CheckSurf) {
    printf("Comparing surfaces\n");

    // Loop over vertices ---------------------------------------
    error_count=0;
    for (nthvtx=0; nthvtx < surf1->nvertices; nthvtx++) {
      vtx1 = &(surf1->vertices[nthvtx]);
      vtx2 = &(surf2->vertices[nthvtx]);
      if (vtx1->ripflag != vtx2->ripflag) {
        printf("Vertex %d differs in ripflag %c %c\n",
               nthvtx,vtx1->ripflag,vtx2->ripflag);
        if (++error_count>=MAX_NUM_ERRORS) break;
      }
      if (CheckXYZ) {
        diff=fabs(vtx1->x - vtx2->x);
        if (diff>maxdiff) maxdiff=diff;
        if (diff>thresh) {
          printf("Vertex %d differs in x %g %g\t(%g)\n",
                 nthvtx,vtx1->x,vtx2->x,diff);
          if (++error_count>=MAX_NUM_ERRORS) break;
        }
        diff=fabs(vtx1->y - vtx2->y);
        if (diff>maxdiff) maxdiff=diff;
        if (diff>thresh) {
          printf("Vertex %d differs in y %g %g\t(%g)\n",
                 nthvtx,vtx1->y,vtx2->y,diff);
          if (++error_count>=MAX_NUM_ERRORS) break;
        }
        diff=fabs(vtx1->z - vtx2->z);
        if (diff>maxdiff) maxdiff=diff;
        if (diff>thresh) {
          printf("Vertex %d differs in z %g %g\t(%g)\n",
                 nthvtx,vtx1->z,vtx2->z,diff);
          if (++error_count>=MAX_NUM_ERRORS) break;
        }
      }
      if (CheckNXYZ) {
        diff=fabs(vtx1->nx - vtx2->nx);
        if (diff>maxdiff) maxdiff=diff;
        if (diff>thresh) {
          printf("Vertex %d differs in nx %g %g\t(%g)\n",
                 nthvtx,vtx1->nx,vtx2->nx,diff);
          if (++error_count>=MAX_NUM_ERRORS) break;
        }
        diff=fabs(vtx1->ny - vtx2->ny);
        if (diff>maxdiff) maxdiff=diff;
        if (diff>thresh) {
          printf("Vertex %d differs in ny %g %g\t(%g)\n",
                 nthvtx,vtx1->ny,vtx2->ny,diff);
          if (++error_count>=MAX_NUM_ERRORS) break;
        }
        diff=fabs(vtx1->nz - vtx2->nz);
        if (diff>maxdiff) maxdiff=diff;
        if (diff>thresh) {
          printf("Vertex %d differs in nz %g %g\t(%g)\n",
                 nthvtx,vtx1->nz,vtx2->nz,diff);
          if (++error_count>=MAX_NUM_ERRORS) break;
        }
      }
      nnbrs1 = surf1->vertices[nthvtx].vnum;
      nnbrs2 = surf2->vertices[nthvtx].vnum;
      if (nnbrs1 != nnbrs2) {
        printf("Vertex %d has a different number of neighbors %d %d\n",
               nthvtx,nnbrs1,nnbrs2);
        if (++error_count>=MAX_NUM_ERRORS) break;
      }
      for (nthnbr=0; nthnbr < nnbrs1; nthnbr++) {
        nbrvtxno1 = surf1->vertices[nthvtx].v[nthnbr];
        nbrvtxno2 = surf2->vertices[nthvtx].v[nthnbr];
        if (nbrvtxno1 != nbrvtxno2) {
          printf("Vertex %d differs in the identity of the "
                 "%dth neighbor %d %d\n",nthvtx,nthnbr,nbrvtxno1,nbrvtxno2);
          if (++error_count>=MAX_NUM_ERRORS) break;
        }
      }
      if (error_count>=MAX_NUM_ERRORS) break;
    }// loop over vertices
    if (maxdiff>0) printf("maxdiff=%g\n",maxdiff);
    if (error_count > 0) {
      printf("Exiting after finding %d errors\n",error_count);
      if (error_count>=MAX_NUM_ERRORS) {
        printf("Exceeded MAX_NUM_ERRORS loop guard\n");
      }
      exit(103);
    }

    // Loop over faces ----------------------------------------
    error_count=0;
    for (nthface=0; nthface < surf1->nfaces; nthface++) {
      face1 = &(surf1->faces[nthface]);
      face2 = &(surf2->faces[nthface]);
      if (CheckNXYZ) {
        diff=fabs(face1->nx - face2->nx);
        if (diff>maxdiff) maxdiff=diff;
        if (diff>thresh) {
          printf("Face %d differs in nx %g %g\t(%g)\n",
                 nthface,face1->nx,face2->nx,diff);
          if (++error_count>=MAX_NUM_ERRORS) break;
        }
        diff=fabs(face1->ny - face2->ny);
        if (diff>maxdiff) maxdiff=diff;
        if (diff>thresh) {
          printf("Face %d differs in ny %g %g\t(%g)\n",
                 nthface,face1->ny,face2->ny,diff);
          if (++error_count>=MAX_NUM_ERRORS) break;
        }
        diff=fabs(face1->nz - face2->nz);
        if (diff>maxdiff) maxdiff=diff;
        if (diff>thresh) {
          printf("Face %d differs in nz %g %g\t(%g)\n",
                 nthface,face1->nz,face2->nz,diff);
          if (++error_count>=MAX_NUM_ERRORS) break;
        }
      }
      diff=fabs(face1->area - face2->area);
      if (diff>maxdiff) maxdiff=diff;
      if (diff>thresh) {
        printf("Face %d differs in area %g %g\t(%g)\n",
               nthface,face1->area,face2->area,diff);
        if (++error_count>=MAX_NUM_ERRORS) break;
      }
      if (face1->ripflag != face2->ripflag) {
        printf("Face %d differs in ripflag %c %c\n",
               nthface,face1->ripflag,face2->ripflag);
        if (++error_count>=MAX_NUM_ERRORS) break;
      }
      for (nthvtx = 0; nthvtx < 3; nthvtx++) {
        if (face1->v[nthvtx] != face2->v[nthvtx]) {
          printf("Face %d differs in identity of %dth vertex %d %d\n",
                 nthface,nthvtx,face1->ripflag,face2->ripflag);
          if (++error_count>=MAX_NUM_ERRORS) break;
        }
      } // end loop over nthface vertex
      if (error_count>=MAX_NUM_ERRORS) break;
    } // end loop over faces
    if (maxdiff>0) printf("maxdiff=%g\n",maxdiff);
    if (error_count > 0) {
      printf("Exiting after finding %d errors\n",error_count);
      if (error_count>=MAX_NUM_ERRORS) {
        printf("Exceeded MAX_NUM_ERRORS loop guard\n");
      }
      exit(103);
    }

    printf("Surfaces are the same\n");
    exit(0);
  } // end check surf

  // -----------------------------------------------------------------
  if (CheckCurv) {
    printf("Checking curv file %s\n",curvname);
    sprintf(tmpstr,"%s/%s/surf/%s.%s",SUBJECTS_DIR1,subject1,hemi,curvname);
    printf("Loading curv file %s\n",tmpstr);
    if (MRISreadCurvatureFile(surf1, tmpstr) != 0) {
      printf("ERROR: reading curvature file %s\n",tmpstr);
      exit(1);
    }
    sprintf(tmpstr,"%s/%s/surf/%s.%s",SUBJECTS_DIR2,subject2,hemi,curvname);
    printf("Loading curv file %s\n",tmpstr);
    if (MRISreadCurvatureFile(surf2, tmpstr) != 0) {
      printf("ERROR: reading curvature file %s\n",tmpstr);
      exit(1);
    }
    error_count=0;
    for (nthvtx=0; nthvtx < surf1->nvertices; nthvtx++) {
      vtx1 = &(surf1->vertices[nthvtx]);
      vtx2 = &(surf2->vertices[nthvtx]);
      diff=fabs(vtx1->curv - vtx2->curv);
      if (diff>maxdiff) maxdiff=diff;
      if (diff > thresh) {
        printf("curv files differ at vertex %d %g %g\t(%g)\n",
               nthvtx,vtx1->curv,vtx2->curv,diff);
        if (++error_count>=MAX_NUM_ERRORS) break;
      }
    } // end loop over vertices
    if (maxdiff>0) printf("maxdiff=%g\n",maxdiff);
    if (error_count > 0) {
      printf("Exiting after finding %d errors\n",error_count);
      if (error_count>=MAX_NUM_ERRORS) {
        printf("Exceeded MAX_NUM_ERRORS loop guard\n");
      }
      exit(103);
    }
    printf("Curv files are the same\n");
    exit(0);
  } // end check curv

  // ---------------------------------------------------------
  if (CheckAParc) {
    printf("Checking AParc %s\n",aparcname);
    sprintf(tmpstr,"%s/%s/label/%s.%s.annot",
            SUBJECTS_DIR1,subject1,hemi,aparcname);
    printf("Loading aparc file %s\n",tmpstr);
    fflush(stdout);
    if (MRISreadAnnotation(surf1, tmpstr)) {
      printf("ERROR: MRISreadAnnotation() failed %s\n",tmpstr);
      exit(1);
    }
    if (aparc2name) aparcname = aparc2name;
    sprintf(tmpstr,"%s/%s/label/%s.%s.annot",
            SUBJECTS_DIR2,subject2,hemi,aparcname);
    printf("Loading aparc file %s\n",tmpstr);
    fflush(stdout);
    if (MRISreadAnnotation(surf2, tmpstr)) {
      printf("ERROR: MRISreadAnnotation() failed %s\n",tmpstr);
      exit(1);
    }
    error_count=0;
    for (nthvtx=0; nthvtx < surf1->nvertices; nthvtx++) {
      annot1 = surf1->vertices[nthvtx].annotation;
      annot2 = surf2->vertices[nthvtx].annotation;
      if (annot1 != annot2) {
        printf("aparc files differ at vertex %d: 1:%s 2:%s\n",
               nthvtx,
               CTABgetAnnotationName(surf1->ct,annot1),
               CTABgetAnnotationName(surf2->ct,annot2));
        if (++error_count>=MAX_NUM_ERRORS) break;
      }
    } // end loop over vertices
    if (error_count > 0) {
      printf("Exiting after finding %d errors\n",error_count);
      if (error_count>=MAX_NUM_ERRORS) {
        printf("Exceeded MAX_NUM_ERRORS loop guard\n");
      }
      exit(103);
    }
    printf("\n"
           "AParc files are the same\n"
           "------------------------\n");
    exit(0);
  }

  return 0;
}
コード例 #5
0
ファイル: mri_vol2roi.c プロジェクト: guo2004131/freesurfer
/*---------------------------------------------------------*/
int main(int argc, char **argv) {
  int n,err, f, nhits, r,c,s;
  float ipr, bpr, intensity;
  float *framepower=NULL, val;
  LTA *lta;
  int nargs;
  //int endian,roitype;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mri_vol2roi.c,v 1.32 2011/03/02 00:04:25 nicks Exp $", "$Name: stable5 $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

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

  if (argc == 0) usage_exit();

  parse_commandline(argc, argv);
  check_options();

  printf("--------------------------------------------------------\n");
  getcwd(tmpstr,2000);
  printf("%s\n",tmpstr);
  printf("%s\n",Progname);
  for (n=0;n<argc;n++) printf(" %s",argv[n]);
  printf("\n");
  printf("version %s\n",vcid);
  printf("--------------------------------------------------------\n");

  dump_options(stdout);

  /* --------- load in the (possibly 4-D) source volume --------------*/
  printf("Loading volume %s ...",srcvolid);
  mSrcVol = MRIread(srcvolid);
  if(mSrcVol == NULL) exit(1);
  printf("done\n");

  /* Dsrc: read the source registration file */
  if (srcregfile != NULL) {
    err = regio_read_register(srcregfile, &srcsubject, &ipr, &bpr,
                              &intensity, &Dsrc, &float2int_src);
    if (err) exit(1);
    printf("srcreg Dsrc -------------\n");
    MatrixPrint(stdout,Dsrc);
    printf("----------------------------------\n");
  } else Dsrc = NULL;

  /* Wsrc: Get the source warping Transform */
  Wsrc = NULL;
  /* Fsrc: Get the source FOV registration matrix */
  Fsrc = NULL;
  /* Qsrc: Compute the quantization matrix for src volume */
  Qsrc = FOVQuantMatrix(mSrcVol->width,  mSrcVol->height,  mSrcVol->depth,
                        mSrcVol->xsize,  mSrcVol->ysize,  mSrcVol->zsize);
  printf("ras2vox src (tkreg) Qsrc -------------\n");
  MatrixPrint(stdout,Qsrc);
  printf("----------------------------------\n");

  /* ----------- load in the label ----------------- */
  if (labelfile != NULL) {
    Label = LabelReadFile(labelfile);
    if (Label == NULL) exit(1);
    /* load in the source-to-label registration */
    if (src2lblregfile != NULL) {
      //err = regio_read_xfm(src2lblregfile, &Msrc2lbl);
      //if(err) exit(1);
      lta = LTAread(src2lblregfile);
      if (lta->type == LINEAR_VOX_TO_VOX) {
        printf("INFO: converting LTA to RAS\n");
        LTAvoxelTransformToCoronalRasTransform(lta);
      }
      Msrc2lbl = MatrixCopy(lta->xforms[0].m_L,NULL);
    } else if (labeltal) {
      /* Load the talairach.xfm and make it approp for reg.dat*/
      Msrc2lbl = DevolveXFM(srcsubject,NULL,talxfm);
      if (Msrc2lbl==NULL) exit(1);
    } else Msrc2lbl = NULL;
    if (Msrc2lbl != NULL) {
      printf("-- Source2Label %s ---- \n",src2lblregfile);
      MatrixPrint(stdout,Msrc2lbl);
      printf("-------------------------------\n");
    }
  } else {
    Label = NULL;
    Msrc2lbl = NULL;
  }

  /* -------------- load mask volume stuff -----------------------------*/
  if (mskvolid != NULL) {
    /* load the mask volume (single frame) */
    printf("Reading %s\n",mskvolid);
    mMskVol = MRIread(mskvolid);
    if(mMskVol == NULL) exit(1);
    if(mskframe > 0){
      mritmp = fMRIframe(mMskVol, mskframe, NULL);
      if(mritmp == NULL) exit(1);
      MRIfree(&mMskVol);
      mMskVol = mritmp;
    }

    /* Qmsk: Compute the quantization matrix for msk volume */
    /* crsFOV = Qmsk*xyzFOV */
    Qmsk = FOVQuantMatrix(mMskVol->width, mMskVol->height, mMskVol->depth,
                          mMskVol->xsize, mMskVol->ysize,  mMskVol->zsize);

    /* get the mask2source registration information */
    /* xyzSrc = Mmsk2src * xyzMsk */
    if (msk2srcregfile != NULL) {
      err = regio_read_mincxfm(msk2srcregfile, &Mmsk2src, NULL);
      if (err) exit(1);
    } else Mmsk2src = NULL;

    /* convert from Mask Anatomical to Src FOV */
    if (!msksamesrc) {
      mSrcMskVol = vol2vol_linear(mMskVol, Qmsk, NULL, NULL, Dmsk,
                                  Qsrc, Fsrc, Wsrc, Dsrc,
                                  mSrcVol->height, mSrcVol->width, mSrcVol->depth,
                                  Mmsk2src, INTERP_NEAREST, float2int_msk);
      if (mSrcMskVol == NULL) exit(1);
    } else mSrcMskVol = mMskVol;

    /* binarize the mask volume */
    mri_binarize(mSrcMskVol, mskthresh, msktail, mskinvert,
                 mSrcMskVol, &nmskhits);
  } else {
    mSrcMskVol = NULL;
    nmskhits = 0;
  }
  /*-------------- Done loading mask stuff -------------------------*/

  /* If this is a statistical volume, raise each frame to it's appropriate
     power (eg, stddev needs to be squared)*/
  if (is_sxa_volume(srcvolid)) {
    printf("INFO: Source volume detected as selxavg format\n");
    sxa = ld_sxadat_from_stem(srcvolid);
    if (sxa == NULL) exit(1);
    framepower = sxa_framepower(sxa,&f);
    if (f != mSrcVol->nframes) {
      fprintf(stderr," number of frames is incorrect (%d,%d)\n",
              f,mSrcVol->nframes);
      exit(1);
    }
    printf("INFO: Adjusting Frame Power\n");
    fflush(stdout);
    mri_framepower(mSrcVol,framepower);
  }

  /*--------- Prepare the final mask ------------------------*/
  if (Label != NULL) {
    mFinalMskVol = label2mask_linear(mSrcVol, Qsrc, Fsrc, Wsrc,
                                     Dsrc, mSrcMskVol,
                                     Msrc2lbl, Label, labelfillthresh, float2int_src,
                                     &nlabelhits, &nfinalhits);

    if (mFinalMskVol == NULL) exit(1);
  } else {
    mFinalMskVol = mSrcMskVol;
    nfinalhits = nmskhits;
  }

  if (!oldtxtstyle) {
    /* count the number of functional voxels = 1 in the mask */
    nfinalhits = 0;
    for (r=0;r<mFinalMskVol->height;r++) {
      for (c=0;c<mFinalMskVol->width;c++) {
        for (s=0;s<mFinalMskVol->depth;s++) {
          val = MRIgetVoxVal(mFinalMskVol,c,r,s,0);
          if (val > 0.5) nfinalhits ++;
        }
      }
    }
    if (Label != NULL)
      nlabelhits = CountLabelHits(mSrcVol, Qsrc, Fsrc,
                                  Wsrc, Dsrc, Msrc2lbl,
                                  Label, labelfillthresh,float2int_src);
    else  nlabelhits = 0;
  }

  /*-------------------------------------------------------*/
  /*--------- Map the volume into the ROI -----------------*/
  printf("Averging over ROI\n");
  fflush(stdout);
  mROI = vol2maskavg(mSrcVol, mFinalMskVol,&nhits);
  if (mROI == NULL) exit(1);
  printf("Done averging over ROI (nhits = %d)\n",nhits);
  /*-------------------------------------------------------*/

  /* ------- Save the final mask ------------------ */
  if (finalmskvolid != 0) {
    //mri_save_as_bvolume(mFinalMskVol,finalmskvolid,endian,BF_FLOAT);
    //MRIwriteAnyFormat(mFinalMskVol,finalmskvolid,"bfloat",-1,NULL);
    sprintf(tmpstr,"%s.%s",finalmskvolid,outext);
    MRIwrite(mFinalMskVol,tmpstr);
  }

  /* ------- Save CRS of the the final mask ------------------ */
  if (finalmskcrs != NULL) {
    fp = fopen(finalmskcrs,"w");
    if (fp==NULL) {
      fprintf(stderr,"ERROR: cannot open %s\n",finalmskcrs);
      exit(1);
    }
    for (r=0;r<mFinalMskVol->height;r++) {
      for (c=0;c<mFinalMskVol->width;c++) {
        for (s=0;s<mFinalMskVol->depth;s++) {
          val = MRIgetVoxVal(mFinalMskVol,c,r,s,0);
          if (val > 0.5) {
            fprintf(fp,"%d %d %d\n",c,r,s);
          }
        }
      }
    }
    fclose(fp);
  }

  /* If this is a statistical volume, lower each frame to it's appropriate
     power (eg, variance needs to be sqrt'ed) */
  if (is_sxa_volume(srcvolid)) {
    printf("INFO: Readjusting Frame Power\n");
    fflush(stdout);
    for (f=0; f < mROI->nframes; f++) framepower[f] = 1.0/framepower[f];
    mri_framepower(mROI,framepower);
  }

  /* save the target volume in an appropriate format */
  if(roifile != NULL){
    sprintf(tmpstr,"%s.%s",roifile,outext);
    MRIwrite(mROI,tmpstr);
    /* for a stat volume, save the .dat file */
    if (is_sxa_volume(srcvolid)) {
      sxa->nrows = 1;
      sxa->ncols = 1;
      sv_sxadat_by_stem(sxa,roifile);
    }
  }

  /* save as text */
  if(roitxtfile != NULL) {
    fp = fopen(roitxtfile,"w");
    if (fp==NULL) {
      fprintf(stderr,"ERROR: cannot open %s\n",roitxtfile);
      exit(1);
    }
    if (oldtxtstyle) {
      printf("INFO: saving as old style txt\n");
      fprintf(fp,"%d \n",nmskhits);
    }
    if (! plaintxtstyle ) {
      fprintf(fp,"%d \n",nlabelhits);
      fprintf(fp,"%d \n",nfinalhits);
    }
    for (f=0; f < mROI->nframes; f++)
      fprintf(fp,"%f\n",MRIgetVoxVal(mROI,0,0,0,f));
    fclose(fp);
  }

  /* ------- Mask the source and save it  ------------------ */
  if (srcmskvolid != 0) {
    for (r=0;r<mFinalMskVol->height;r++) {
      for (c=0;c<mFinalMskVol->width;c++) {
        for (s=0;s<mFinalMskVol->depth;s++) {
          val = MRIgetVoxVal(mFinalMskVol,c,r,s,0);
          if (val < 0.5) {
            for (f=0; f < mROI->nframes; f++)
              MRIFseq_vox(mSrcVol,c,r,s,f) = 0.0;
          }
        }
      }
    }
    MRIwrite(mSrcVol,srcmskvolid);
  }

  /* ------- Save as a text list  ------------------ */
  if (ListFile != 0) {
    fp = fopen(ListFile,"w");
    for (c=0;c<mFinalMskVol->width;c++) {
      for (r=0;r<mFinalMskVol->height;r++) {
        for (s=0;s<mFinalMskVol->depth;s++) {
          val = MRIFseq_vox(mFinalMskVol,c,r,s,0);
          if(val < 0.5) continue;
	  fprintf(fp,"%3d %3d %3d ",c,r,s);
	  for (f=0; f < mROI->nframes; f++){
	    val = MRIgetVoxVal(mSrcVol,c,r,s,f);
	    fprintf(fp,"%f ",val);
          }
	  fprintf(fp,"\n");
        }
      }
    }
    fclose(fp);
  }

  return(0);
}
コード例 #6
0
int
main(int argc, char *argv[])
{
  char         **av, fname[STRLEN] ;
  int          ac, nargs, i ;
  char         *subject, *cp, mdir[STRLEN], *out_fname, *name ;
  int          r, g, b, nedits = 0 ;
  MRI          *mri=NULL, *mri_edits=NULL, *mri_aseg_auto=NULL;

  // default output file name:
  out_fname = strcpyalloc("edits.mgz");

  /* rkt: check for and handle version tag */
  nargs = handle_version_option
    (argc, argv,
     "$Id: mri_compile_edits.c,v 1.6 2011/03/02 00:04:14 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 (argc < 2)
    usage_exit(1) ;

  if (strlen(sdir) == 0)
  {
    cp = getenv("SUBJECTS_DIR") ;
    if (cp == NULL)
      ErrorExit
        (ERROR_BADPARM,
         "%s: SUBJECTS_DIR must be defined in the env or on cmdline "
         "with -sdir", Progname) ;
    strcpy(sdir, cp) ;
  }

  subject = argv[1] ;
  if (argv[2]) out_fname = argv[2] ;
  printf("Compiling volume edits for subject %s...\n", subject) ;
  fflush(stdout);

  sprintf(mdir, "%s/%s/mri", sdir, subject) ;

  /*
   * brain.mgz
   */
  sprintf(fname, "%s/brain.mgz", mdir) ;
  mri = MRIread(fname) ;
  if (mri)
  {
    if(NULL == mri_edits) mri_edits = MRIclone(mri, NULL) ;
    int edits = MRIsetVoxelsWithValue(mri,
                                      mri_edits,
                                      WM_EDITED_OFF_VAL,
                                      EDIT_BRAIN_OFF) ;
    edits += MRIsetVoxelsWithValue(mri,
                                   mri_edits,
                                   WM_EDITED_ON_VAL,
                                   EDIT_BRAIN_ON) ;
    nedits += edits;
    MRIfree(&mri) ;
    if (edits) printf("Found %d edits in brain.mgz\n",edits);
    fflush(stdout);
  }

  /*
   * wm.mgz
   */
  sprintf(fname, "%s/wm.mgz", mdir) ;
  mri = MRIread(fname) ;
  if (mri)
  {
    if(NULL == mri_edits) mri_edits = MRIclone(mri, NULL) ;
    int edits = MRIsetVoxelsWithValue(mri,
                                      mri_edits,
                                      WM_EDITED_OFF_VAL,
                                      EDIT_WM_OFF) ;
    edits += MRIsetVoxelsWithValue(mri, mri_edits,
                                   WM_EDITED_ON_VAL,
                                   EDIT_WM_ON) ;
    nedits += edits;
    MRIfree(&mri) ;
    if (edits) printf("Found %d edits in wm.mgz\n",edits);
    fflush(stdout);
  }

  /*
   * brainmask.mgz
   */
  sprintf(fname, "%s/brainmask.mgz", mdir) ;
  mri = MRIread(fname) ;
  if (mri)
  {
    if(NULL == mri_edits) mri_edits = MRIclone(mri, NULL) ;
    int edits = MRIsetVoxelsWithValue(mri,
                                      mri_edits,
                                      WM_EDITED_OFF_VAL,
                                      EDIT_BRAINMASK_OFF) ;
    edits += MRIsetVoxelsWithValue(mri, mri_edits,
                                   WM_EDITED_ON_VAL,
                                   EDIT_BRAINMASK_ON) ;
    nedits += edits;
    MRIfree(&mri) ;
    if (edits) printf("Found %d edits in brainmask.mgz\n",edits);
    fflush(stdout);
  }

  /*
   * brain.finalsurfs.mgz
   */
  sprintf(fname, "%s/brain.finalsurfs.mgz", mdir) ;
  mri = MRIread(fname) ;
  if (mri)
  {
    if(NULL == mri_edits) mri_edits = MRIclone(mri, NULL) ;
    int edits = MRIsetVoxelsWithValue(mri,
                                      mri_edits,
                                      WM_EDITED_OFF_VAL,
                                      EDIT_FINALSURFS_OFF) ;
    edits += MRIsetVoxelsWithValue(mri,
                                   mri_edits,
                                   WM_EDITED_ON_VAL,
                                   EDIT_FINALSURFS_ON) ;
    nedits += edits;
    MRIfree(&mri) ;
    if (edits) printf("Found %d edits in brain.finalsurfs.mgz\n",edits);
    fflush(stdout);
  }

  /*
   * aseg.mgz
   */
  sprintf(fname, "%s/aseg.mgz", mdir) ;
  mri = MRIread(fname) ;
  if (mri)
  {
    if(NULL == mri_edits) mri_edits = MRIclone(mri, NULL) ;
    sprintf(fname, "%s/aseg.auto.mgz", mdir) ;
    mri_aseg_auto = MRIread(fname) ;
    if (mri_aseg_auto)
    {
      int edits = MRIsetDifferentVoxelsWithValue(mri,
                                                 mri_aseg_auto,
                                                 mri_edits,
                                                 EDIT_ASEG_CHANGED);
      nedits += edits;
      MRIfree(&mri) ;
      MRIfree(&mri_aseg_auto) ;
      if (edits) printf("Found %d edits in aseg.mgz\n",edits);
      fflush(stdout);
    }
  }

  if (mri_edits)
  {
    mri_edits->ct = CTABalloc(CTAB_ENTRIES) ;
    strcpy (mri_edits->fname, "mri_compile_edits");
    for (i = 0 ; i < CTAB_ENTRIES ; i++)
    {
      switch (i)
      {
      case EDIT_WM_OFF:
        name = "wm-OFF" ;
        r = 0 ;
        g = 0 ;
        b = 255 ;
        break ;
      case EDIT_WM_ON:
        name = "wm-ON" ;
        r = 255 ;
        g = 0 ;
        b = 0 ;
        break ;
      case EDIT_BRAIN_OFF:
        name = "brain-OFF" ;
        r = 0 ;
        g = 255 ;
        b = 255 ;
        break ;
      case EDIT_BRAIN_ON:
        name = "brain-ON" ;
        r = 255 ;
        g = 255 ;
        b = 0 ;
        break ;
      case EDIT_BRAINMASK_OFF:
        name = "brainmask-OFF" ;
        r = 0 ;
        g = 64 ;
        b = 255 ;
        break ;
      case EDIT_BRAINMASK_ON:
        name = "brainmask-ON" ;
        r = 255 ;
        g = 26 ;
        b = 0 ;
        break ;
      case EDIT_FINALSURFS_OFF:
        name = "brain.finalsurf-OFF" ;
        r = 0 ;
        g = 128 ;
        b = 255 ;
        break ;
      case EDIT_FINALSURFS_ON:
        name = "brain.finalsurfs-ON" ;
        r = 255 ;
        g = 128 ;
        b = 0 ;
        break ;
      case EDIT_ASEG_CHANGED:
        name = "aseg-CHANGED" ;
        r = 255 ;
        g = 255 ;
        b = 128 ;
        break ;
      default:
        continue ;
      }

      strcpy(mri_edits->ct->entries[i]->name, name) ;
      mri_edits->ct->entries[i]->ri = r ;
      mri_edits->ct->entries[i]->gi = g ;
      mri_edits->ct->entries[i]->bi = b ;
      mri_edits->ct->entries[i]->ai = 255;

      /* Now calculate the float versions. */
      mri_edits->ct->entries[i]->rf =
        (float)mri_edits->ct->entries[i]->ri / 255.0;
      mri_edits->ct->entries[i]->gf =
        (float)mri_edits->ct->entries[i]->gi / 255.0;
      mri_edits->ct->entries[i]->bf =
        (float)mri_edits->ct->entries[i]->bi / 255.0;
      mri_edits->ct->entries[i]->af =
        (float)mri_edits->ct->entries[i]->ai / 255.0;
    }
  }

  // recon-all -show-edits greps on this text, so dont change it
  if (nedits && mri_edits)
  {
    printf("%d mri_compile_edits_found, saving results to %s\n",
           nedits, out_fname) ;
    MRIwrite(mri_edits, out_fname);
    printf("Edits can be viewed with command:\n");
    printf("tkmedit %s T1.mgz -segmentation %s\n",subject,out_fname);
  }
  else
  {
    printf("0 mri_compile_edits_found\n") ;
  }

  exit(0) ;
  return(0) ;
}
コード例 #7
0
static int
normalize_timepoints(MRI *mri, double thresh, int nsoap)
{
  int   frame, x, y, z, skip, nvox ;
  double target, val ;
  MRI    *mri_ctrl, *mri_bias, *mri_target, *mri_frame, *mri_kernel ;

  mri_ctrl = MRIcloneDifferentType(mri, MRI_UCHAR) ;
  mri_bias = MRIcloneDifferentType(mri, MRI_FLOAT) ;
  mri_target = MRIcloneDifferentType(mri, MRI_FLOAT) ;
  mri_kernel = MRIgaussian1d(sqrt(2.0*nsoap/M_PI), -1) ;

  for (nvox = x = 0 ; x < mri->width ; x++)
    for (y = 0 ; y < mri->height ; y++)
      for (z = 0 ; z < mri->depth ; z++)
      {
        if (x == Gx && y == Gy && z == Gz)
          DiagBreak() ;
        for (target = 0.0, frame = 0 ; frame < mri->nframes ; frame++)
          target += MRIgetVoxVal(mri, x, y, z, frame) ;
        target /= mri->nframes ;
        if (FZERO(target))
          continue ;  // both vals  0
        skip = 0 ;
        for (frame = 0 ; frame < mri->nframes ; frame++)
        {
          val = MRIgetVoxVal(mri, x, y, z, frame) ;
          if (fabs(val-target) > thresh)
          {
            skip = 1 ;
            break ;
          }
        }
        if (skip)
          continue ;
        nvox++ ;
        MRIsetVoxVal(mri_ctrl, x, y, z, 0, CONTROL_MARKED) ;
        MRIsetVoxVal(mri_target, x, y, z, 0, target) ;
      }

  printf("%d voxels found to base intensity correction on\n", nvox) ;

  // build a bias correction for each time point (which each has its own frame)
  for (frame = 0 ; frame < mri->nframes ; frame++)
  {
    MRIclear(mri_bias) ; 
    for (x = 0 ; x < mri->width ; x++)
      for (y = 0 ; y < mri->height ; y++)
        for (z = 0 ; z < mri->depth ; z++)
        {
          target = MRIgetVoxVal(mri_target, x, y, z, 0) ;
          val = MRIgetVoxVal(mri, x, y, z, frame) ;
          if (FZERO(val))
            val = 1.0 ;
          MRIsetVoxVal(mri_bias, x, y, z, 0, target/val) ;
        }
    MRIbuildVoronoiDiagram(mri_bias, mri_ctrl, mri_bias) ;
    MRIconvolveGaussian(mri_bias, mri_bias, mri_kernel) ;
    //    MRIsoapBubble(mri_bias, mri_ctrl, mri_bias, nsoap) ;
    mri_frame = MRIcopyFrame(mri, NULL, frame, 0) ;
    MRImultiply(mri_frame, mri_bias, mri_frame) ;
    if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
    {
      char fname[STRLEN] ;
      sprintf(fname, "frame%d.mgz", frame) ;
      MRIwrite(mri_frame, fname) ;
      sprintf(fname, "bias%d.mgz", frame) ;
      MRIwrite(mri_bias, fname) ;
      sprintf(fname, "target%d.mgz", frame) ;
      MRIwrite(mri_target, fname) ;
    }
    MRIcopyFrame(mri_frame, mri, 0, frame) ;
  }
  MRIfree(&mri_bias) ; MRIfree(&mri_kernel) ; MRIfree(&mri_target) ; MRIfree(&mri_ctrl) ;
  return(NO_ERROR) ;
}
コード例 #8
0
ファイル: mri_segment.c プロジェクト: guo2004131/freesurfer
static int
MRIcheckRemovals(MRI *mri_T1, MRI *mri_dst, MRI *mri_labels, int wsize)
{
    int    x, y, z, width, depth, height, whalf, ntested, nchanged, on, vertex;
    MRI    *mri_tmp, *mri_region, *mri_plane, *mri_binary_plane ;
    float  min_on ;

    whalf = (wsize-1)/2 ;

    mri_tmp = MRIcopy(mri_dst, NULL) ;
    mri_region = MRIalloc(wsize, wsize, wsize, MRI_UCHAR) ;
    min_on = .1*wsize*wsize ;
    MRIcopyLabel(mri_labels, mri_tmp, 255) ;

    MRIbinarize(mri_tmp, mri_tmp, WM_MIN_VAL, 0, 100) ;
    width = mri_T1->width ;
    height = mri_T1->height ;
    depth = mri_T1->depth ;

    ntested = nchanged = 0 ;
    if (Gdiag == 99)
    {
        MRIwrite(mri_tmp, "tmp.mgh") ;
    }
    for (z = 0 ; z < depth ; z++)
    {
        for (y = 0 ; y < height ; y++)
        {
            for (x = 0 ; x < width ; x++)
            {
                if (z == 87 && y == 88 && x == 163)  /* test1 cs filled */
                {
                    DiagBreak() ;
                }
                if (z == 88 && y == 89 && x == 163)  /* test1 cs filled */
                {
                    DiagBreak() ;
                }

                if (z == 101 && y == 133 && x == 152)
                {
                    DiagBreak() ;
                }
                if (x == 157 && y == 143 && z == 98)
                {
                    DiagBreak() ;
                }
                if (x == 156 && y == 143 && z == 98)
                {
                    DiagBreak() ;
                }

                if (x == 154 && y == 167 && z == 128)
                {
                    DiagBreak() ;
                }
                if (x == 136 && y == 147 && z == 28)
                {
                    DiagBreak() ;
                }

                if (x == 163 && y == 88 && z == 86)
                {
                    DiagBreak() ;
                }

                if ((x == 140 && y == 141 && z == 54) ||
                        (x == 140 && y == 141 && z == 53) ||
                        (x == 140 && y == 142 && z == 53) ||
                        (x == 140 && y == 142 && z == 54) ||
                        (x == 140 && y == 140 && z == 53))
                {
                    DiagBreak() ;  /* test4 cerebellum */
                }
                if (x == 142 && y == 139 && z == 54)   /* test4 */
                {
                    DiagBreak() ;
                }

                if (!MRIgetVoxVal(mri_labels, x, y, z, 0))
                {
                    continue ;
                }
                ntested++ ;

                MRIextract(mri_tmp, mri_region, x-whalf,y-whalf,z-whalf,
                           wsize, wsize, wsize) ;

                vertex =
                    MRIcountCpolvOnAtVoxel(mri_region, whalf, whalf, whalf, wsize, &on) ;

                mri_plane = MRIextractVertexPlane(mri_tmp, NULL, vertex,x,y,z,wsize);
                MRIthreshold(mri_plane, mri_plane, 50) ;
                MRIremove1dStructures(mri_plane,mri_plane, 10000,2,NULL);
                mri_binary_plane = MRIfillFG(mri_plane, NULL, whalf, whalf, 0,
                                             50, 128, &on) ;
                if (on > min_on)
                {
                    int  xk, yk, i, ntransitions, i_prev  ;

                    /*
                       now look at the winding # (number of white-black transitions
                       in a circle around the central point
                    */

                    ntransitions = 0 ;
                    for (i = 0 ; i < NPTS ; i++)
                    {
                        xk = xpts[i] ;
                        yk = ypts[i] ;
                        i_prev = i-1 ;
                        if (i_prev < 0)
                        {
                            i_prev = NPTS-1 ;
                        }
                        if (MRIgetVoxVal(mri_binary_plane, whalf+xpts[i], whalf+ypts[i], 0, 0) !=
                                MRIgetVoxVal(mri_binary_plane,whalf+xpts[i_prev],
                                             whalf+ypts[i_prev],0, 0))
                        {
                            ntransitions++ ;
                        }
                    }
                    if (ntransitions > 2)   /* not planar */
                    {
                        nchanged++ ;
                        MRIsetVoxVal(mri_dst, x, y, z, 0, MRIgetVoxVal(mri_T1, x, y, z, 0)) ;
                    }
                }
                if (Gdiag & DIAG_WRITE)
                {
                    MRIwrite(mri_region, "region.mgh") ;
                    MRIwrite(mri_plane, "plane.mgh") ;
                    MRIwrite(mri_binary_plane, "binary_plane.mgh") ;
                }
                MRIfree(&mri_plane) ;
                MRIfree(&mri_binary_plane) ;
            }
        }
    }
    MRIfree(&mri_tmp) ;
    MRIfree(&mri_region) ;
    if (Gdiag & DIAG_SHOW)
    {
        fprintf(stderr, "               %8d voxels tested (%2.2f%%)\n",
                ntested, 100.0f*(float)ntested/ (float)(width*height*depth));
        fprintf(stderr, "               %8d voxels restored (%2.2f%%)\n",
                nchanged, 100.0f*(float)nchanged/ (float)(width*height*depth));
    }
    return(NO_ERROR) ;
}
コード例 #9
0
ファイル: mri_segment.c プロジェクト: guo2004131/freesurfer
MRI *
MRIfindBrightNonWM(MRI *mri_T1, MRI *mri_wm)
{
    int     width, height, depth, x, y, z, nlabeled, nwhite,
            xk, yk, zk, xi, yi, zi;
    BUFTYPE val, wm ;
    MRI     *mri_labeled, *mri_tmp ;

    mri_labeled = MRIclone(mri_T1, NULL) ;
    width = mri_T1->width ;
    height = mri_T1->height ;
    depth = mri_T1->depth ;

    for (z = 0 ; z < depth ; z++)
    {
        for (y = 0 ; y < height ; y++)
        {
            for (x = 0 ; x < width ; x++)
            {
                val = MRIgetVoxVal(mri_T1, x, y, z, 0) ;
                wm = MRIgetVoxVal(mri_wm, x, y, z, 0) ;

                if (x == 110 && y == 125 && z == 172)  /* T1=148 */
                {
                    DiagBreak() ;
                }
                /* not white matter and bright (e.g. eye sockets) */
                if ((wm < WM_MIN_VAL) && (val > 125))
                {
                    nwhite = 0 ;
                    for (xk = -1 ; xk <= 1 ; xk++)
                    {
                        xi = mri_T1->xi[x+xk] ;
                        for (yk = -1 ; yk <= 1 ; yk++)
                        {
                            yi = mri_T1->yi[y+yk] ;
                            for (zk = -1 ; zk <= 1 ; zk++)
                            {
                                zi = mri_T1->zi[z+zk] ;
                                if (MRIgetVoxVal(mri_wm, xi, yi, zi, 0) >= WM_MIN_VAL)
                                {
                                    nwhite++ ;
                                }
                            }
                        }
                    }
#define MIN_WHITE  ((3*3*3-1)/2)
                    if (nwhite < MIN_WHITE)
                    {
                        MRIsetVoxVal(mri_labeled, x, y, z, 0, BRIGHT_LABEL) ;
                    }
                }
            }
        }
    }

    /* find all connected voxels that are above 115 */
    MRIdilateThreshLabel(mri_labeled, mri_T1, NULL, BRIGHT_LABEL, 10,115);
    MRIclose(mri_labeled, mri_labeled) ;

    /* expand once more to all neighboring voxels that are bright. At
       worst we will erase one voxel of white matter.
    */
    mri_tmp =
        MRIdilateThreshLabel(mri_labeled, mri_T1, NULL, BRIGHT_LABEL,1,100);
    MRIxor(mri_labeled, mri_tmp, mri_tmp, 1, 255) ;
    MRIreplaceValues(mri_tmp, mri_tmp, 1, BRIGHT_BORDER_LABEL) ;
    MRIunion(mri_tmp, mri_labeled, mri_labeled) ;
#if 0
    fprintf(stderr, "selectively smoothing volume....\n") ;
    MRIsoapBubbleLabel(mri_T1, mri_labeled, mri_T1, BRIGHT_LABEL, 200) ;
#endif
    if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
    {
        MRIwrite(mri_labeled, "label.mgh") ;
    }
    /*    MRIwrite(mri_tmp, "tmp.mgh") ;*/
    nlabeled = MRIvoxelsInLabel(mri_labeled, BRIGHT_LABEL) ;
    fprintf(stderr, "%d bright non-wm voxels segmented.\n", nlabeled) ;

    MRIfree(&mri_tmp) ;
    return(mri_labeled) ;
}
コード例 #10
0
ファイル: mri_segment.c プロジェクト: guo2004131/freesurfer
MRI *
MRIfillVentricles(MRI *mri_src, MRI *mri_dst)
{
    int     width, height, depth, x, y, z, xk, yk, xi, yi, nfilled, total, s ;
    MRI     *mri_filled, *mri_ventricles = NULL ;
    MRI_SEGMENTATION *mriseg ;
    MRI_SEGMENT      *mseg ;
    Real    xt, yt, zt ;

    if (!mri_dst)
    {
        mri_dst = MRIclone(mri_src, NULL) ;
    }

    width = mri_src->width ;
    height = mri_src->height ;
    depth = mri_src->depth ;

    MRIcopy(mri_src, mri_dst) ;
    mri_filled = MRIcopy(mri_src, NULL) ;

    MRIreplaceValues(mri_filled, mri_filled, VENTRICLE_FILL,
                     VENTRICLE_FILL-1) ;

    /* first fill each coronal slice starting from a background seed */
    for (z = 0 ; z < depth ; z++)
    {
        total = 0 ;
        do
        {
            nfilled = 0 ;
            MRIsetVoxVal(mri_filled, 0, 0, z, 0, VENTRICLE_FILL) ;
            for (y = 0 ; y < height ; y++)
            {
                for (x = 0 ; x < width ; x++)
                {
                    if (MRIgetVoxVal(mri_filled, x, y, z, 0) == VENTRICLE_FILL)
                    {
                        for (yk = -1 ; yk <= 1 ; yk++)
                        {
                            yi = mri_src->yi[y+yk] ;
                            for (xk = -1 ; xk <= 1 ; xk++)
                            {
                                xi = mri_src->xi[x+xk] ;
                                if (!MRIgetVoxVal(mri_filled, xi, yi, z, 0))
                                {
                                    nfilled++ ;
                                    MRIsetVoxVal(mri_filled, xi, yi, z, 0, VENTRICLE_FILL) ;
                                }
                            }
                        }
                    }
                }
            }
            total += nfilled ;
        }
        while (nfilled > 0) ;
    }

    MRIcomplement(mri_filled, mri_filled) ;
    MRIreplaceValues(mri_filled, mri_filled, 1, VENTRICLE_FILL) ;
    mriseg = MRIsegment(mri_filled, 1, 255) ;
    fprintf(stderr, "%d segments found...\n", mriseg->nsegments) ;
    if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
    {
        MRIwrite(mri_filled, "exterior_filled.mgh") ;
    }
    for (s = 0 ; s < mriseg->nsegments ; s++)
    {
        mseg = &mriseg->segments[s] ;
        if (mseg->nvoxels < 100 ||
                mseg->z1-mseg->z0 < 7)
        {
            continue ;
        }
        MRIvoxelToTalairach(mri_src, mseg->cx, mseg->cy, mseg->cz, &xt, &yt, &zt);
        fprintf(stderr, "added segment %d, nvox=%d, bbox [%d:%d, %d:%d, %d:%d]\n"
                "\tc = %2.1f, %2.1f, %2.1f (tal = %2.1f, %2.1f, %2.1f)\n",
                s, mseg->nvoxels, mseg->x0, mseg->x1, mseg->y0,mseg->y1,mseg->z0,
                mseg->z1, mseg->cx, mseg->cy, mseg->cz, xt, yt, zt) ;
        mri_ventricles = MRIsegmentToImage(mri_filled, mri_ventricles, mriseg, s) ;
    }

    MRIfree(&mri_filled) ;
    MRIsegmentFree(&mriseg) ;

    /* remove voxels close to the midline so that the cc can still be found */
    for (z = 0 ; z < depth ; z++)
    {
        for (y = 0 ; y < height ; y++)
        {
            for (x = 0 ; x < width ; x++)
            {
                MRIvoxelToTalairach(mri_src, x, y, z, &xt, &yt, &zt);
                if (fabs(xt) < 5)
                {
                    MRIsetVoxVal(mri_ventricles, x, y, z, 0, 0) ;
                }
            }
        }
    }

    if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
    {
        MRIwrite(mri_ventricles, "ventricles.mgh") ;
    }
    MRIunion(mri_ventricles, mri_dst, mri_dst) ;

    MRIfree(&mri_ventricles) ;
    return(mri_dst) ;
}
コード例 #11
0
ファイル: mri_segment.c プロジェクト: guo2004131/freesurfer
int
main(int argc, char *argv[])
{
    MRI     *mri_src, *mri_dst, *mri_tmp, *mri_labeled, *mri_labels;
    char    *input_file_name, *output_file_name ;
    int     nargs, i, msec ;
    struct timeb  then ;
    float   white_mean, white_sigma, gray_mean, gray_sigma ;

    char cmdline[CMD_LINE_LEN] ;

    TAGmakeCommandLineString(argc, argv, cmdline) ;

    /* rkt: check for and handle version tag */
    nargs = handle_version_option
            (argc, argv,
             "$Id: mri_segment.c,v 1.40 2011/03/02 00:04:24 nicks Exp $",
             "$Name: stable5 $");
    if (nargs && argc - nargs == 1)
    {
        exit (0);
    }
    argc -= nargs;

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

    for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++)
    {
        nargs = get_option(argc, argv) ;
        argc -= nargs ;
        argv += nargs ;
    }

    if (argc < 3)
    {
        usage_exit(1);
    }

    TimerStart(&then) ;
    input_file_name = argv[1] ;
    output_file_name = argv[2] ;

    mri_src = MRIread(input_file_name) ;
    if (!mri_src)
        ErrorExit(ERROR_NOFILE, "%s: could not read source volume from %s",
                  Progname, input_file_name) ;
    MRIaddCommandLine(mri_src, cmdline) ;
    if (mri_src->type != MRI_UCHAR)
    {
        MRI *mri_tmp ;
        printf("changing input type from %d to UCHAR\n", mri_src->type) ;
        mri_tmp = MRIchangeType(mri_src, MRI_UCHAR, 0, 1000, 1) ;
        MRIfree(&mri_src) ;
        mri_src = mri_tmp ;
    }

    if (thicken > 1)
    {
        mri_dst = MRIcopy(mri_src, NULL) ;
        /*    MRIfilterMorphology(mri_dst, mri_dst) ;*/
        fprintf(stderr, "removing 1-dimensional structures...\n") ;
        MRIremove1dStructures(mri_dst, mri_dst, 10000, 2, NULL) ;
#if 0
        MRIcheckRemovals(mri_src, mri_dst, mri_labels, 5) ;
        fprintf(stderr, "thickening thin strands....\n") ;
        MRIthickenThinWMStrands(mri_src, mri_dst, mri_dst, thickness, nsegments,
                                wm_hi) ;
#endif
        MRIwrite(mri_dst, output_file_name) ;
        exit(0) ;
    }

    mri_labels = MRIclone(mri_src, NULL) ;
    if (auto_detect_stats && !wm_low_set) /* widen range to allow
                                           for more variability */
    {
        wm_low -= 10 ;
    }
    fprintf(stderr, "doing initial intensity segmentation...\n") ;
    mri_tmp = MRIintensitySegmentation(mri_src, NULL, wm_low, wm_hi, gray_hi);

    if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
    {
        MRIwrite(mri_tmp, "tmp1.mgz") ;
    }
    fprintf(stderr, "using local statistics to label ambiguous voxels...\n") ;
    MRIhistoSegment(mri_src, mri_tmp, wm_low, wm_hi, gray_hi, wsize, 3.0f) ;
    if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
    {
        MRIwrite(mri_tmp, "tmp2.mgz") ;
    }

    if (auto_detect_stats)
    {

        fprintf(stderr, "computing class statistics for intensity windows...\n") ;
        MRIcomputeClassStatistics(mri_src, mri_tmp, gray_low, WHITE_MATTER_MEAN,
                                  &white_mean, &white_sigma, &gray_mean,
                                  &gray_sigma) ;
        if (!finite(white_mean) || !finite(white_sigma) ||
                !finite(gray_mean) || !finite(gray_sigma))
            ErrorExit
            (ERROR_BADPARM,
             "%s: class statistics not finite - check input volume!",
             Progname);

        if (!wm_low_set)
        {
            if (FZERO(gray_sigma))
            {
                wm_low = (white_mean+gray_mean) / 2 ;
            }
            else
            {
                wm_low = gray_mean + gray_sigma ;
            }
        }

        if (!gray_hi_set)
        {
            gray_hi = gray_mean + 2*gray_sigma ;
#if 1
            if (gray_hi >= white_mean)
            {
                gray_hi = white_mean-1 ;
            }
#endif
        }
        fprintf(stderr, "setting bottom of white matter range to %2.1f\n",wm_low);
        fprintf(stderr, "setting top of gray matter range to %2.1f\n", gray_hi) ;

        if (log_stats)
        {
            FILE *fp ;

            fp = fopen("segment.dat", "w") ;
            if (fp)
            {
                fprintf(fp, "WM: %2.1f +- %2.1f\n",white_mean, white_sigma) ;
                fprintf(fp, "GM: %2.1f +- %2.1f\n",gray_mean, gray_sigma) ;
                fprintf(fp, "setting bottom of white matter range to %2.1f\n",wm_low);
                fprintf(fp, "setting top of gray matter range to %2.1f\n", gray_hi) ;
                fclose(fp) ;
            }
        }

        fprintf(stderr, "doing initial intensity segmentation...\n") ;
        mri_tmp = MRIintensitySegmentation(mri_src, NULL, wm_low, wm_hi, gray_hi);

        fprintf(stderr, "using local statistics to label ambiguous voxels...\n") ;
        MRIhistoSegment(mri_src, mri_tmp, wm_low, wm_hi, gray_hi, wsize, 3.0f) ;
    }
    else
    {
        /* just some not-too-dopey defaults - won't really be used */
        white_mean =  110 ;
        white_sigma = 5.0 ;
        gray_mean = 65 ;
        gray_sigma = 12 ;
    }

    fprintf(stderr,
            "using local geometry to label remaining ambiguous voxels...\n") ;
    mri_labeled = MRIcpolvMedianCurveSegment(mri_src, mri_tmp, NULL, 5, 3,
                  gray_hi, wm_low);
    fprintf(stderr,
            "\nreclassifying voxels using Gaussian border classifier...\n") ;

    /*
      now use the gray and white matter border voxels to build a Gaussian
      classifier at each point in space and reclassify all voxels in the
      range [wm_low-5,gray_hi].
      */
    for (i = 0 ; i < niter ; i++)
    {
        MRIreclassify(mri_src, mri_labeled, mri_labeled, wm_low-5,gray_hi,wsize);
    }
    MRIfree(&mri_tmp) ;

    mri_dst = MRImaskLabels(mri_src, mri_labeled, NULL) ;
    MRIfree(&mri_labeled) ;
    MRIrecoverBrightWhite(mri_src, mri_dst,mri_dst,wm_low,wm_hi,white_sigma,.33);
    fprintf(stderr,
            "\nremoving voxels with positive offset direction...\n") ;

#if 0
    MRIremoveWrongDirection(mri_dst, mri_dst, 3, wm_low-5, gray_hi, mri_labels) ;
#else
    MRIremoveWrongDirection(mri_dst, mri_dst, 3, wm_low-5, gray_hi, NULL) ;
#endif

    if (thicken)
    {
        /*    MRIfilterMorphology(mri_dst, mri_dst) ;*/
        fprintf(stderr, "removing 1-dimensional structures...\n") ;
        MRIremove1dStructures(mri_dst, mri_dst, 10000, 2, mri_labels) ;
#if 0
        MRIcheckRemovals(mri_src, mri_dst, mri_labels, 5) ;
#endif
        fprintf(stderr, "thickening thin strands....\n") ;
        MRIthickenThinWMStrands(mri_src, mri_dst, mri_dst, thickness, nsegments,
                                wm_hi) ;
    }

    mri_tmp = MRIfindBrightNonWM(mri_src, mri_dst) ;
    MRIbinarize(mri_tmp, mri_tmp, WM_MIN_VAL, 255, 0) ;
    MRImaskLabels(mri_dst, mri_tmp, mri_dst) ;
    MRIfilterMorphology(mri_dst, mri_dst) ;

    if (fill_bg)
    {
        fprintf(stderr, "filling basal ganglia....\n") ;
        MRIfillBasalGanglia(mri_src, mri_dst) ;
    }
    if (fill_ventricles)
    {
        fprintf(stderr, "filling ventricles....\n") ;
        MRIfillVentricles(mri_dst, mri_dst) ;
    }


    MRIfree(&mri_src) ;
    msec = TimerStop(&then) ;
    fprintf(stderr, "white matter segmentation took %2.1f minutes\n",
            (float)msec/(1000.0f*60.0f));
    fprintf(stderr, "writing output to %s...\n", output_file_name) ;
    if (keep_edits)
    {
        MRI *mri_old ;

        mri_old = MRIread(output_file_name) ;
        if (!mri_old)
        {
            ErrorPrintf
            (ERROR_NOFILE, "%s: could not read file %s to preserve edits",
             Progname, output_file_name) ;
            exit(1);
        }
        else
        {
            MRIcopyLabel(mri_old, mri_dst, WM_EDITED_ON_VAL) ;
            MRIcopyLabel(mri_old, mri_dst, WM_EDITED_OFF_VAL) ;
            MRIfree(&mri_old) ;
        }
    }
    MRIwrite(mri_dst, output_file_name) ;

    MRIfree(&mri_dst) ;

    exit(0) ;
    return(0) ;
}
コード例 #12
0
static int
MRISrepositionToInnerSkull(MRI_SURFACE *mris, MRI *mri_smooth, INTEGRATION_PARMS *parms) {
  MRI   *mri_dist, *mri_bin, *mri_kernel, *mri_bin_smooth, *mri_dist_smooth ;
  float l_spring, sigma ;
  int   i, ic_order, avgs ;

  parms->niterations = 1000 ;
  if (parms->momentum < 0.0)
    parms->momentum = 0.0 /*0.75*/ ;

  mri_bin = MRIbinarize(mri_smooth, NULL, 15, 0, TARGET_VAL) ;
  mri_dist = MRIdistanceTransform(mri_bin, NULL, TARGET_VAL, 10*mri_bin->width, DTRANS_MODE_SIGNED, NULL) ;
  MRIwrite(mri_bin, "bin.mgz") ;
  MRIwrite(mri_dist, "dist.mgz") ;
  MRISscaleBrain(mris, mris, 0.5) ;  // start inside

  mri_kernel = MRIgaussian1d(2, 0) ;
  mri_bin_smooth = MRIconvolveGaussian(mri_bin, NULL, mri_kernel) ;
  MRIwrite(mri_bin_smooth, "bin_smooth.mgz") ;
  MRISfindOptimalRigidPosition(mris, mri_bin_smooth, parms) ;
  MRIfree(&mri_kernel) ;
  MRIfree(&mri_bin_smooth) ;
  avgs = parms->n_averages = 32 ;
  l_spring = parms->l_spring_norm ;
  for (ic_order = 3 ; ic_order <= 3 ; ic_order++) {
    if (ic_order != ic_init) {
      MRI_SURFACE *mris_new ;
      char fname[STRLEN], *mdir ;

      mdir = getenv("FREESURFER_HOME") ;
      if (!mdir)
        ErrorExit(ERROR_BADPARM, "FREESURFER_HOME not defined in environment") ;

      sprintf(fname, "%s/lib/bem/ic%d.tri", mdir, ic_order) ;
      mris_new = MRISread(fname) ;
      MRISupsampleIco(mris, mris_new) ;
      MRISfree(&mris) ;
      mris = mris_new ;
    }

    printf("********************** using ICO order %d *********************\n", ic_order) ;
    parms->n_averages = avgs ;
    parms->l_spring_norm = l_spring ;
    for (sigma = 16.0, i = 0 ; i < 7 ; i++, sigma /= 2) {
      printf("******************** pass %d, sigma = %2.2f, avgs = %d ******************\n",
             i+1, sigma, parms->n_averages) ;
      parms->sigma = sigma ;
      MRISsetVals(mris,parms->sigma) ;
      MRIScopyValToVal2(mris) ;
      MRISsetVals(mris, 0) ;  // 0 mm from fat
      parms->mri_brain = mri_dist ;


      mri_kernel = MRIgaussian1d(sigma, 0) ;
      mri_dist_smooth = MRIconvolveGaussian(mri_dist, NULL, mri_kernel) ;
      MRIfree(&mri_kernel) ;
      if (i == 0) {
        MRIwrite(mri_dist_smooth, "dist_smooth.mgz") ;

        MRISwrite(mris, "lh.0000") ;
      }
      MRISsetVals(mris, 0) ;
      MRISpositionSurface(mris, mri_dist, mri_dist_smooth, parms) ;
      parms->l_spring_norm /= 2;
      parms->n_averages /= 2 ;
    }
  }

  MRIfree(&mri_bin) ;
  MRIfree(&mri_dist) ;
  return(NO_ERROR) ;
}
コード例 #13
0
static int
initialize_surface_position(MRI_SURFACE *mris, MRI *mri_masked, int outside, INTEGRATION_PARMS *parms) {
  MRI    *mri_dilated ;
  int    x, y, z, vno ;
  double x0, y0, z0, radius = 0, dist, num ;
  Real   xs, ys, zs ;
  VERTEX *v ;

  if (outside) {
    mri_dilated = MRIdilate(mri_masked, NULL) ;

    MRIsubtract(mri_dilated, mri_masked, mri_dilated) ;
    MRIwrite(mri_dilated, "outside.mgz") ;

    num = x0 = y0 = z0 = 0 ;
    for (x = 0 ; x < mri_dilated->width ; x++) {
      for (y = 0 ; y < mri_dilated->height ; y++) {
        for (z = 0 ; z < mri_dilated->depth ; z++) {
          if (MRIgetVoxVal(mri_dilated, x, y, z,0) > 0) {
            MRIvoxelToSurfaceRAS(mri_dilated, x, y, z, &xs, &ys, &zs) ;
            x0 += xs ;
            y0 += ys ;
            z0 += zs ;
            num++ ;
          }
        }
      }
    }
    x0 /= num ;
    y0 /= num ;
    z0 /= num ;
    printf("centroid at (%2.1f, %2.1f, %2.1f)\n", x0,  y0, z0) ;

    num = radius = 0 ;
    for (x = 0 ; x < mri_dilated->width ; x++) {
      for (y = 0 ; y < mri_dilated->height ; y++) {
        for (z = 0 ; z < mri_dilated->depth ; z++) {
          if (MRIgetVoxVal(mri_dilated, x, y, z,0) > 0) {
            MRIvoxelToSurfaceRAS(mri_dilated, x, y, z, &xs, &ys, &zs) ;
            dist = sqrt(SQR(xs-x0)+SQR(ys-y0)+SQR(zs-z0)) ;
            radius += dist ;
            num++ ;
          }
        }
      }
    }

    radius /= num ;
    printf("average radius = %2.3f\n", radius) ;


    MRIfree(&mri_dilated) ;
    MRISprojectOntoSphere(mris, mris, radius*1.25) ;
    for (vno = 0 ; vno < mris->nvertices ; vno++) {
      v = &mris->vertices[vno] ;
      v->x += x0 ;
      v->y += y0 ;
      v->z += z0 ;
    }
    MRIScomputeMetricProperties(mris) ;
  }
  parms->target_radius = radius ;
  MRISsaveVertexPositions(mris, ORIGINAL_VERTICES) ;
  return(NO_ERROR) ;
}
コード例 #14
0
int
main(int argc, char *argv[]) {
  char          **av, fname[STRLEN], *T1_fname, *PD_fname, *output_dir, *mdir ;
  int           ac, nargs, msec, s ;
  MRI_SURFACE   *mris ;
  MRI           *mri_flash1, *mri_flash2, *mri_masked, *mri_masked_smooth, *mri_kernel,
  *mri_mean, *mri_dif, *mri_binary, *mri_distance ;
  MRI *mri_smooth, *mri_grad, *mri_inner ;
  struct timeb  then ;
  double        l_spring ;
  MRI_SEGMENTATION *mriseg ;


  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mris_AA_shrinkwrap.c,v 1.5 2011/03/02 00:04:34 nicks Exp $", "$Name: stable5 $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  Gdiag |= DIAG_SHOW ;
  Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  memset(&parms, 0, sizeof(parms)) ;

  parms.projection = NO_PROJECTION ;
  parms.tol = 0.05 ;
  parms.check_tol = 1 ;
  parms.ignore_energy = 1 ;
  parms.dt = 0.5f ;
  parms.base_dt = BASE_DT_SCALE*parms.dt ;

  parms.l_spring_norm = 1 ;
  parms.l_shrinkwrap = 0 ;
  parms.l_intensity = 1 ;

  parms.niterations = 0 ;
  parms.write_iterations = 0 /*WRITE_ITERATIONS */;
  parms.integration_type = INTEGRATE_MOMENTUM ;
  parms.momentum = 0.0 /*0.8*/ ;
  parms.l_intensity = 1 ;
  parms.dt_increase = 1.0 /* DT_INCREASE */;
  parms.dt_decrease = 0.50 /* DT_DECREASE*/ ;
  parms.error_ratio = 50.0 /*ERROR_RATIO */;
  /*  parms.integration_type = INTEGRATE_LINE_MINIMIZE ;*/
  parms.l_surf_repulse = 0.0 ;
  parms.l_repulse = 0 /*1*/ ;

  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  mdir = getenv("FREESURFER_HOME") ;
  if (!mdir)
    ErrorExit(ERROR_BADPARM, "FREESURFER_HOME not defined in environment") ;

  if (argc < 4)
    usage_exit() ;

  /* set default parameters for white and gray matter surfaces */
  parms.niterations = 1000 ;
  if (parms.momentum < 0.0)
    parms.momentum = 0.0 /*0.75*/ ;

  TimerStart(&then) ;
  T1_fname = argv[1] ;
  PD_fname = argv[2] ;
  output_dir = argv[3] ;
  fprintf(stderr, "reading volume %s...\n", T1_fname) ;
  mri_flash1 = MRIread(T1_fname) ;
  if (!mri_flash1)
    ErrorExit(ERROR_NOFILE, "%s: could not read input volume %s", Progname, T1_fname) ;

  mri_flash2 = MRIread(PD_fname) ;
  if (!mri_flash2)
    ErrorExit(ERROR_NOFILE, "%s: could not read input volume %s", Progname, T1_fname) ;

  //  setMRIforSurface(mri_flash1);
  sprintf(fname, "%s/lib/bem/ic%d.tri", mdir, ic_init) ;
  mris = MRISread(fname) ;
  if (!mris)
    ErrorExit(ERROR_NOFILE, "%s: could not read icosahedron %s", Progname, fname) ;

  mri_mean = MRImean(mri_flash1, NULL, 5) ;
  MRIwrite(mri_mean, "mean.mgz") ;

  mri_dif = MRIabsdiff(mri_flash1, mri_flash2, NULL) ;
  MRIwrite(mri_dif, "dif.mgz") ;

  mriseg = MRIsegment(mri_mean, 30, 100000) ;
  s = MRIsegmentMax(mriseg) ;
  mri_masked = MRIsegmentToImage(mri_flash1, NULL, mriseg, s) ;
  MRIwrite(mri_masked, "mask.mgz") ;
  MRIsegmentFree(&mriseg) ;

  // MRIthresholdMask(mri_dif, mri_masked, mri_dif, 1, 0) ;
  // MRIwrite(mri_dif, "dif_masked.mgz") ;


  mri_kernel = MRIgaussian1d(2, 0) ;
  mri_smooth = MRIconvolveGaussian(mri_dif, NULL, mri_kernel) ;
  MRIwrite(mri_smooth, "smooth.mgz") ;
  MRIScopyVolGeomFromMRI(mris, mri_smooth) ;
  mris->useRealRAS = 1 ;

  initialize_surface_position(mris, mri_dif, 1, &parms) ;
  MRISwrite(mris, "init") ;
  MRISrepositionToInnerSkull(mris, mri_smooth, &parms) ;

  exit(0) ;
  mri_grad = MRIsobel(mri_smooth, NULL, NULL) ;
  MRIwrite(mri_grad, "grad.mgz") ;
  mri_inner = MRIfindInnerBoundary(mri_dif, mri_grad, NULL, 5.0) ;
  MRIwrite(mri_inner, "inner.mgz") ;
  MRIbinarize(mri_inner, mri_inner, 10, 0, 128) ;

  MRISpositionOptimalSphere(mris, mri_inner, 6) ;
  MRISwrite(mris, "optimal") ;
  exit(0) ;
  parms.sigma = 4 / mri_flash1->xsize ;
  // mri_dist = create_distance_map(mri_masked, NULL, BORDER_VAL, OUTSIDE_BORDER_STEP) ;
  MRISsetVals(mris,parms.sigma) ;
  MRIScopyValToVal2(mris) ;
  MRISsetVals(mris, 0) ;
  sprintf(parms.base_name, "%s_inner_skull%s%s", "test", output_suffix, suffix) ;
  parms.mri_brain = mri_masked ;
  l_spring = parms.l_spring_norm ;
  mri_kernel = MRIgaussian1d(parms.sigma, 0) ;


  mri_binary = MRIbinarize(mri_dif, mri_binary, 40, 0, 128) ;
  MRIwrite(mri_binary, "bin.mgz") ;
  mri_distance = MRIdistanceTransform(mri_binary, NULL, 128, 100, DTRANS_MODE_SIGNED, NULL) ;
  MRIwrite(mri_distance, "dist.mgz") ;
  mri_masked_smooth = MRIconvolveGaussian(mri_distance, NULL, mri_kernel) ;
  MRIfree(&mri_kernel) ;
  MRIwrite(mri_masked_smooth, "dif_smooth.mgz") ;

  MRISwrite(mris, "inner_skull.tri") ;

  msec = TimerStop(&then) ;
  fprintf(stderr,"positioning took %2.1f minutes\n", (float)msec/(60*1000.0f));
  exit(0) ;
  return(0) ;  /* for ansi */
}
コード例 #15
0
int
main(int argc, char *argv[]) {
  char   **av, fname[STRLEN] ;
  int    ac, nargs, i ;
  MRI    *mri_flash[MAX_IMAGES], *mri_T1, *mri_PD ;
  char   *in_fname, *out_PD_fname, *out_T1_fname ;
  int          msec, minutes, seconds, nvolumes ;
  struct timeb start ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mri_estimate_tissue_parms.c,v 1.9 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) ;

  TimerStart(&start) ;
  parms.dt = 1e-6 ;
  parms.tol = 1e-5 ;
  parms.momentum = 0.0 ;
  parms.niterations = 20 ;

  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_T1_fname = argv[argc-2] ;
  out_PD_fname = argv[argc-1] ;
  FileNameOnly(out_T1_fname, fname) ;
  FileNameRemoveExtension(fname, fname) ;
  strcpy(parms.base_name, fname) ;

  nvolumes = 0 ;
  for (i = 1 ; i < argc-2 ; i++) {
    if (argv[i][0] == '-') {
      if (!stricmp(argv[i]+1, "te"))
        te = atof(argv[i+1]) ;
      else if (!stricmp(argv[i]+1, "tr"))
        tr = atof(argv[i+1]) ;
      else if (!stricmp(argv[i]+1, "fa"))
        fa = RADIANS(atof(argv[i+1])) ;
      else
        ErrorExit(ERROR_BADPARM, "%s: unsupported MR parameter %s",
                  Progname, argv[i]+1) ;
      i++ ;  /* skip parameter */
      continue ;
    }

    in_fname = argv[i] ;
    printf("reading %s...", in_fname) ;

    mri_flash[nvolumes] = MRIread(in_fname) ;
    if (!mri_flash[nvolumes])
      ErrorExit(Gerror, "%s: MRIread(%s) failed", Progname, in_fname) ;
    if (tr > 0) {
      mri_flash[nvolumes]->tr = tr ;
      tr = 0 ;
    }
    if (te > 0) {
      mri_flash[nvolumes]->te = te ;
      te = 0 ;
    }
    if (fa > 0) {
      mri_flash[nvolumes]->flip_angle = fa ;
      fa = 0 ;
    }
    printf("TE = %2.2f, TR = %2.2f, alpha = %2.2f\n", mri_flash[nvolumes]->te,
           mri_flash[nvolumes]->tr, DEGREES(mri_flash[nvolumes]->flip_angle)) ;
    mri_flash[nvolumes]->flip_angle = mri_flash[nvolumes]->flip_angle;
    if (conform) {
      MRI *mri_tmp ;

      printf("embedding and interpolating volume\n") ;
      mri_tmp = MRIconform(mri_flash[nvolumes]) ;
      /*      MRIfree(&mri_src) ;*/
      mri_flash[nvolumes] = mri_tmp ;
    }
    if (FZERO(mri_flash[nvolumes]->tr) ||
        FZERO(mri_flash[nvolumes]->flip_angle))
      ErrorExit(ERROR_BADPARM, "%s: invalid TR or FA for image %d:%s",
                Progname, nvolumes, in_fname) ;
    nvolumes++ ;
  }
  printf("using %d FLASH volumes to estimate tissue parameters.\n", nvolumes) ;
  mri_T1 = MRIclone(mri_flash[0], NULL) ;
  mri_PD = MRIclone(mri_flash[0], NULL) ;


  {
    double   sse, last_T1, last_PD, total_rms, avg_rms ;
    int      x, y, z, width, height, depth, total_vox, ignored, nvox ;
    struct timeb first_slice ;

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

    TimerStart(&first_slice) ;

    last_T1 = last_PD = 1000 ;
    sse = 0.0 ;
    width = mri_T1->width ;
    height = mri_T1->height ;
    depth = mri_T1->depth ;
    total_vox = width*depth*height ;
#if 0
    estimateVoxelParameters(mri_flash, nvolumes, width/2, height/2, depth/2,
                            mri_T1, mri_PD, last_T1, last_PD) ;
#endif
    if (Gdiag_no == 999) {
      x = 130 ;
      y = 124 ;
      z = 74 ; /* CSF */
      computeErrorSurface("error_surf_csf.dat",mri_flash,nvolumes,x,y,z,500,3000,500,3000);
      x = 161 ;
      y = 157 ;
      z = 63 ;  /* wm */
      computeErrorSurface("error_surf_wm.dat",mri_flash,nvolumes,x,y,z,250,3000,250,3000);
      x = 166 ;
      y = 153 ;
      z = 63 ;  /* gm */
      computeErrorSurface("error_surf_gm.dat",mri_flash,nvolumes,x,y,z,250,3000,250,3000);
    }
    avg_rms = 0 ;
    for (ignored = z = 0 ; z < depth ; z++) {
      if (z > 0)
        printf("z = %d, avg rms=%2.1f, T1=%2.0f, PD=%2.0f...\n",
               z, avg_rms, last_T1, last_PD) ;
#if 0
      if (z > 0 && z*width*height - ignored > 0) {
        int processed = z*width*height - ignored, hours ;

        msec = TimerStop(&first_slice) ;
        seconds = nint((float)msec/1000.0f) ;
        minutes = seconds / 60 ;
        seconds = seconds % 60 ;
        hours = minutes / 60 ;
        minutes = minutes % 60 ;
        printf("%02d:%02d:%02d total processing time ... ",
               hours,minutes,seconds);
        msec = (int)((float)(total_vox-ignored)*msec/(float)processed) ;
        seconds = nint((float)msec/1000.0f) ;
        minutes = seconds / 60 ;
        seconds = seconds % 60 ;
        hours = minutes / 60 ;
        minutes = minutes % 60 ;
        printf("estimate %02d:%02d:%02d remaining.\n", hours,minutes, seconds);
      }
#endif
      if (write_iterations > 0 && z > 0 && !(z%write_iterations)) {
        printf("writing T1 esimates to %s...\n", out_T1_fname) ;
        printf("writing PD estimates to %s...\n", out_PD_fname) ;
        MRIwrite(mri_T1, out_T1_fname) ;
        MRIwrite(mri_PD, out_PD_fname) ;
        printf("writing residuals to %s...\n", residual_name) ;
        if (residual_name) {
          MRI *mri_res, *mri_res_total = NULL ;
          for (i = 0 ; i < nvolumes ; i++) {

            mri_res = compute_residuals(mri_flash[i], mri_T1, mri_PD) ;
            sprintf(fname, "%s%d.mgh", residual_name, i) ;
#if 0
            MRIwrite(mri_res, fname) ;
#endif
            if (!mri_res_total) {
              mri_res_total = MRIcopy(mri_res, NULL) ;
            } else {
              MRIsadd(mri_res, mri_res_total, mri_res_total) ;
            }

            MRIfree(&mri_res) ;
          }
          MRIsscalarMul(mri_res_total, mri_res_total, 1.0/(float)nvolumes) ;
          MRIssqrt(mri_res_total, mri_res_total) ;
          sprintf(fname, "%s.mgh", residual_name) ;
          MRIwrite(mri_res_total, fname) ;
        }
      }

      nvox = 0 ;
      total_rms = 0 ;
      for (y = 0 ; y < height ; y++) {
#if 0
        if (y%32 == 0 && nvox > 0)
          printf("z = %d, y = %d, avg rms=%2.1f, T1=%2.0f, PD=%2.0f...\n",
                 z, y, total_rms/(double)nvox, last_T1, last_PD) ;
#endif
        for (x = 0 ; x < width ; x++) {
#if 0
          for (i = 0 ; i < nvolumes ; i++)
            if (MRISvox(mri_flash[i],x,y,z) > thresh)
              break ;
          if (i >= nvolumes)
#else
          if (no_valid_data(mri_flash, nvolumes, x, y, z, thresh))
#endif
          {
            ignored++ ;
            MRISvox(mri_T1, x, y, z) = MRISvox(mri_PD, x, y, z) = 0 ;
            /*            last_T1 = last_PD = 1000 ;*/
            continue ;
          }
#if 0
          sse = findInitialParameters(mri_flash, nvolumes, x, y, z,
                                      last_PD-1000, last_PD+1000,
                                      last_T1-1000, last_T1+1000,
                                      &last_PD, &last_T1, 10) ;
#endif
#if 0
          sse = findInitialParameters(mri_flash, nvolumes, x, y, z,
                                      last_PD-100, last_PD+100,
                                      last_T1-100, last_T1+100,
                                      &last_PD, &last_T1, 10) ;
          if (last_T1 <= MIN_T1 || last_PD <= 0) {
            ignored++ ;
            MRISvox(mri_T1, x, y, z) = MRISvox(mri_PD, x, y, z) = 0 ;
            /*            last_T1 = last_PD = 1000 ;*/
            continue ;
          }
#endif
          sse = estimateVoxelParameters(mri_flash, nvolumes, x, y, z,
                                        mri_T1, mri_PD, nsteps) ;
          nvox++ ;
          last_T1 = MRISvox(mri_T1, x, y, z) ;
          last_PD = MRISvox(mri_PD, x, y, z) ;
          total_rms += sqrt(sse/nvolumes) ;
          if (!finite(total_rms))
            DiagBreak() ;
        }
      }
      avg_rms = total_rms / nvox ;
      if (!finite(avg_rms))
        DiagBreak() ;
    }
  }


  printf("writing T1 esimates to %s...\n", out_T1_fname) ;
  printf("writing PD estimates to %s...\n", out_PD_fname) ;
  MRIwrite(mri_T1, out_T1_fname) ;
  MRIwrite(mri_PD, out_PD_fname) ;
  if (residual_name) {
    MRI *mri_res_total = NULL ;

    for (i = 0 ; i < nvolumes ; i++) {
      MRI *mri_res ;

      mri_res = compute_residuals(mri_flash[i], mri_T1, mri_PD) ;
#if 0
      sprintf(fname, "%s%d.mgh", residual_name, i) ;
      MRIwrite(mri_res, fname) ;
#endif
      if (!mri_res_total) {
        mri_res_total = MRIcopy(mri_res, NULL) ;
      } else {
        MRIsadd(mri_res, mri_res_total, mri_res_total) ;
      }
      MRIfree(&mri_res) ;
    }
    MRIsscalarMul(mri_res_total, mri_res_total, 1.0/(float)nvolumes) ;
    MRIssqrt(mri_res_total, mri_res_total) ;
    sprintf(fname, "%s.mgh", residual_name) ;
    MRIwrite(mri_res_total, fname) ;
  }
  MRIfree(&mri_T1) ;
  MRIfree(&mri_PD) ;
  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  printf("parameter estimation took %d minutes and %d seconds.\n",
         minutes, seconds) ;
  exit(0) ;
  return(0) ;
}
コード例 #16
0
ファイル: mri_synthesize.c プロジェクト: ewong718/freesurfer
int
main(int argc, char *argv[]) {
  char        **av, *out_fname, *T1_fname, *PD_fname ;
  int         ac, nargs ;
  MRI         *mri_T1, *mri_PD, *mri_out, *mri_T2star = NULL ;
  float       TR, TE, alpha ;

  char cmdline[CMD_LINE_LEN] ;

  make_cmd_version_string (argc, argv, "$Id: mri_synthesize.c,v 1.18 2011/03/02 00:04:25 nicks Exp $", "$Name:  $", cmdline);

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mri_synthesize.c,v 1.18 2011/03/02 00:04:25 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 < 7)
    usage_exit() ;

  TR = atof(argv[1]) ;
  alpha = atof(argv[2]) ;
  TE = atof(argv[3]) ;
  T1_fname = argv[4] ;
  PD_fname = argv[5] ;
  out_fname = argv[6] ;

  printf("reading T1 volume from %s...\n", T1_fname) ;
  mri_T1 = MRIread(T1_fname) ;
  if (!mri_T1)
    ErrorExit(ERROR_NOFILE, "%s: could not read T1 volume %s", Progname,
              T1_fname) ;
  if (extract) {
    MRI *mri_tmp ;
    int dx, dy, dz ;

    dx = mri_T1->width/2 ;
    dy = mri_T1->height/2 ;
    dz = mri_T1->depth/2 ;
    printf("extracting interior %dx%dx%d\n", dx, dy, dz) ;
    mri_tmp = MRIextract(mri_T1, NULL, dx/2, dy/2, dz/2, dx, dy, dz) ;
    MRIfree(&mri_T1) ;
    mri_T1 = mri_tmp ;
  }
  if (jpdf_name) {
    transform_T1_values_using_joint_pdf(mri_T1, jpdf_name, invert) ;
  }

  printf("reading PD volume from %s...\n", PD_fname) ;
  mri_PD = MRIread(PD_fname) ;
  if (!mri_PD)
    ErrorExit(ERROR_NOFILE, "%s: could not read PD volume %s", Progname,
              PD_fname) ;

  if (T2star_fname != NULL) {
    printf("reading T2* volume from %s...\n", T2star_fname) ;
    mri_T2star = MRIread(T2star_fname) ;
    if (!mri_T2star)
      ErrorExit(ERROR_NOFILE, "%s: could not read T2* volume %s", Progname,
                T2star_fname) ;
  }

  if (PDsat > 0)
    saturate_PD(mri_PD, PDsat) ;
  if (extract) {
    MRI *mri_tmp ;
    int dx, dy, dz ;

    dx = mri_PD->width/2 ;
    dy = mri_PD->height/2 ;
    dz = mri_PD->depth/2 ;
    mri_tmp = MRIextract(mri_PD, NULL, dx/2, dy/2, dz/2, dx, dy, dz) ;
    MRIfree(&mri_PD) ;
    mri_PD = mri_tmp ;
  }
  if (use_weighting) {
    mri_out = MRIsynthesizeWeightedVolume(mri_T1, mri_PD, w5, TR, w30, TR, 110,TE);
  } else {
    printf("synthesizing volume with TR=%2.1f msec, TE=%2.1f msec, and alpha=%2.2f degrees...\n",
           TR, TE, alpha) ;
    if (normalize)
      normalize_PD(mri_PD, 1000) ;
    if (discard)
      discard_PD(mri_PD, 250, 1500) ;
    if (nl_remap_T1)
      remap_T1(mri_T1, nl_mean, nl_scale) ;
    if (nfaf > 0)
      mri_out = MRIsynthesizeWithFAF(mri_T1, mri_PD, NULL, TR, RADIANS(alpha), TE, nfaf, faf_coefs) ;
    else
      mri_out = MRIsynthesize(mri_T1, mri_PD, mri_T2star, NULL, TR, RADIANS(alpha), TE) ;
  }

  if (nbias > 0)
    apply_bias_field(mri_out, nbias, bias_coefs) ;
  printf("writing output to %s.\n", out_fname) ;
  MRIaddCommandLine(mri_out, cmdline) ;
  MRIwrite(mri_out, out_fname) ;

  exit(0) ;
  return(0) ;  /* for ansi */
}
コード例 #17
0
ファイル: mri_concat.c プロジェクト: guo2004131/freesurfer
/*--------------------------------------------------*/
int main(int argc, char **argv)
{
  int nargs, nthin, nframestot=0, nr=0,nc=0,ns=0, fout;
  int r,c,s,f,outf,nframes,err,nthrep;
  double v, v1, v2, vavg, vsum;
  int inputDatatype=MRI_UCHAR;
  MATRIX *Upca=NULL,*Spca=NULL;
  MRI *Vpca=NULL;
  char *stem;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, vcid, "$Name: stable5 $");
  if (nargs && argc - nargs == 1)
  {
    exit (0);
  }
  argc -= nargs;

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

  if (argc == 0)
  {
    usage_exit();
  }

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

  if(maskfile)
  {
    printf("Loading mask %s\n",maskfile);
    mask = MRIread(maskfile);
    if(mask == NULL)
    {
      exit(1);
    }
  }

  printf("ninputs = %d\n",ninputs);
  if(DoCheck)
  {
    printf("Checking inputs\n");
    for(nthin = 0; nthin < ninputs; nthin++)
    {
      if(Gdiag_no > 0 || debug)
      {
        printf("Checking %2d %s\n",nthin,inlist[nthin]);
        fflush(stdout);
      }
      mritmp = MRIreadHeader(inlist[nthin],MRI_VOLUME_TYPE_UNKNOWN);
      if (mritmp == NULL)
      {
        printf("ERROR: reading %s\n",inlist[nthin]);
        exit(1);
      }
      if (nthin == 0)
      {
        nc = mritmp->width;
        nr = mritmp->height;
        ns = mritmp->depth;
      }
      if (mritmp->width != nc ||
          mritmp->height != nr ||
          mritmp->depth != ns)
      {
        printf("ERROR: dimension mismatch between %s and %s\n",
               inlist[0],inlist[nthin]);
        exit(1);
      }

      nframestot += mritmp->nframes;
      inputDatatype = mritmp->type; // used by DoKeepDatatype option
      MRIfree(&mritmp);
    }
  }
  else
  {
    printf("NOT Checking inputs, assuming nframestot = ninputs\n");
    nframestot = ninputs;
    mritmp = MRIreadHeader(inlist[0],MRI_VOLUME_TYPE_UNKNOWN);
    if (mritmp == NULL)
    {
      printf("ERROR: reading %s\n",inlist[0]);
      exit(1);
    }
    nc = mritmp->width;
    nr = mritmp->height;
    ns = mritmp->depth;
    MRIfree(&mritmp);
  }

  printf("nframestot = %d\n",nframestot);

  if (DoRMS)
  {
    if (ninputs != 1)
    {
      printf("ERROR: --rms supports only single input w/ multiple frames\n");
      exit (1);
    }
    if (nframestot == 1)
    {
      printf("ERROR: --rms input must have multiple frames\n");
      exit (1);
    }
  }

  if(ngroups != 0)
  {
    printf("Creating grouped mean matrix ngroups=%d, nper=%d\n",
           ngroups,nframestot/ngroups);
    M = GroupedMeanMatrix(ngroups,nframestot);
    if(M==NULL)
    {
      exit(1);
    }
    if(debug)
    {
      MatrixPrint(stdout,M);
    }
  }

  if(M != NULL)
  {
    if(nframestot != M->cols)
    {
      printf("ERROR: dimension mismatch between inputs (%d) and matrix (%d)\n",
             nframestot,M->rows);
      exit(1);
    }
  }

  if (DoPaired)
  {
    if (remainder(nframestot,2) != 0)
    {
      printf("ERROR: --paired-xxx specified but there are an "
             "odd number of frames\n");
      exit(1);
    }
  }

  printf("Allocing output\n");
  fflush(stdout);
  int datatype=MRI_FLOAT;
  if (DoKeepDatatype)
  {
    datatype = inputDatatype;
  }
  if (DoRMS)
  {
    // RMS always has single frame output
    mriout = MRIallocSequence(nc,nr,ns,datatype,1);
  }
  else
  {
    mriout = MRIallocSequence(nc,nr,ns,datatype,nframestot);
  }
  if (mriout == NULL)
  {
    exit(1);
  }
  printf("Done allocing\n");

  fout = 0;
  for (nthin = 0; nthin < ninputs; nthin++)
  {
    if (DoRMS) break; // MRIrms reads the input frames
    if(Gdiag_no > 0 || debug)
    {
      printf("Loading %dth input %s\n",
             nthin+1,fio_basename(inlist[nthin],NULL));
      fflush(stdout);
    }
    mritmp = MRIread(inlist[nthin]);
    if(mritmp == NULL)
    {
      printf("ERROR: loading %s\n",inlist[nthin]);
      exit(1);
    }
    if(nthin == 0)
    {
      MRIcopyHeader(mritmp, mriout);
      //mriout->nframes = nframestot;
    }
    if(DoAbs)
    {
      if(Gdiag_no > 0 || debug)
      {
        printf("Removing sign from input\n");
      }
      MRIabs(mritmp,mritmp);
    }
    if(DoPos)
    {
      if(Gdiag_no > 0 || debug)
      {
        printf("Setting input negatives to 0.\n");
      }
      MRIpos(mritmp,mritmp);
    }
    if(DoNeg)
    {
      if(Gdiag_no > 0 || debug)
      {
        printf("Setting input positives to 0.\n");
      }
      MRIneg(mritmp,mritmp);
    }
    for(f=0; f < mritmp->nframes; f++)
    {
      for(c=0; c < nc; c++)
      {
        for(r=0; r < nr; r++)
        {
          for(s=0; s < ns; s++)
          {
            v = MRIgetVoxVal(mritmp,c,r,s,f);
            MRIsetVoxVal(mriout,c,r,s,fout,v);
          }
        }
      }
      fout++;
    }
    MRIfree(&mritmp);
  }

  if(DoCombine)
  {
    // Average frames from non-zero voxels
    int nhits;
    mritmp = MRIallocSequence(nc,nr,ns,MRI_FLOAT,1);
    MRIcopyHeader(mritmp,mriout);
    for(c=0; c < nc; c++)
    {
      for(r=0; r < nr; r++)
      {
        for(s=0; s < ns; s++)
        {
          nhits = 0;
          vsum = 0;
          for(f=0; f < mriout->nframes; f++)
          {
            v = MRIgetVoxVal(mriout,c,r,s,f);
            if (v > 0)
            {
              vsum += v;
              nhits ++;
            }
          }
          if(nhits > 0 )
          {
            MRIsetVoxVal(mritmp,c,r,s,0,vsum/nhits);
          }
        } // for s
      }// for r
    } // for c
    MRIfree(&mriout);
    mriout = mritmp;
  } // do combine

  if(DoPrune)
  {
    // This computes the prune mask, applied below
    printf("Computing prune mask \n");
    PruneMask = MRIframeBinarize(mriout,FLT_MIN,NULL);
    printf("Found %d voxels in prune mask\n",MRInMask(PruneMask));
  }

  if(DoNormMean)
  {
    printf("Normalizing by mean across frames\n");
    MRInormalizeFramesMean(mriout);
  }
  if(DoNorm1)
  {
    printf("Normalizing by first across frames\n");
    MRInormalizeFramesFirst(mriout);
  }

  if(DoASL)
  {
    printf("Computing ASL matrix matrix\n");
    M = ASLinterpMatrix(mriout->nframes);
  }

  if(M != NULL)
  {
    printf("Multiplying by matrix\n");
    mritmp = fMRImatrixMultiply(mriout, M, NULL);
    if(mritmp == NULL)
    {
      exit(1);
    }
    MRIfree(&mriout);
    mriout = mritmp;
  }

  if(DoPaired)
  {
    printf("Combining pairs\n");
    mritmp = MRIcloneBySpace(mriout,-1,mriout->nframes/2);
    for (c=0; c < nc; c++)
    {
      for (r=0; r < nr; r++)
      {
        for (s=0; s < ns; s++)
        {
          fout = 0;
          for (f=0; f < mriout->nframes; f+=2)
          {
            v1 = MRIgetVoxVal(mriout,c,r,s,f);
            v2 = MRIgetVoxVal(mriout,c,r,s,f+1);
            v = 0;
            if(DoPairedAvg)
            {
              v = (v1+v2)/2.0;
            }
            if(DoPairedSum)
            {
              v = (v1+v2);
            }
            if(DoPairedDiff)
            {
              v = v1-v2;  // difference
            }
            if(DoPairedDiffNorm)
            {
              v = v1-v2; // difference
              vavg = (v1+v2)/2.0;
              if (vavg != 0.0)
              {
                v = v/vavg;
              }
            }
            if(DoPairedDiffNorm1)
            {
              v = v1-v2; // difference
              if (v1 != 0.0)
              {
                v = v/v1;
              }
              else
              {
                v = 0;
              }
            }
            if(DoPairedDiffNorm2)
            {
              v = v1-v2; // difference
              if (v2 != 0.0)
              {
                v = v/v2;
              }
              else
              {
                v = 0;
              }
            }
            MRIsetVoxVal(mritmp,c,r,s,fout,v);
            fout++;
          }
        }
      }
    }
    MRIfree(&mriout);
    mriout = mritmp;
  }
  nframes = mriout->nframes;
  printf("nframes = %d\n",nframes);

  if(DoBonfCor)
  {
    DoAdd = 1;
    AddVal = -log10(mriout->nframes);
  }

  if(DoMean)
  {
    printf("Computing mean across frames\n");
    mritmp = MRIframeMean(mriout,NULL);
    MRIfree(&mriout);
    mriout = mritmp;
  }
  if(DoMedian)
  {
    printf("Computing median across frames\n");
    mritmp = MRIframeMedian(mriout,NULL);
    MRIfree(&mriout);
    mriout = mritmp;
  }
  if(DoMeanDivN)
  {
    printf("Computing mean2 = sum/(nframes^2)\n");
    mritmp = MRIframeSum(mriout,NULL);
    MRIfree(&mriout);
    mriout = mritmp;
    MRImultiplyConst(mriout, 1.0/(nframes*nframes), mriout);
  }
  if(DoSum)
  {
    printf("Computing sum across frames\n");
    mritmp = MRIframeSum(mriout,NULL);
    MRIfree(&mriout);
    mriout = mritmp;
  }
  if(DoTAR1)
  {
    printf("Computing temoral AR1 %d\n",mriout->nframes-TAR1DOFAdjust);
    mritmp = fMRItemporalAR1(mriout,TAR1DOFAdjust,NULL,NULL);
    MRIfree(&mriout);
    mriout = mritmp;
  }

  if(DoStd || DoVar)
  {
    printf("Computing std/var across frames\n");
    if(mriout->nframes < 2)
    {
      printf("ERROR: cannot compute std from one frame\n");
      exit(1);
    }
    //mritmp = fMRIvariance(mriout, -1, 1, NULL);
    mritmp = fMRIcovariance(mriout, 0, -1, NULL, NULL);
    if(DoStd)
    {
      MRIsqrt(mritmp, mritmp);
    }
    MRIfree(&mriout);
    mriout = mritmp;
  }

  if(DoMax)
  {
    printf("Computing max across all frames \n");
    mritmp = MRIvolMax(mriout,NULL);
    MRIfree(&mriout);
    mriout = mritmp;
  }

  if(DoMaxIndex)
  {
    printf("Computing max index across all frames \n");
    mritmp = MRIvolMaxIndex(mriout,1,NULL,NULL);
    MRIfree(&mriout);
    mriout = mritmp;
  }

  if(DoConjunction)
  {
    printf("Computing conjunction across all frames \n");
    mritmp = MRIconjunct(mriout,NULL);
    MRIfree(&mriout);
    mriout = mritmp;
  }

  if(DoMin)
  {
    printf("Computing min across all frames \n");
    mritmp = MRIvolMin(mriout,NULL);
    MRIfree(&mriout);
    mriout = mritmp;
  }

  if(DoSort)
  {
    printf("Sorting \n");
    mritmp = MRIsort(mriout,mask,NULL);
    MRIfree(&mriout);
    mriout = mritmp;
  }

  if(DoVote)
  {
    printf("Voting \n");
    mritmp = MRIvote(mriout,mask,NULL);
    MRIfree(&mriout);
    mriout = mritmp;
  }

  if(DoMultiply)
  {
    printf("Multiplying by %lf\n",MultiplyVal);
    MRImultiplyConst(mriout, MultiplyVal, mriout);
  }

  if(DoAdd)
  {
    printf("Adding %lf\n",AddVal);
    MRIaddConst(mriout, AddVal, mriout);
  }

  if(DoSCM)
  {
    printf("Computing spatial correlation matrix (%d)\n",mriout->nframes);
    mritmp = fMRIspatialCorMatrix(mriout);
    if(mritmp == NULL)
    {
      exit(1);
    }
    MRIfree(&mriout);
    mriout = mritmp;
  }

  if(DoPCA)
  {
    // Saves only non-zero components
    printf("Computing PCA\n");
    if(PCAMaskFile)
    {
      printf("  PCA Mask %s\n",PCAMaskFile);
      PCAMask = MRIread(PCAMaskFile);
      if(PCAMask == NULL)
      {
        exit(1);
      }
    }
    err=MRIpca(mriout, &Upca, &Spca, &Vpca, PCAMask);
    if(err)
    {
      exit(1);
    }
    stem = IDstemFromName(out);
    sprintf(tmpstr,"%s.u.mtx",stem);
    MatrixWriteTxt(tmpstr, Upca);
    sprintf(tmpstr,"%s.stats.dat",stem);
    WritePCAStats(tmpstr,Spca);
    MRIfree(&mriout);
    mriout = Vpca;
  }

  if(NReplications > 0)
  {
    printf("NReplications %d\n",NReplications);
    mritmp = MRIallocSequence(mriout->width,
                              mriout->height,
                              mriout->depth,
                              mriout->type,
                              mriout->nframes*NReplications);
    if(mritmp == NULL)
    {
      exit(1);
    }
    printf("Done allocing\n");
    MRIcopyHeader(mriout,mritmp);
    for(c=0; c < mriout->width; c++)
    {
      for(r=0; r < mriout->height; r++)
      {
        for(s=0; s < mriout->depth; s++)
        {
          outf = 0;
          for(nthrep = 0; nthrep < NReplications; nthrep++)
          {
            for(f=0; f < mriout->nframes; f++)
            {
              v = MRIgetVoxVal(mriout,c,r,s,f);
              MRIsetVoxVal(mritmp,c,r,s,outf,v);
              outf ++;
            }
          }
        }
      }
    }
    MRIfree(&mriout);
    mriout = mritmp;
  }

  if(DoPrune)
  {
    // Apply prune mask that was computed above
    printf("Applying prune mask \n");
    MRImask(mriout, PruneMask, mriout, 0, 0);
  }

  if(DoRMS)
  {
    printf("Computing RMS across input frames\n");
    mritmp = MRIread(inlist[0]);
    MRIcopyHeader(mritmp, mriout);
    MRIrms(mritmp,mriout);
  }

  printf("Writing to %s\n",out);
  err = MRIwrite(mriout,out);
  if(err)
  {
    exit(err);
  }

  return(0);
}
コード例 #18
0
int
main(int argc, char *argv[]) {
  char   **av, fname[STRLEN] ;
  int    ac, nargs ;
  char   *reg_fname, *in_fname, *out_stem, *cp ;
  int    msec, minutes, seconds, nvox, float2int ;
  struct timeb start ;
  MRI_SURFACE *mris_lh_white, *mris_rh_white, *mris_lh_pial, *mris_rh_pial ;
  MRI         *mri_aseg, *mri_seg, *mri_pial, *mri_tmp, *mri_ribbon, *mri_in, *mri_cortex, 
    *mri_subcort_gm, *mri_wm, *mri_csf ;
  MATRIX      *m_regdat ;
  float       intensity, betplaneres, inplaneres ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mri_compute_volume_fractions.c,v 1.9 2012/11/07 18:58:02 greve Exp $", "$Name:  $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  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) ;
  if (!strlen(sdir)) {
    cp = getenv("SUBJECTS_DIR") ;
    if (!cp)
      ErrorExit(ERROR_BADPARM,
                "%s: SUBJECTS_DIR not defined in environment.\n", Progname) ;
    strcpy(sdir, cp) ;
  }
  reg_fname = argv[1] ; in_fname = argv[2] ;
  out_stem = argv[3] ; Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  TimerStart(&start) ;

  if (stricmp(reg_fname, "identity.nofile") == 0)
  {
    printf("using identity transform\n") ;
    m_regdat = NULL ;
    inplaneres = betplaneres = intensity = 1 ;
    float2int = 0 ;
    if (subject == NULL)
      subject = "unknown" ;
  }
  else
  {
    char *saved_subject = subject ;
    printf("reading registration file %s\n", reg_fname) ;
    regio_read_register(reg_fname, &subject, &inplaneres,
                        &betplaneres, &intensity,  &m_regdat,
                        &float2int);
    
    if (saved_subject)  // specified on cmdline
      subject = saved_subject ;
    m_regdat = regio_read_registermat(reg_fname) ;
    if (m_regdat == NULL)
      ErrorExit(ERROR_NOFILE, "%s: could not load registration file from %s", Progname,reg_fname) ;
  }
  printf("Format is %s\n",fmt);
    
  sprintf(fname, "%s/%s/surf/lh.white", sdir, subject) ;
  printf("reading surface %s\n", fname) ;
  mris_lh_white = MRISread(fname) ;
  if (mris_lh_white == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not load lh white surface from %s", Progname,fname) ;

  sprintf(fname, "%s/%s/surf/rh.white", sdir, subject) ;
  printf("reading surface %s\n", fname) ;
  mris_rh_white = MRISread(fname) ;
  if (mris_rh_white == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not load rh white surface from %s", Progname,fname) ;

  sprintf(fname, "%s/%s/surf/lh.pial", sdir, subject) ;
  printf("reading surface %s\n", fname) ;
  mris_lh_pial = MRISread(fname) ;
  if (mris_lh_pial == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not load lh pial surface from %s", Progname,fname) ;

  sprintf(fname, "%s/%s/surf/rh.pial", sdir, subject) ;
  printf("reading surface %s\n", fname) ;
  mris_rh_pial = MRISread(fname) ;
  if (mris_rh_pial == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not load rh pial surface from %s", Progname,fname) ;

  sprintf(fname, "%s/%s/mri/aseg.mgz", sdir, subject) ;
  printf("reading volume %s\n", fname) ;
  mri_aseg = MRIread(fname) ;
  if (mri_aseg == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not load aseg volume from %s", Progname,fname) ;

  printf("reading movable volume %s\n", in_fname) ;
  mri_in = MRIread(in_fname) ;
  if (mri_in == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not load input volume from %s", Progname,in_fname) ;
 
  nvox = (int)ceil(256/resolution); 
  mri_pial = MRIalloc(nvox, nvox, nvox, MRI_UCHAR) ;
  MRIsetResolution(mri_pial, resolution, resolution, resolution) ;

  mri_pial->xstart = -resolution*mri_pial->width/2.0 ;
  mri_pial->xend = resolution*mri_pial->width/2.0 ;
  mri_pial->ystart = -resolution*mri_pial->height/2.0 ;
  mri_pial->yend = resolution*mri_pial->height/2.0 ;
  mri_pial->zstart = -resolution*mri_pial->depth/2.0 ;
  mri_pial->zend = resolution*mri_pial->depth/2 ;
  mri_pial->c_r = mri_aseg->c_r ; mri_pial->c_a = mri_aseg->c_a ; mri_pial->c_s = mri_aseg->c_s ;
  MRIreInitCache(mri_pial) ; 

  printf("filling interior of lh pial surface...\n") ;
  MRISfillInterior(mris_lh_pial, resolution, mri_pial) ;
  mri_seg = MRIclone(mri_pial, NULL) ;
  mri_tmp = MRIclone(mri_pial, NULL) ;
  printf("filling interior of rh pial surface...\n") ;
  MRISfillInterior(mris_rh_pial, resolution, mri_tmp) ;
  MRIcopyLabel(mri_tmp, mri_pial, 1) ;
  MRIclear(mri_tmp) ;
  printf("filling interior of lh white matter surface...\n") ;
  MRISfillWhiteMatterInterior(mris_lh_white, mri_aseg, mri_seg, resolution,
                              WM_VAL, SUBCORT_GM_VAL, CSF_VAL);
  printf("filling interior of rh white matter surface...\n") ;
  MRISfillWhiteMatterInterior(mris_rh_white, mri_aseg, mri_tmp, resolution,
                              WM_VAL, SUBCORT_GM_VAL, CSF_VAL);
  MRIcopyLabel(mri_tmp, mri_seg, WM_VAL) ;
  MRIcopyLabel(mri_tmp, mri_seg, SUBCORT_GM_VAL) ;
  MRIcopyLabel(mri_tmp, mri_seg, CSF_VAL) ;
  MRIfree(&mri_tmp) ;
  
  mri_ribbon = MRInot(mri_seg, NULL) ;
  MRIcopyLabel(mri_seg, mri_pial, CSF_VAL) ;
  MRIreplaceValuesOnly(mri_pial, mri_pial, CSF_VAL, 0) ;
  MRIand(mri_ribbon, mri_pial, mri_ribbon, 1) ;
  MRIbinarize(mri_ribbon, mri_ribbon, 1, 0, GM_VAL) ;
  MRIcopyLabel(mri_ribbon, mri_seg, GM_VAL) ;
  MRIreplaceValuesOnly(mri_seg, mri_seg, CSF_VAL, 0) ;
  add_aseg_structures_outside_ribbon(mri_seg, mri_aseg, mri_seg, WM_VAL, SUBCORT_GM_VAL, CSF_VAL) ;


  {
    MATRIX *m_conformed_to_epi_vox2vox, *m_seg_to_conformed_vox2vox,
           *m_seg_to_epi_vox2vox ;

    if (m_regdat == NULL)    // assume identity transform
      m_seg_to_epi_vox2vox = MRIgetVoxelToVoxelXform(mri_seg, mri_in) ;
    else
    {
      m_conformed_to_epi_vox2vox = MRIvoxToVoxFromTkRegMtx(mri_in, mri_aseg, m_regdat);
      m_seg_to_conformed_vox2vox = MRIgetVoxelToVoxelXform(mri_seg, mri_aseg) ;
      
      m_seg_to_epi_vox2vox = MatrixMultiply(m_conformed_to_epi_vox2vox, m_seg_to_conformed_vox2vox, NULL) ;
      MatrixFree(&m_regdat) ; MatrixFree(&m_conformed_to_epi_vox2vox) ; 
      MatrixFree(&m_seg_to_conformed_vox2vox);

    }
    printf("seg to EPI vox2vox matrix:\n") ;
    MatrixPrint(Gstdout, m_seg_to_epi_vox2vox) ;
    mri_cortex = MRIalloc(mri_in->width, mri_in->height, mri_in->depth, MRI_FLOAT) ;
    MRIcopyHeader(mri_in, mri_cortex) ;
    mri_subcort_gm = MRIclone(mri_cortex, NULL) ;
    mri_wm = MRIclone(mri_cortex, NULL) ;
    mri_csf = MRIclone(mri_cortex, NULL) ;
    printf("computing partial volume fractions...\n") ;
    MRIcomputePartialVolumeFractions(mri_in, m_seg_to_epi_vox2vox, mri_seg, mri_wm, mri_subcort_gm, mri_cortex, mri_csf,
                                     WM_VAL, SUBCORT_GM_VAL, GM_VAL, 0) ;
  }
  
  sprintf(fname, "%s.wm.%s", out_stem,fmt) ;
  printf("writing wm %% to %s\n", fname) ;
  MRIwrite(mri_wm, fname) ;

  sprintf(fname, "%s.subcort_gm.%s", out_stem,fmt) ;
  printf("writing subcortical gm %% to %s\n", fname) ;
  MRIwrite(mri_subcort_gm, fname) ;

  sprintf(fname, "%s.cortex.%s", out_stem, fmt) ;
  printf("writing cortical gm %% to %s\n", fname) ;
  MRIwrite(mri_cortex, fname) ;
  
  sprintf(fname, "%s.csf.%s", out_stem,fmt) ;
  printf("writing csf %% to %s\n", fname) ;
  MRIwrite(mri_csf, fname) ;

  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  printf("volume fraction calculation took %d minutes"
          " and %d seconds.\n", minutes, seconds) ;
  exit(0) ;
  return(0) ;
}
コード例 #19
0
ファイル: mri_gcut.cpp プロジェクト: guo2004131/freesurfer
/*-------------------------------------------------------------*/
int main(int argc, char *argv[])
{
  /* check for and handle version tag */
  int nargs = handle_version_option
              (argc, argv,
               "$Id: mri_gcut.cpp,v 1.14 2011/03/02 00:04:16 nicks Exp $",
               "$Name: stable5 $");
  if (nargs && argc - nargs == 1)
  {
    exit (0);
  }
  argc -= nargs;

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

  parse_commandline(argc, argv);

  MRI *mri, *mri2, *mri3, *mri_mask=NULL;
  mri3  = MRIread(in_filename);
  if ( mri3 == NULL )
  {
    printf("can't read file %s\nexit!\n", in_filename);
    exit(0);
  }
  mri   = MRISeqchangeType(mri3, MRI_UCHAR, 0.0, 0.999, FALSE);
  mri2  = MRISeqchangeType(mri3, MRI_UCHAR, 0.0, 0.999, FALSE);
  //MRI* mri4 = MRIread("gcutted.mgz");

  if (bNeedMasking == 1)
  {
    printf("reading mask...\n");
    mri_mask = MRIread(mask_filename);
    if ( mri_mask == NULL )
    {
      printf("can't read %s, omit -mult option!\n", mask_filename);
      print_help();
      exit(1);
    }
    else
    {
      if ( mri_mask->width != mri->width ||
           mri_mask->height != mri->height ||
           mri_mask->depth != mri->depth )
      {
        printf("Two masks are of different size, omit -mult option!\n");
        print_help();
        exit(1);
      }
    }
  }

  int w = mri->width;
  int h = mri->height;
  int d = mri->depth;

  // -- copy of mri matrix
  unsigned char ***label;
  label = new unsigned char**[d];
  for (int i = 0; i < d; i++)
  {
    label[i] = new unsigned char*[h];
    for (int j = 0; j < h; j++)
    {
      label[i][j] = new unsigned char[w];
      for (int k = 0; k < w; k++)
      {
        label[i][j][k] = 0;
      }
    }
  }
  // -- gcut image
  int ***im_gcut;
  im_gcut = new int**[d];
  for (int i = 0; i < d; i++)
  {
    im_gcut[i] = new int*[h];
    for (int j = 0; j < h; j++)
    {
      im_gcut[i][j] = new int[w];
      for (int k = 0; k < w; k++)
      {
        im_gcut[i][j][k] = 0;
      }
    }
  }
  // -- diluted
  int ***im_diluteerode;
  im_diluteerode = new int**[d];
  for (int i = 0; i < d; i++)
  {
    im_diluteerode[i] = new int*[h];
    for (int j = 0; j < h; j++)
    {
      im_diluteerode[i][j] = new int[w];
      for (int k = 0; k < w; k++)
      {
        im_diluteerode[i][j][k] = 0;
      }
    }
  }
  //int w, h, d;
  //int x, y, z;
  double whitemean;
  if (bNeedPreprocessing == 0)
  {
    // pre-processed: 110 intensity voxels are the WM
    if (LCC_function(mri ->slices,
                     label,
                     mri->width,
                     mri->height,
                     mri->depth,
                     whitemean) == 1)
    {
      if ( whitemean < 0 )
      {
        printf("whitemean < 0 error!\n");
        exit(0);
      }
    }
    else
    {
      whitemean = 110;
      printf("use voxels with intensity 110 as WM mask\n");
    }
  }
  else
  {
    printf("estimating WM mask\n");
    whitemean = pre_processing(mri ->slices,
                               label,
                               mri->width,
                               mri->height,
                               mri->depth);
    if ( whitemean < 0 )
    {
      printf("whitemean < 0 error!\n");
      exit(0);
    }
  }
  double threshold = whitemean * _t;
  printf("threshold set to: %f*%f=%f\n", whitemean, _t, threshold);

  for (int z = 0 ; z < mri->depth ; z++)
  {
    for (int y = 0 ; y < mri->height ; y++)
    {
      for (int x = 0 ; x < mri->width ; x++)
      {
        if ( mri->slices[z][y][x] < threshold + 1 )
        {
          mri->slices[z][y][x] = 0;
        }
      }
    }//end of for
  }

  //new code
  int ***foregroundseedwt;
  int ***backgroundseedwt;
  matrix_alloc(&foregroundseedwt, d, h, w);
  matrix_alloc(&backgroundseedwt, d, h, w);

  double kval = 2.3;
  graphcut(mri->slices, label, im_gcut,
           foregroundseedwt, backgroundseedwt,
           w, h, d, kval, threshold, whitemean);
  printf("g-cut done!\npost-processing...\n");
  //printf("_test: %f\n", _test);

  post_processing(mri2->slices,
                  mri->slices,
                  threshold,
                  im_gcut,
                  im_diluteerode,
                  w, h, d);
  printf("post-processing done!\n");

  if (bNeedMasking == 1)//masking
  {
    printf("masking...\n");
    for (int z = 0 ; z < mri_mask->depth ; z++)
    {
      for (int y = 0 ; y < mri_mask->height ; y++)
      {
        for (int x = 0 ; x < mri_mask->width ; x++)
        {
          if ( mri_mask->slices[z][y][x] == 0 )
          {
            im_diluteerode[z][y][x] = 0;
          }
        }
      }
    }
  }

  //if the output might have some problem
  int numGcut = 0, numMask = 0;
  double _ratio = 0;
  int error_Hurestic = 0;
  if (bNeedMasking == 1)//-110 and masking are both set
  {
    for (int z = 0 ; z < mri_mask->depth ; z++)
    {
      for (int y = 0 ; y < mri_mask->height ; y++)
      {
        for (int x = 0 ; x < mri_mask->width ; x++)
        {
          if ( im_diluteerode[z][y][x] != 0 )
          {
            numGcut++;
          }
          if ( mri_mask->slices[z][y][x] != 0 )
          {
            numMask++;
          }
        }
      }
    }
    _ratio = (double)numGcut / numMask;
    if (_ratio <= 0.85)
    {
      error_Hurestic = 1;
    }
  }

  if (error_Hurestic == 1)
  {
    printf("** Gcutted brain is much smaller than the mask!\n");
    printf("** Using the mask as the output instead!\n");
    //printf("** Gcutted output is written as: 'error_gcutted_sample'\n");
  }

  for (int z = 0 ; z < mri->depth ; z++)
  {
    for (int y = 0 ; y < mri->height ; y++)
    {
      for (int x = 0 ; x < mri->width ; x++)
      {
        if (error_Hurestic == 0)
        {
          if ( im_diluteerode[z][y][x] == 0 )
          {
            mri2 ->slices[z][y][x] = 0;
          }
        }
        else
        {
          if ( mri_mask->slices[z][y][x] == 0 )
          {
            mri2 ->slices[z][y][x] = 0;
          }
          //if( im_diluteerode[z][y][x] == 0 )
          //mri ->slices[z][y][x] = 0;
        }
      }
    }//end of for 2
  }//end of for 1

  MRIwrite(mri2, out_filename);

  // if user supplied a filename to which to write diffs, then write-out
  // volume file containing where cuts were made (for debug)
  if (diff_filename[0] && (error_Hurestic != 1))
  {
    MRI *mri_diff = MRISeqchangeType(mri3, MRI_UCHAR, 0.0, 0.999, FALSE);
    for (int z = 0 ; z < mri3->depth ; z++)
    {
      for (int y = 0 ; y < mri3->height ; y++)
      {
        for (int x = 0 ; x < mri3->width ; x++)
        {
          if (mri_mask)
          {
            mri_diff->slices[z][y][x] =
              mri2->slices[z][y][x] - mri_mask->slices[z][y][x];
          }
          else
          {
            mri_diff->slices[z][y][x] =
              mri2->slices[z][y][x] - mri3->slices[z][y][x];
          }
        }
      }//end of for 2
    }//end of for 1
    MRIwrite(mri_diff, diff_filename);
    MRIfree(&mri_diff);
  }

  if (mri)
  {
    MRIfree(&mri);
  }
  if (mri2)
  {
    MRIfree(&mri2);
  }
  if (mri3)
  {
    MRIfree(&mri3);
  }
  if (mri_mask)
  {
    MRIfree(&mri_mask);
  }
  for (int i = 0; i < d; i++)
  {
    for (int j = 0; j < h; j++)
    {
      delete[] im_diluteerode[i][j];
      delete[] im_gcut[i][j];
      delete[] label[i][j];
    }
    delete[] im_diluteerode[i];
    delete[] im_gcut[i];
    delete[] label[i];
  }
  delete[] im_diluteerode;
  delete[] im_gcut;
  delete[] label;

  return 0;
}
コード例 #20
0
/*--------------------------------------------------*/
int main(int argc, char **argv) {
  int nargs, err, asegid, c, r, s, annot, hemioffset;
  int annotid;
  struct utsname uts;
  char *cmdline, cwd[2000];

  /* rkt: check for and handle version tag */
  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();
  dump_options(stdout);

  printf("\n");
  printf("%s\n",vcid);
  printf("cwd %s\n",cwd);
  printf("cmdline %s\n",cmdline);
  printf("sysname  %s\n",uts.sysname);
  printf("hostname %s\n",uts.nodename);
  printf("machine  %s\n",uts.machine);

  SUBJECTS_DIR = getenv("SUBJECTS_DIR");
  if (SUBJECTS_DIR==NULL) {
    printf("ERROR: SUBJECTS_DIR not defined in environment\n");
    exit(1);
  }
  printf("SUBJECTS_DIR %s\n",SUBJECTS_DIR);
  printf("subject %s\n",subject);
  printf("\n");
  fflush(stdout);

  /* ------ Load subject's lh white surface ------ */
  sprintf(tmpstr,"%s/%s/surf/lh.white",SUBJECTS_DIR,subject);
  printf("Reading lh white surface \n %s\n",tmpstr);
  lhwhite = MRISread(tmpstr);
  if (lhwhite == NULL) {
    fprintf(stderr,"ERROR: could not read %s\n",tmpstr);
    exit(1);
  }

  printf("Building hash of lh white\n");
  lhwhite_hash = MHTfillVertexTableRes(lhwhite, NULL,CURRENT_VERTICES,16);

  /* ------ Load lh annotation ------ */
  sprintf(annotfile,"%s/%s/label/lh.aparc.annot",SUBJECTS_DIR,subject);
  printf("Loading lh annotations from %s\n",annotfile);
  err = MRISreadAnnotation(lhwhite, annotfile);
  if (err) {
    printf("ERROR: MRISreadAnnotation() failed %s\n",annotfile);
    exit(1);
  }

  /* ------ Load subject's rh surface ------ */
  sprintf(tmpstr,"%s/%s/surf/rh.white",SUBJECTS_DIR,subject);
  printf("Reading rh white surface \n %s\n",tmpstr);
  rhwhite = MRISread(tmpstr);
  if (rhwhite == NULL) {
    fprintf(stderr,"ERROR: could not read %s\n",tmpstr);
    exit(1);
  }
  if (debug) printf("Building hash of rh white\n");
  rhwhite_hash = MHTfillVertexTableRes(rhwhite, NULL,CURRENT_VERTICES,16);

  /* ------ Load rh annotation ------ */
  sprintf(annotfile,"%s/%s/label/rh.aparc.annot",SUBJECTS_DIR,subject);
  printf("Loading rh annotations from %s\n",annotfile);
  err = MRISreadAnnotation(rhwhite, annotfile);
  if (err) {
    printf("ERROR: MRISreadAnnotation() failed %s\n",annotfile);
    exit(1);
  }

  if (debug && lhwhite->ct) printf("Have color table for annotation\n");
  if (debug) print_annotation_table(stdout);

  /* ------ Load ASeg ------ */
  sprintf(tmpstr,"%s/%s/mri/aseg.mgz",SUBJECTS_DIR,subject);
  if (!fio_FileExistsReadable(tmpstr)) {
    sprintf(tmpstr,"%s/%s/mri/aseg.mgh",SUBJECTS_DIR,subject);
    if (!fio_FileExistsReadable(tmpstr)) {
      sprintf(tmpstr,"%s/%s/mri/aseg/COR-.info",SUBJECTS_DIR,subject);
      if (!fio_FileExistsReadable(tmpstr)) {
        printf("ERROR: cannot find aseg\n");
        exit(1);
      } else
        sprintf(tmpstr,"%s/%s/mri/aseg/",SUBJECTS_DIR,subject);
    }
  }

  printf("Loading aseg from %s\n",tmpstr);
  ASeg = MRIread(tmpstr);
  if (ASeg == NULL) {
    printf("ERROR: loading aseg %s\n",tmpstr);
    exit(1);
  }
  mritmp = MRIchangeType(ASeg,MRI_INT,0,0,0);
  MRIfree(&ASeg);
  ASeg = mritmp;
  WMSeg = MRIclone(ASeg,NULL);

  Vox2RAS = MRIxfmCRS2XYZtkreg(ASeg);
  if (debug) {
    printf("ASeg Vox2RAS: -----------\n");
    MatrixPrint(stdout,Vox2RAS);
    printf("-------------------------\n");
  }
  CRS = MatrixAlloc(4,1,MATRIX_REAL);
  CRS->rptr[4][1] = 1;
  RAS = MatrixAlloc(4,1,MATRIX_REAL);
  RAS->rptr[4][1] = 1;

  // Go through each voxel in the aseg
  printf("\n");
  printf("Labeling WM\n");
  for (c=0; c < ASeg->width; c++) {
    if (debug) printf("%3d ",c);
    if (debug && c%20 ==19) printf("\n");
    for (r=0; r < ASeg->height; r++) {
      for (s=0; s < ASeg->depth; s++) {

        // If it's not labeled as white matter in the aseg, set
        // seg value to that from the aseg and skip the rest
        asegid = MRIgetVoxVal(ASeg,c,r,s,0);
        if (asegid != 2 && asegid != 41) {
          MRIsetVoxVal(WMSeg,c,r,s,0,asegid);
          continue;
        }

        // Convert the CRS to RAS
        CRS->rptr[1][1] = c;
        CRS->rptr[2][1] = r;
        CRS->rptr[3][1] = s;
        RAS = MatrixMultiply(Vox2RAS,CRS,RAS);
        vtx.x = RAS->rptr[1][1];
        vtx.y = RAS->rptr[2][1];
        vtx.z = RAS->rptr[3][1];

        // Get the index of the closest vertex in the
        // lh.white, rh.white
        lhwvtx = MHTfindClosestVertexNo(lhwhite_hash,lhwhite,&vtx,&dlhw);
        rhwvtx = MHTfindClosestVertexNo(rhwhite_hash,rhwhite,&vtx,&drhw);

        if ( (lhwvtx < 0) && (rhwvtx < 0) ) {
          printf("ERROR: could not map to any surface.\n");
          printf("crs = %d %d %d, ras = %6.4f %6.4f %6.4f \n",
                 c,r,s,vtx.x,vtx.y,vtx.z);
          exit(1);
        }

        if (lhwvtx < 0) dlhw = 1000000000000000.0;
        if (rhwvtx < 0) drhw = 1000000000000000.0;

        if (dlhw < drhw) {
          // Left hemi is closer than the right
          annot = lhwhite->vertices[lhwvtx].annotation;
          hemioffset = 1000;
          if (lhwhite->ct)
            CTABfindAnnotation(lhwhite->ct, annot, &annotid);
          else
            annotid = annotation_to_index(annot);
        } else {
          // Right hemi is closer than the left
          annot = rhwhite->vertices[rhwvtx].annotation;
          hemioffset = 2000;
          if (rhwhite->ct)
            CTABfindAnnotation(lhwhite->ct, annot, &annotid);
          else
            annotid = annotation_to_index(annot);
        }

        MRIsetVoxVal(WMSeg,c,r,s,0,annotid+hemioffset);
      }
    }
  }

  printf("\nWriting output wmseg to %s\n",WMSegFile);
  MRIwrite(WMSeg,WMSegFile);

  printf("mri_aparc2wmseg done\n");
  return(0);
}
コード例 #21
0
int
main(int argc, char *argv[])
{
  char         *gca_fname, *in_fname, *out_fname, **av, *xform_fname, fname[STRLEN] ;
  MRI          *mri_in, *mri_norm = NULL, *mri_tmp, *mri_ctrl = NULL ;
  GCA          *gca ;
  int          ac, nargs, nsamples, msec, minutes, seconds;
  int          i, struct_samples, norm_samples = 0, n, input, ninputs ;
  struct timeb start ;
  GCA_SAMPLE   *gcas, *gcas_norm = NULL, *gcas_struct ;
  TRANSFORM    *transform = NULL ;
  char         cmdline[CMD_LINE_LEN], line[STRLEN], *cp, subject[STRLEN], sdir[STRLEN], base_name[STRLEN] ;
  FILE         *fp ;

  make_cmd_version_string
    (argc, argv,
     "$Id: mri_cal_normalize.c,v 1.2.2.1 2011/08/31 00:32:41 nicks Exp $",
     "$Name: stable5 $", cmdline);

  /* rkt: check for and handle version tag */
  nargs = handle_version_option
    (argc, argv,
     "$Id: mri_cal_normalize.c,v 1.2.2.1 2011/08/31 00:32:41 nicks Exp $",
     "$Name: stable5 $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  setRandomSeed(-1L) ;
  Progname = argv[0] ;

  DiagInit(NULL, NULL, NULL) ;
  ErrorInit(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 < 6)
    ErrorExit
      (ERROR_BADPARM,
       "usage: %s [<options>] <longitudinal time point file> <in vol> <atlas> <transform file> <out vol> \n",
       Progname) ;
  in_fname = argv[2] ;
  gca_fname = argv[3] ;
  xform_fname = argv[4] ;
  out_fname = argv[5] ;

  transform = TransformRead(xform_fname) ;
  if (transform == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not read transform from %s", Progname, xform_fname) ;
  if (read_ctrl_point_fname)
  {
    mri_ctrl = MRIread(read_ctrl_point_fname) ;
    if (mri_ctrl == NULL)
      ErrorExit(ERROR_NOFILE, "%s: could not read precomputed control points from %s", 
                Progname, read_ctrl_point_fname) ;
  }
  TimerStart(&start) ;
  printf("reading atlas from '%s'...\n", gca_fname) ;
  fflush(stdout) ;

  gca = GCAread(gca_fname) ;
  if (gca == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not open GCA %s.\n",Progname, gca_fname) ;
  GCAregularizeConditionalDensities(gca, .5) ;

  FileNamePath(argv[1], sdir) ;
  cp = strrchr(sdir, '/') ; 
  if (cp)
  {
    strcpy(base_name, cp+1) ;
    *cp = 0 ;  // remove last component of path, which is base subject name
  }
  ninputs = 0 ;
  fp = fopen(argv[1], "r") ;
  if (fp == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not read time point file %s", argv[1]) ;

  do
  {
    cp = fgetl(line, STRLEN-1, fp) ;
    if (cp != NULL && strlen(cp) > 0)
    {
      subjects[ninputs] = (char *)calloc(strlen(cp)+1, sizeof(char)) ;
      strcpy(subjects[ninputs], cp) ;
      ninputs++ ;
    }
  } while (cp != NULL && strlen(cp) > 0) ;
  fclose(fp) ;
  printf("processing %d timepoints in SUBJECTS_DIR %s...\n", ninputs, sdir) ;
  for (input = 0 ; input < ninputs ; input++)
  {
    sprintf(subject, "%s.long.%s", subjects[input], base_name) ;
    printf("reading subject %s - %d of %d\n", subject, input+1, ninputs) ;
    sprintf(fname, "%s/%s/mri/%s", sdir, subject, in_fname) ;
    mri_tmp = MRIread(fname) ;
    if (!mri_tmp)
      ErrorExit(ERROR_NOFILE, "%s: could not read input MR volume from %s",
                Progname, fname) ;
    MRImakePositive(mri_tmp, mri_tmp) ;
    if (mri_tmp && ctrl_point_fname && !mri_ctrl)
    {
      mri_ctrl = MRIallocSequence(mri_tmp->width, mri_tmp->height, 
                                  mri_tmp->depth,MRI_FLOAT, nregions*2) ; // labels and means
      MRIcopyHeader(mri_tmp, mri_ctrl) ;
    }
    if (input == 0)
    {
      mri_in =
        MRIallocSequence(mri_tmp->width, mri_tmp->height, mri_tmp->depth,
                         mri_tmp->type, ninputs) ;
      if (!mri_in)
        ErrorExit(ERROR_NOMEMORY,
                  "%s: could not allocate input volume %dx%dx%dx%d",
                  mri_tmp->width,mri_tmp->height,mri_tmp->depth,ninputs) ;
      MRIcopyHeader(mri_tmp, mri_in) ;
    }

    if (mask_fname)
    {
      int i ;
      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) ;

      for (i = 1 ; i < WM_MIN_VAL ; i++)
        MRIreplaceValues(mri_mask, mri_mask, i, 0) ;
      MRImask(mri_tmp, mri_mask, mri_tmp, 0, 0) ;
      MRIfree(&mri_mask) ;
    }
    MRIcopyFrame(mri_tmp, mri_in, 0, input) ;
    MRIfree(&mri_tmp) ;
  }
  MRIaddCommandLine(mri_in, cmdline) ;

  GCAhistoScaleImageIntensitiesLongitudinal(gca, mri_in, 1) ;

  {
    int j ;

    gcas = GCAfindAllSamples(gca, &nsamples, NULL, 1) ;
    printf("using %d sample points...\n", nsamples) ;
    GCAcomputeSampleCoords(gca, mri_in, gcas, nsamples, transform) ;
    if (sample_fname)
      GCAtransformAndWriteSamples
        (gca, mri_in, gcas, nsamples, sample_fname, transform) ;

    for (j = 0 ; j < 1 ; j++)
    {
      for (n = 1 ; n <= nregions ; n++)
      {
        for (norm_samples = i = 0 ; i < NSTRUCTURES ; i++)
        {
          if (normalization_structures[i] == Gdiag_no)
            DiagBreak() ;
          printf("finding control points in %s....\n",
                 cma_label_to_name(normalization_structures[i])) ;
          gcas_struct = find_control_points(gca, gcas, nsamples, &struct_samples, n,
                                            normalization_structures[i], mri_in, transform, min_prior,
                                            ctl_point_pct) ;
          discard_unlikely_control_points(gca, gcas_struct, struct_samples, mri_in, transform,
                                          cma_label_to_name(normalization_structures[i])) ;
          if (mri_ctrl && ctrl_point_fname) // store the samples
            copy_ctrl_points_to_volume(gcas_struct, struct_samples, mri_ctrl, n-1) ;
          if (i)
          {
            GCA_SAMPLE *gcas_tmp ;
            gcas_tmp = gcas_concatenate(gcas_norm, gcas_struct, norm_samples, struct_samples) ;
            free(gcas_norm) ;
            norm_samples += struct_samples ;
            gcas_norm = gcas_tmp ;
          }
          else
          {
            gcas_norm = gcas_struct ; norm_samples = struct_samples ;
          }
        }
        
        printf("using %d total control points "
                 "for intensity normalization...\n", norm_samples) ;
        if (normalized_transformed_sample_fname)
          GCAtransformAndWriteSamples(gca, mri_in, gcas_norm, norm_samples,
                                      normalized_transformed_sample_fname,
                                      transform) ;
        mri_norm = GCAnormalizeSamplesAllChannels(mri_in, gca, gcas_norm, file_only ? 0 :norm_samples,
                                                  transform, ctl_point_fname, bias_sigma) ;
        if (Gdiag & DIAG_WRITE)
        {
          char fname[STRLEN] ;
          sprintf(fname, "norm%d.mgz", n) ;
          printf("writing normalized volume to %s...\n", fname) ;
          MRIwrite(mri_norm, fname) ;
          sprintf(fname, "norm_samples%d.mgz", n) ;
          GCAtransformAndWriteSamples(gca, mri_in, gcas_norm, norm_samples,
                                      fname, transform) ;
          
        }
        MRIcopy(mri_norm, mri_in) ;  /* for next pass through */
        MRIfree(&mri_norm) ;
      }
    }
  }

  // now do cross-time normalization to bring each timepoint closer to the mean at each location
  {
    MRI   *mri_frame1, *mri_frame2, *mri_tmp ;
    double rms_before, rms_after ;
    int    i ;

    mri_tmp = MRIcopy(mri_in, NULL) ;
    mri_frame1 = MRIcopyFrame(mri_in, NULL, 0, 0) ;
    mri_frame2 = MRIcopyFrame(mri_in, NULL, 1, 0) ;
    rms_before = MRIrmsDiff(mri_frame1, mri_frame2) ;
    printf("RMS before = %2.2f\n", rms_before) ;
    MRIfree(&mri_frame1) ; MRIfree(&mri_frame2) ;
    for (i = 50 ; i <= 50 ; i += 25)
    {
      MRIcopy(mri_tmp, mri_in) ;
      normalize_timepoints_with_samples(mri_in, gcas_norm, norm_samples, i) ;
      mri_frame1 = MRIcopyFrame(mri_in, NULL, 0, 0) ;
      mri_frame2 = MRIcopyFrame(mri_in, NULL, 1, 0) ;
      rms_after = MRIrmsDiff(mri_frame1, mri_frame2) ;
      MRIfree(&mri_frame1) ; MRIfree(&mri_frame2) ;
      printf("RMS after (%d) = %2.2f\n", i, rms_after) ;
    }
  }
  {
    MRI   *mri_frame1, *mri_frame2 ;
    double rms_after ;
    int    i ;

    mri_tmp = MRIcopy(mri_in, NULL) ;
    for (i = 10 ; i <= 10 ; i += 10)
    {
      MRIcopy(mri_tmp, mri_in) ;
      normalize_timepoints(mri_in, 2.0, i) ;
      mri_frame1 = MRIcopyFrame(mri_in, NULL, 0, 0) ;
      mri_frame2 = MRIcopyFrame(mri_in, NULL, 1, 0) ;
      rms_after = MRIrmsDiff(mri_frame1, mri_frame2) ;
      MRIfree(&mri_frame1) ; MRIfree(&mri_frame2) ;
      printf("RMS after intensity cohering = %2.2f\n", rms_after) ;
    }
  }

  for (input = 0 ; input < ninputs ; input++)
  {
    sprintf(fname, "%s/%s.long.%s/mri/%s", sdir, subjects[input], base_name, out_fname) ;
    printf("writing normalized volume to %s...\n", fname) ;
    if (MRIwriteFrame(mri_in, fname, input)  != NO_ERROR)
      ErrorExit(ERROR_BADFILE, "%s: could not write normalized volume to %s",Progname, fname);
  }

  if (ctrl_point_fname)
  {
    printf("writing control points to %s\n", ctrl_point_fname) ;
    MRIwrite(mri_ctrl, ctrl_point_fname) ;
    MRIfree(&mri_ctrl) ;
  }
  MRIfree(&mri_in) ;

  printf("freeing GCA...") ;
  if (gca)
    GCAfree(&gca) ;
  printf("done.\n") ;
  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  printf("normalization took %d minutes and %d seconds.\n",
         minutes, seconds) ;
  if (diag_fp)
    fclose(diag_fp) ;
  exit(0) ;
  return(0) ;
}
コード例 #22
0
ファイル: mris_flatten.c プロジェクト: zkaufman/freesurfer
int
main(int argc, char *argv[])
{
  char         **av, in_surf_fname[STRLEN], *in_patch_fname, *out_patch_fname,
  fname[STRLEN], path[STRLEN], *cp, hemi[10] ;
  int          ac, nargs ;
  MRI_SURFACE  *mris ;
  MRI          *mri_vertices ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option
          (argc, argv,
           "$Id: mris_flatten.c,v 1.42 2016/12/10 22:57:46 fischl Exp $",
           "$Name:  $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  Gdiag |= DIAG_SHOW ;
  Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;
  Gdiag |= (DIAG_SHOW | DIAG_WRITE) ;
  memset(&parms, 0, sizeof(parms)) ;
  parms.dt = .1 ;
  parms.projection = PROJECT_PLANE ;
  parms.tol = 0.2 ;
  parms.n_averages = 1024 ;
  parms.l_dist = 1.0 ;
  parms.l_nlarea = 1.0 ;
  parms.niterations = 40 ;
  parms.area_coef_scale = 1.0 ;
  parms.dt_increase = 1.01 /* DT_INCREASE */;
  parms.dt_decrease = 0.98 /* DT_DECREASE*/ ;
  parms.error_ratio = 1.03 /*ERROR_RATIO */;
  parms.integration_type = INTEGRATE_LINE_MINIMIZE ;
  parms.momentum = 0.9 ;
  parms.desired_rms_height = -1.0 ;
  parms.base_name[0] = 0 ;
  parms.nbhd_size = 7 ;    /* out to 7-connected neighbors */
  parms.max_nbrs = 12 ;    /* 12 at each distance */
  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++)
  {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  if (argc < 3)
    print_help() ;

  parms.base_dt = base_dt_scale * parms.dt ;
  in_patch_fname = argv[1] ;
  out_patch_fname = argv[2] ;
  FileNamePath(in_patch_fname, path) ;
  cp = strrchr(in_patch_fname, '/') ;
  if (!cp)
    cp = in_patch_fname ;
  cp = strchr(cp, '.') ;
  if (cp)
  {
    strncpy(hemi, cp-2, 2) ;
    hemi[2] = 0 ;
  }
  else
    strcpy(hemi, "lh") ;
  if (one_surf_flag)
    sprintf(in_surf_fname, "%s", in_patch_fname) ;
  else
    sprintf(in_surf_fname, "%s/%s.%s", path, hemi, original_surf_name) ;

  if (parms.base_name[0] == 0)
  {
    FileNameOnly(out_patch_fname, fname) ;
    cp = strchr(fname, '.') ;
    if (cp)
      strcpy(parms.base_name, cp+1) ;
    else
      strcpy(parms.base_name, "flattened") ;
  }

  mris = MRISread(in_surf_fname) ;
  if (!mris)
    ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
              Progname, in_surf_fname) ;

  if (sphere_flag)
  {
    MRIScenter(mris, mris) ;
    mris->radius = MRISaverageRadius(mris) ;
    MRISstoreMetricProperties(mris) ;
    MRISsaveVertexPositions(mris, ORIGINAL_VERTICES) ;
  }

  if (Gdiag_no >= 0)
  {
    int n ;
    printf("vertex %d has %d nbrs before patch:\n",
           Gdiag_no, mris->vertices[Gdiag_no].vnum) ;
    for (n = 0 ; n < mris->vertices[Gdiag_no].vnum ; n++)
      printf("\t%d\n", mris->vertices[Gdiag_no].v[n]) ;
  }
  if (one_surf_flag)  /* only have the 1 surface - no patch file */
  {
    mris->patch = 1 ;
    mris->status = MRIS_PATCH ;
    if (!FEQUAL(rescale,1))
    {
      MRISscaleBrain(mris, mris, rescale) ;
      MRIScomputeMetricProperties(mris) ;
    }
    MRISstoreMetricProperties(mris) ;
    MRISsaveVertexPositions(mris, ORIGINAL_VERTICES) ;

  } 
  else
  {
    MRISresetNeighborhoodSize(mris, mris->vertices[0].nsize) ; // set back to max
    if (label_fname) // read in a label instead of a patch
    {
      LABEL *area ;
      area = LabelRead(NULL, label_fname) ;
      if (area == NULL)
        ErrorExit(ERROR_BADPARM, "%s: could not read label file %s",
                  Progname, label_fname) ;

      LabelDilate(area, mris, dilate_label, CURRENT_VERTICES) ;
      MRISclearMarks(mris) ;
      LabelMark(area, mris) ;
      MRISripUnmarked(mris) ;
      MRISripFaces(mris);
      mris->patch = 1 ;
      mris->status = MRIS_CUT ;
      LabelFree(&area) ;
      printf("%d valid vertices (%2.1f %% of total)\n",
             MRISvalidVertices(mris), 
             100.0*MRISvalidVertices(mris)/mris->nvertices) ;
    }
    else
    {
      if (MRISreadPatch(mris, in_patch_fname) != NO_ERROR)
        ErrorExit(ERROR_BADPARM, "%s: could not read patch file %s",
                  Progname, in_patch_fname) ;
      if (dilate)
      {
        printf("dilating patch %d times\n", dilate) ;
        MRISdilateRipped(mris, dilate) ;
        printf("%d valid vertices (%2.1f %% of total)\n",
               MRISvalidVertices(mris), 100.0*MRISvalidVertices(mris)/mris->nvertices) ;
      }
    }
    MRISremoveRipped(mris) ;
    MRISupdateSurface(mris) ;
#if 0
    mris->nsize = 1 ; // before recalculation of 2 and 3-nbrs
    {
      int vno ;
      VERTEX *v ;
      for (vno= 0 ; vno < mris->nvertices ; vno++)
      {
        v = &mris->vertices[vno] ;
        v->vtotal = v->vnum ;
        v->nsize = 1 ;
      }
    }
    MRISsetNeighborhoodSize(mris, nbrs) ;
#endif
  }

  if (Gdiag_no >= 0)
    printf("vno %d is %sin patch\n", Gdiag_no,
           mris->vertices[Gdiag_no].ripflag ? "NOT " : "") ;

  if (Gdiag_no >= 0 && mris->vertices[Gdiag_no].ripflag == 0)
  {
    int n ;
    printf("vertex %d has %d nbrs after patch:\n",
           Gdiag_no, mris->vertices[Gdiag_no].vnum) ;
    for (n = 0 ; n < mris->vertices[Gdiag_no].vnum ; n++)
      printf("\t%d\n", mris->vertices[Gdiag_no].v[n]) ;
  }
  fprintf(stderr, "reading original vertex positions...\n") ;
  if (!FZERO(disturb))
    mrisDisturbVertices(mris, disturb) ;
  if (parms.niterations > 0)
  {
    MRISresetNeighborhoodSize(mris, nbrs) ;

    if (!FZERO(parms.l_unfold) || !FZERO(parms.l_expand))
    {
      static INTEGRATION_PARMS p2 ;
      sprintf(in_surf_fname, "%s/%s.%s", path, hemi, original_surf_name) ;
      if (stricmp(original_unfold_surf_name,"none") == 0)
      {
        printf("using current position of patch as initial position\n") ;
        MRISstoreMetricProperties(mris) ;  /* use current positions */
      }
      else if (!sphere_flag && !one_surf_flag)
        MRISreadOriginalProperties(mris, original_unfold_surf_name) ;
      *(&p2) = *(&parms) ;
      p2.l_dist = 0 ;
      p2.niterations = 100 ;
      p2.nbhd_size = p2.max_nbrs = 1 ;
      p2.n_averages = 0 ;
      p2.write_iterations = parms.write_iterations > 0 ? 25 : 0 ;
      p2.tol = -1 ;
      p2.dt = 0.5 ;
      p2.l_area = 0.0 ;
      p2.l_spring = 0.9 ;
      p2.l_convex = 0.9 ;
      p2.momentum = 0 ;
      p2.integration_type = INTEGRATE_MOMENTUM ;
      MRISrestoreVertexPositions(mris, ORIGINAL_VERTICES) ;
#if 0
      p2.flags |= IPFLAG_NO_SELF_INT_TEST ;
      printf("expanding surface....\n") ;
      MRISexpandSurface(mris, 4.0, &p2) ;  // push it away from fissure
#endif
      p2.niterations = 100 ;
      MRISunfold(mris, &p2, 1) ;
      p2.niterations = 300 ;
      p2.l_unfold *= 0.25 ;
      MRISunfold(mris, &p2, 1) ;
      p2.l_unfold *= 0.25 ;
      MRISunfold(mris, &p2, 1) ;
#if 0
      printf("smoothing unfolded surface..\n");
      p2.niterations = 200 ;
      p2.l_unfold = 0 ;  // just smooth it
      MRISunfold(mris, &p2, max_passes) ;
#endif
      parms.start_t = p2.start_t ;
      parms.l_unfold = parms.l_convex = parms.l_boundary = parms.l_expand=0 ;
      MRIfree(&parms.mri_dist) ;
    }

    sprintf(in_surf_fname, "%s/%s.%s", path, hemi, original_surf_name) ;
    if (!sphere_flag && !one_surf_flag)
      MRISreadOriginalProperties(mris, original_surf_name) ;
    if (randomly_flatten)
      MRISflattenPatchRandomly(mris) ;
    else
      MRISflattenPatch(mris) ;

    /* optimize metric properties of flat map */
    fprintf(stderr,"minimizing metric distortion induced by projection...\n");
    MRISscaleBrain(mris, mris, scale) ;
    MRIScomputeMetricProperties(mris) ;
    MRISunfold(mris, &parms, max_passes) ;
    MRIScenter(mris, mris) ;
    fprintf(stderr, "writing flattened patch to %s\n", out_patch_fname) ;
    MRISwritePatch(mris, out_patch_fname) ;
  }

  if (plane_flag || sphere_flag)
  {
    char fname[STRLEN] ;
    FILE *fp ;

#if 0
    sprintf(fname, "%s.%s.out",
            mris->hemisphere == RIGHT_HEMISPHERE ? "rh" : "lh",
            parms.base_name);
#else
    sprintf(fname, "flatten.log") ;
#endif
    fp = fopen(fname, "a") ;

    if (plane_flag)
      MRIScomputeAnalyticDistanceError(mris, MRIS_PLANE, fp) ;
    else if (sphere_flag)
      MRIScomputeAnalyticDistanceError(mris, MRIS_SPHERE, fp) ;
    fclose(fp) ;
  }

  if (mri_overlay)
  {
    MRI  *mri_flattened ;
    char fname[STRLEN] ;

    // if it is NxNx1x1 reshape it to be Nx1x1xN
    if ( mri_overlay->width == mri_overlay->height &&
       mri_overlay->depth == 1 &&
       mri_overlay->nframes == 1)
    {
      MRI *mri_tmp ;
      printf("reshaping to move 2nd dimension to time\n") ;
      mri_tmp = mri_reshape( mri_overlay, mri_overlay->width, 1, 1, mri_overlay->height);
      MRIfree( &mri_overlay );
      mri_overlay = mri_tmp;
    }

    // put in some special code that knows about icosahedra
    if (mris->nvertices == 163842 ||  // ic7
        mris->nvertices == 40962 ||  // ic6
        mris->nvertices == 10242 ||  // ic5
        mris->nvertices == 2562)  // ic4
    {
      int nvals, start_index, end_index ;
      MRI *mri_tmp ;
      
      printf("cross-hemispheric correlation matrix detected, reshaping...\n") ;
      nvals = mri_overlay->width * mri_overlay->height * mri_overlay->depth ;
      if (nvals == 2*mris->nvertices)   // it's a corr matrix for both hemis
      {
        if (mris->hemisphere == LEFT_HEMISPHERE || mris->hemisphere == RIGHT_HEMISPHERE)
        {
          if (mris->hemisphere == LEFT_HEMISPHERE)
          {
            start_index = 0 ; 
            end_index = mris->nvertices-1 ;
          }
          else
          {
            start_index = mris->nvertices ; 
            end_index = 2*mris->nvertices-1 ;
          }
          mri_tmp = MRIextract(mri_overlay, NULL, start_index, 0, 0, mris->nvertices, 1, 1) ;
          MRIfree(&mri_overlay) ;
          mri_overlay = mri_tmp;
        }
        else // both hemis
        {
        }
      }
    }
    
    printf("resampling overlay (%d x %d x %d x %d) into flattened coordinates..\n",
           mri_overlay->width, mri_overlay->height, mri_overlay->depth, mri_overlay->nframes) ;
    if (synth_name)
    {
      LABEL *area_lh, *area_rh ;
      char  fname[STRLEN], path[STRLEN], fname_no_path[STRLEN] ;
      int   vno, n, vno2, n2 ;

      MRIsetValues(mri_overlay, 0) ;
      FileNameOnly(synth_name, fname_no_path) ;
      FileNamePath(synth_name, path) ;
      sprintf(fname, "%s/lh.%s", path, fname_no_path) ;
      area_lh = LabelRead(NULL, fname) ;
      if (area_lh == NULL)
        ErrorExit(ERROR_NOFILE, "%s: could not read label from %s",
                  Progname,fname) ;
      sprintf(fname, "%s/rh.%s", path, fname_no_path) ;
      area_rh = LabelRead(NULL, fname) ;
      if (area_rh == NULL)
        ErrorExit(ERROR_NOFILE, "%s: could not read label from %s",
                  Progname,fname) ;
#if 0
      for (n = 0 ; n < area_lh->n_points ; n++)
      {
        vno = area_lh->lv[n].vno ;
        MRIsetVoxVal(mri_overlay, vno, 0, 0, vno, 1) ;
	printf("synthesizing map with vno %d: (%2.1f, %2.1f)\n", vno, mris->vertices[vno].x, mris->vertices[vno].y) ;
        break ;
      }
#else
      for (n = 0 ; n < area_lh->n_points ; n++)
      {
        vno = area_lh->lv[n].vno ;
        if (vno >= 0)
        {
          for (n2 = 0 ; n2 < area_lh->n_points ; n2++)
          {
            vno2 = area_lh->lv[n2].vno ;
            if (vno2 >= 0)
              MRIsetVoxVal(mri_overlay, vno, 0, 0, vno2, 1) ;
          }
          for (n2 = 0 ; n2 < area_rh->n_points ; n2++)
          {
            vno2 = area_rh->lv[n2].vno ;
            if (vno2 >= 0)
              MRIsetVoxVal(mri_overlay, vno, 0, 0, mris->nvertices+vno2, 1) ;
          }
        }
      }
#endif
    }

    mri_flattened = MRIflattenOverlay(mris, mri_overlay, NULL, 1.0, label_overlay, &mri_vertices) ;
    printf("writing flattened overlay to %s\n", out_patch_fname) ;
    MRIwrite(mri_flattened, out_patch_fname) ;
    MRIfree(&mri_flattened) ;

    FileNameRemoveExtension(out_patch_fname, fname) ;
    strcat(fname, ".vnos.mgz") ;
    printf("writing flattened vertex #s to %s\n", fname) ;
    MRIwrite(mri_vertices, fname) ;
    MRIfree(&mri_vertices) ;
  }
#if 0
  sprintf(fname, "%s.area_error", out_fname) ;
  printf("writing area errors to %s\n", fname) ;
  MRISwriteAreaError(mris, fname) ;
  sprintf(fname, "%s.angle_error", out_fname) ;
  printf("writing angle errors to %s\n", fname) ;
  MRISwriteAngleError(mris, fname) ;
  MRISfree(&mris) ;
#endif

  exit(0) ;
  return(0) ;  /* for ansi */
}
コード例 #23
0
ファイル: mri_ribbon.c プロジェクト: guo2004131/freesurfer
int main(int argc, char *argv[]) {
  char *inner_mris_fname,*outer_mris_fname,*input_mri_pref,*output_mri_pref;
  MRI *mri=0,*mri_src=0;
  MRI_SURFACE *inner_mris=0,*outer_mris=0;
  int nargs;
  LABEL *area = NULL ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option 
    (argc, argv, 
     "$Id: mri_ribbon.c,v 1.15 2011/03/02 00:04:24 nicks Exp $", 
     "$Name: stable5 $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  Progname=argv[0];
  if (argc > 1)
    while (*argv[1] == '-')
    {
      int nargs = 0 ;
      switch (toupper(argv[1][1]))
      {
      case 'L':
        printf("cropping ribbon to label file %s\n", argv[2]) ;
        nargs = 1 ;
        area = LabelRead(NULL, argv[2]) ;
        if (area == NULL)
          ErrorExit(ERROR_NOFILE, 
                    "%s: could not read label file %s\n", 
                    argv[2]) ;
        break ;
      default:
        break ;
      }
      argc -= (nargs+1) ;
      if (argc == 1) break;
      argv += (nargs+1) ;
    }

  /* Set command-line parameters */
  if (argc!=5) {
    printf("Usage: mri_ribbon [-l fname.label] \\ \n"
           "       inner_surface_fname \\ \n"
           "       outer_surface_fname \\ \n"
           "       input_volume_pref \\ \n"
           "       output_volume_pref\n");
    exit(1);
  }

  inner_mris_fname=argv[1];
  outer_mris_fname=argv[2];
  input_mri_pref=argv[3];
  output_mri_pref=argv[4];

  /* Read surface information from inner surface file */
  printf("Reading surface file %s.\n",inner_mris_fname);
  inner_mris=MRISread(inner_mris_fname);
  if (!inner_mris) {
    printf("Could not read surface file %s.\n",inner_mris_fname);
    exit(1);
  }

  /* Read surface information from outer surface file */
  printf("Reading surface file %s.\n",outer_mris_fname);
  outer_mris=MRISread(outer_mris_fname);
  if (!outer_mris) {
    printf("Could not read surface file %s.\n",outer_mris_fname);
    exit(1);
  }

  /* Read example volume from file */
  printf("Reading MRI volume directory %s.\n",input_mri_pref);
  mri_src=MRIread(input_mri_pref);
  if (!mri_src) {
    printf("Could not read MRI volume directory %s.\n",input_mri_pref);
    exit(1);
  }

  /* Extract ribbon */
  printf("Extracting ribbon.\n");
  mri=MRISribbon(inner_mris,outer_mris,mri_src,NULL);

  if (area)
    MRIcropVolumeToLabel(mri, mri, area, inner_mris, outer_mris) ;
  /* Save MRI volume to directory */
  printf("Writing volume file %s.\n",output_mri_pref);
  MRIwrite(mri,output_mri_pref);

  MRIfree(&mri);
  MRIfree(&mri_src);
  MRISfree(&inner_mris);
  MRISfree(&outer_mris);

  return 0;
}
コード例 #24
0
int main(int argc, char *argv[]) {
  MRIS *mris;
  char  *in_orig_fname=NULL, *in_seg_fname=NULL,*out_fname=NULL;
  MRI *mri_orig=NULL,*mri_seg=NULL,*mri_out=NULL;
  int nargs,n;
  char fname[512];

  Progname=argv[0];
  fprintf(stderr,"\n");
  MRI_TOPOLOGY_PARMSdefault(&parms);

  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }
  if (parms.tesselation_mode==-1)
    parms.tesselation_mode=parms.connectivity;
  if (argc<4) {
    fprintf(stderr, "\nUsage: %s options input_orig_file input_segmented_file output_folder\n", Progname);
    exit(1);
  };

  in_orig_fname=argv[argc-3];
  in_seg_fname = argv[argc-2];
  out_fname = argv[argc-1];

  fprintf(stderr,"************************************************************"
          "\nThe input orig volume is %s"
          "\nThe input segmented volume is %s"
          "\nThe output volume is %s"
          "\nIf this is incorrect, please exit quickly the program (Ctl-C)\n",in_orig_fname,in_seg_fname,out_fname);
  for (n=0;n<parms.nlabels;n++)
    fprintf(stderr,"label = %d: %s \n",parms.labels[n],cma_label_to_name(parms.labels[n]));
  if (parms.using_gca_maps)
    fprintf(stderr,"mixing parameters: alpha=%1.3f , beta=%1.3f \n",parms.alpha,parms.beta);
  else {
    parms.beta=1.0f;
    parms.alpha=1.0f;
  }
  fprintf(stderr,"connectivity = %d\n",parms.connectivity);

  mri_orig=MRIread(in_orig_fname);
  if (!mri_orig && parms.using_gca_maps)
    Error("orig volume: orig volume could not be read\n");
  mri_seg=MRIread(in_seg_fname);
  if (!mri_seg)
    Error("segmented volume: segmented volume could not be read\n");


  //check euler characteristic of initial surface
  if (parms.initial_surface_file) {
    int i,j,k,val,euler,pnvertices,  pnfaces, pnedges;
    MRI *mri_tmp;
    mri_tmp=MRIclone(mri_seg,NULL);
    for (k=0;k<mri_seg->depth;k++)
      for (j=0;j<mri_seg->height;j++)
        for (i=0;i<mri_seg->width;i++)
          for (n=0;n<parms.nlabels;n++) {
            val=MRIgetVoxVal(mri_seg,i,j,k, 0);
            if (val==parms.labels[n]) {
              MRIsetVoxVal(mri_tmp,i,j,k,0,1);
              break;
            }
          }
    mris=MRIScreateSurfaceFromVolume(mri_tmp,1,parms.connectivity);
    euler=MRIScomputeEulerNumber(mris,&pnvertices,&pnfaces,&pnedges);
    fprintf(stderr,"\ninitial euler characteristic = %d, %d vertices, %d faces, %d edges"
            ,euler,pnvertices,pnfaces,pnedges);
    MRISwrite(mris,parms.initial_surface_file);
    MRISfree(&mris);
    MRIfree(&mri_tmp);
  }

  mri_out=MRIcorrectTopology(mri_orig,mri_seg,NULL,&parms);

  if (parms.nlabels == 1) {
    MRI *mri_tmp ;

    // turn off all voxels that are going to be on in the output
    MRImask(mri_seg, mri_out, mri_seg, 1, 0) ;
    /* whatever ones are left are now incorrect and should be labeled
      something else
    */
    resegment_erased_voxels(mri_orig, mri_seg, mri_seg, parms.labels[0]) ;
    MRIreplaceValues(mri_out, mri_out, 1, parms.labels[0]) ;
    mri_tmp = MRIcopy(mri_seg, NULL) ;
    MRIcopyLabel(mri_out, mri_tmp, parms.labels[0]) ;
    MRIfree(&mri_out) ;
    mri_out = mri_tmp ;
    //  check_volume(mri_save, mri_out, parms.labels[0]) ;
  }
  MRIwrite(mri_out,out_fname);

  ////TEMPORARY VALIDATION STUFF //////////////////////////////////////////////////////////////////
  //////////////////////////////////////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////////////////////////////////////
#if 0
  //validation of the algo
  {
    FILE *f;
    MRIS *mristb[20],*mrisr;
    int n,i,j,k,depth,height,width,count,count2;
    int tab[20]={4,43,51,12,52,13,54,18,53,17,49,10,50,11};//,6,7,10,11,12,13,17,18,43,44,45,46,49,50,51,52,53,54};
    MRI *mri_val=MRIclone(parms.mri_seg,NULL);
    parms.nlabels=1;

    depth=parms.mri_seg->depth;
    height=parms.mri_seg->height;
    width=parms.mri_seg->width;
    for (n=0;n<14;n++) {
      MRIfree(&parms.mri_output);
      MRIfree(&parms.mri_bin);
      MRIfree(&parms.mri_dist);
      MRIfree(&parms.mri_fcost);
      MRIfree(&parms.mri_bcost);
      MRIfree(&parms.mri_fprior);
      MRIfree(&parms.mri_bprior);
      MRIfree(&parms.mri_labeled);
      segmentationFree(&parms.F_Bseg);
      segmentationFree(&parms.F_Rseg);
      segmentationFree(&parms.B_Bseg);
      segmentationFree(&parms.B_Rseg);
      CCSfree(&parms.F_Bccs);
      CCSfree(&parms.F_Rccs);
      CCSfree(&parms.B_Bccs);
      CCSfree(&parms.B_Rccs);

      parms.labels[0]=tab[n];
      MRIcorrectTopology(parms.mri_orig,parms.mri_seg,&parms.mri_output,mris
                         ,parms.labels,parms.nblabels,parms.f_c,parms);



      MRISwrite(*mris,"./tmp");
      mristb[n]=MRISread("./tmp");
#if 0
      count=0;
      count2=0;
      for (k=0;k<depth;k++)
        for (j=0;j<height;j++)
          for (i=0;i<width;i++) {
            if (MRIvox(parms.mri_seg,i,j,k)==parms.labels[0])
              count2++;
            if (MRIvox(parms.mri_output,i,j,k)==1) {
              MRIvox(mri_val,i,j,k)++;
              if (MRIvox(parms.mri_seg,i,j,k)!=parms.labels[0])
                count++;
            } else if (MRIvox(parms.mri_seg,i,j,k)==parms.labels[0])
              count++;
          }
      fprintf(stderr,"\n yeh %d %d %f \n",count,count2,100.*count/count2);
      sprintf(fname,"./label%d",tab[n]);
      f=fopen(fname,"a+");
      fprintf(f,"\n %d %d %f ",count,count2,(float)100.*count/count2);
      fclose(f);
#endif

#if 0
      sprintf(fname,"./surf%d",n);
      MRISwrite(mristb[n],fname);
      MRISsmoothSurface2(mristb[n],5,0.5,0);
      MRISsmoothSurface2(mristb[n],5,0.25,2);
      MRISsmoothSurface2(mristb[n],10,0.05,5);
      sprintf(fname,"./surfsmooth%d",n);
      mristb[n]->type=MRIS_TRIANGULAR_SURFACE;//MRIS_BINARY_QUADRANGLE_FILE;
      MRISwrite(mristb[n],fname);

      MRISsetNeighborhoodSize(mristb[n],3) ;
      MRIScomputeMetricProperties(mristb[n]) ;
      MRIScomputeSecondFundamentalForm(mristb[n]) ;
      MRISuseMeanCurvature(mristb[n]);
      MRISaverageCurvatures(mristb[n],2) ;
      MRISnormalizeCurvature(mristb[n], NORM_MEAN) ;
      sprintf(fname,"./curv%d",n);
      MRISwriteCurvature(mristb[n],fname);
#endif
    }

#if 0
    mrisr=MRISconcatenateQuadSurfaces(n,mristb);
    mrisr->type=MRIS_TRIANGULAR_SURFACE;
    MRISwrite(mrisr,"./lh.ZURFACE");


    //    for(k=0;k<mrisr->nvertices;k++)
    // mrisr->vertices[k].curv=0.3;

    //MRISnormalizeCurvature(mrisr, NORM_MEAN) ;
    MRISwriteCurvature(mrisr,"./ZURFACE_CURVATURE");
    for (k=0;k<mrisr->nvertices;k++)
      mrisr->vertices[k].curv=mrisr->vertices[k].val;
    MRISwriteCurvature(mrisr,"./ZURFACE_VAL");
#endif

    n=0;
    count=0;
    for (k=0;k<depth;k++)
      for (j=0;j<height;j++)
        for (i=0;i<width;i++) {
          if (MRIgetVoxVal(mri_val,i,j,k,0)>=1) {
            n++;
            if (MRIsetVoxVal(mri_val,i,j,k,0)>1)
              count++;
          }
        }
    //    sprintf(fname,"./labeltotal");
    /// f=fopen(fname,"a+");
    //fprintf(f,"\n %s %d %d %f ",in_seg_fname,count,n,(float)100.*count/n);
    //fclose(f);




#if 0
    MRIwrite(mri_val,"/tmp/tmp");
#endif

    fprintf(stderr,"\n WE HAVE %d %d %f   \n",count,n,100.*count/n);

  }
#endif
  //////////////////////////////////////////////////////////////////////////////////
  //////////////////////////////////////////////////////////////////////////////////

  if (parms.final_surface_file) {
    int euler,pnvertices,  pnfaces, pnedges;
    mris=MRIScreateSurfaceFromVolume(mri_out,1,parms.connectivity);
    euler=MRIScomputeEulerNumber(mris,&pnvertices,&pnfaces,&pnedges);
    fprintf(stderr,"\nfinal euler characteristic = %d, %d vertices, %d faces, %d edges"
            ,euler,pnvertices,pnfaces,pnedges);
    sprintf(fname,"%s",parms.final_surface_file);
    MRISwrite(mris,fname);

#if 0
    MRISsmoothSurface(mris,7,0.2);
    strcat(fname,"_smooth");
    MRISwrite(mris,fname);
    if (parms.fit) {
      sprintf(fname,parms.surfname);
      strcat(fname,"_fit");
      MRISmatchSurfaceToLabel(parms.mris,parms.mri_output,1,NULL,NULL,parms.f_c);
      MRISwrite(parms.mris,fname);
    }
#endif
    MRISfree(&mris);
  }

  if (mri_out)
    MRIfree(&mri_out);
  if (mri_orig)
    MRIfree(&mri_orig);
  if (mri_seg)
    MRIfree(&mri_seg);
  fprintf(stderr,"\n");
  return NO_ERROR;
}
コード例 #25
0
ファイル: mri_volsynth.c プロジェクト: ewong718/freesurfer
/* ------------------------------------------------------------------ */
static int parse_commandline(int argc, char **argv) {
  int  i, nargc , nargsused;
  char **pargv, *option ;
  char tmpstr[1000];

  if (argc < 1) usage_exit();

  nargc   = argc;
  pargv = argv;
  while (nargc > 0) {

    option = pargv[0];
    if (debug) printf("%d %s\n",nargc,option);
    nargc -= 1;
    pargv += 1;

    nargsused = 0;

    if (!strcasecmp(option, "--help"))           print_help() ;
    else if (!strcasecmp(option, "--version"))   print_version() ;
    else if (!strcasecmp(option, "--debug"))     debug = 1;
    else if (!strcasecmp(option, "--abs"))       DoAbs = 1;
    else if (!strcasecmp(option, "--nogmnnorm")) gmnnorm = 0;
    else if (!strcasecmp(option, "--rescale"))   rescale=1;
    else if (!strcasecmp(option, "--norescale")) rescale=0;
    else if (!strcasecmp(option, "--no-output")) NoOutput = 1;
    else if (!strcasecmp(option, "--fft"))       UseFFT = 1;
    else if (!strcasecmp(option, "--offset"))    AddOffset=1;
    else if (!strcasecmp(option, "--offset-mid")){
      AddOffset = 1;
      OffsetFrame = -1;
    }
    else if (!strcmp(option, "--hsc")) {
      if (nargc < 2) argnerr(option,2);
      sscanf(pargv[0],"%lf",&HSCMin);
      sscanf(pargv[1],"%lf",&HSCMax);
      DoHSC = 1;
      nargsused = 2;
    }
    else if (!strcmp(option, "--sum2")) {
      if (nargc < 1) argnerr(option,1);
      sum2file = pargv[0];
      pdfname  = "delta";
      //NoOutput = 1;
      nframes  = 1;
      nargsused = 1;
    }
    else if (!strcmp(option, "--hsynth")) {
      // eres mask DoTnorm out
      if (nargc < 3) argnerr(option,3);
      mri = MRIread(pargv[0]);
      mask = MRIread(pargv[1]);
      sscanf(pargv[2],"%d",&DoTNorm);
      mri2 = fMRIhsynth(mri, mask, DoTNorm);
      MRIwrite(mri2,pargv[3]);
      exit(0);
      nargsused = 2;
    }
    else if (!strcmp(option, "--vol") || !strcmp(option, "--o")) {
      if (nargc < 1) argnerr(option,1);
      volid = pargv[0];
      nargsused = 1;
      if (nth_is_arg(nargc, pargv, 1)) {
        volfmt = pargv[1];
        nargsused ++;
        volfmtid = checkfmt(volfmt);
      } 
    }
    else if (!strcmp(option, "--temp") || !strcmp(option, "--template")) {
      if(DoCurv){
	printf("ERROR: cannot use --temp and --curv\n");
	exit(1);
      }
      if(nargc < 1) argnerr(option,1);
      tempid = pargv[0];
      nargsused = 1;
      if (nth_is_arg(nargc, pargv, 1)) {
        tempfmt = pargv[1];
        nargsused ++;
        tempfmtid = checkfmt(tempfmt);
      } else tempfmtid = getfmtid(tempid);
    } else if (!strcmp(option, "--curv")) {
      if(tempid != NULL){
	printf("ERROR: cannot use --temp and --curv\n");
	exit(1);
      }
      if(nargc < 2) argnerr(option,2);
      subject = pargv[0];
      hemi = pargv[1];
      DoCurv = 1;
      nargsused = 2;
      sprintf(tmpstr,"%s/%s/surf/%s.thickness",getenv("SUBJECTS_DIR"),subject,hemi);
      tempid = strcpyalloc(tmpstr);
    } else if ( !strcmp(option, "--dim") ) {
      if (nargc < 4) argnerr(option,4);
      for (i=0;i<4;i++) sscanf(pargv[i],"%d",&dim[i]);
      nargsused = 4;
      dimSpeced = 1;
    } 
    else if ( !strcmp(option, "--nframes") ) {
      if (nargc < 1) argnerr(option,1);
      sscanf(pargv[0],"%d",&nframes);
      nargsused = 1;
    } 
    else if ( !strcmp(option, "--TR") || !strcmp(option, "--tr") ) {
      if (nargc < 1) argnerr(option,1);
      sscanf(pargv[0],"%lf",&TR);
      nargsused = 1;
    } 
    else if ( !strcmp(option, "--res") ) {
      if (nargc < 4) argnerr(option,4);
      for (i=0;i<4;i++) sscanf(pargv[i],"%f",&res[i]);
      nargsused = 4;
      resSpeced = 1;
    } 
    else if ( !strcmp(option, "--vox-size") ) {
      if (nargc < 3) argnerr(option,3);
      for (i=0;i<3;i++) sscanf(pargv[i],"%f",&res[i]);
      nargsused = 4;
      resSpeced = 1;
      NewVoxSizeSpeced = 1;
    } 
    else if ( !strcmp(option, "--c_ras") ) {
      if (nargc < 3) argnerr(option,3);
      for (i=0;i<3;i++) sscanf(pargv[i],"%f",&cras[i]);
      nargsused = 3;
    } 
    else if ( !strcmp(option, "--p0") ) {
      if (nargc < 3) argnerr(option,3);
      for (i=0;i<3;i++) sscanf(pargv[i],"%f",&p0[i]);
      usep0 = 1;
      nargsused = 3;
    } 
    else if ( !strcmp(option, "--cdircos") ) {
      if (nargc < 3) argnerr(option,3);
      for (i=0;i<3;i++) sscanf(pargv[i],"%f",&cdircos[i]);
      nargsused = 3;
    } else if ( !strcmp(option, "--rdircos") ) {
      if (nargc < 3) argnerr(option,3);
      for (i=0;i<3;i++) sscanf(pargv[i],"%f",&rdircos[i]);
      nargsused = 3;
    } else if ( !strcmp(option, "--sdircos") ) {
      if (nargc < 3) argnerr(option,3);
      for (i=0;i<3;i++) sscanf(pargv[i],"%f",&sdircos[i]);
      nargsused = 3;
    } else if ( !strcmp(option, "--fwhm") ) {
      if (nargc < 1) argnerr(option,1);
      sscanf(pargv[0],"%f",&fwhm);
      gstd = fwhm/sqrt(log(256.0));
      nargsused = 1;
    } else if (!strcmp(option, "--precision")) {
      if (nargc < 1) argnerr(option,1);
      precision = pargv[0];
      nargsused = 1;
    } else if (!strcmp(option, "--seed")) {
      if (nargc < 1) argnerr(option,1);
      sscanf(pargv[0],"%ld",&seed);
      nargsused = 1;
    } else if (!strcmp(option, "--seedfile")) {
      if (nargc < 1) argnerr(option,1);
      seedfile = pargv[0];
      nargsused = 1;
    } else if (!strcmp(option, "--pdf")) {
      if (nargc < 1) argnerr(option,1);
      pdfname = pargv[0];
      nargsused = 1;
    } else if (!strcmp(option, "--bb")) {
      if (nargc < 6) argnerr(option,6);
      sscanf(pargv[0],"%d",&boundingbox.x);
      sscanf(pargv[1],"%d",&boundingbox.y);
      sscanf(pargv[2],"%d",&boundingbox.z);
      sscanf(pargv[3],"%d",&boundingbox.dx);
      sscanf(pargv[4],"%d",&boundingbox.dy);
      sscanf(pargv[5],"%d",&boundingbox.dz);
      pdfname = "boundingbox";
      nargsused = 6;
    }
    else if (!strcasecmp(option, "--checker"))
      pdfname = "checker";
    else if (!strcmp(option, "--dof-num")) {
      if (nargc < 1) argnerr(option,1);
      sscanf(pargv[0],"%d",&numdof);
      nargsused = 1;
    } else if (!strcmp(option, "--val-a")) {
      if (nargc < 1) argnerr(option,1);
      sscanf(pargv[0],"%lf",&ValueA);
      nargsused = 1;
    } else if (!strcmp(option, "--val-b")) {
      if (nargc < 1) argnerr(option,1);
      sscanf(pargv[0],"%lf",&ValueB);
      nargsused = 1;
    } else if (!strcmp(option, "--radius")) {
      if (nargc < 1) argnerr(option,1);
      sscanf(pargv[0],"%lf",&voxradius);
      nargsused = 1;
    } else if (!strcmp(option, "--dof-den") || !strcmp(option, "--dof")) {
      if (nargc < 1) argnerr(option,1);
      sscanf(pargv[0],"%d",&dendof);
      nargsused = 1;
    } else if (!strcmp(option, "--gmean")) {
      if (nargc < 1) argnerr(option,1);
      sscanf(pargv[0],"%lf",&gausmean);
      nargsused = 1;
    } else if (!strcmp(option, "--gstd")) {
      if (nargc < 1) argnerr(option,1);
      sscanf(pargv[0],"%lf",&gausstd);
      nargsused = 1;
    } else if (!strcmp(option, "--delta-crsf")) {
      if (nargc < 4) argnerr(option,4);
      sscanf(pargv[0],"%d",&delta_crsf[0]);
      sscanf(pargv[1],"%d",&delta_crsf[1]);
      sscanf(pargv[2],"%d",&delta_crsf[2]);
      sscanf(pargv[3],"%d",&delta_crsf[3]);
      delta_crsf_speced = 1;
      nargsused = 4;
    } else if (!strcmp(option, "--delta-val")) {
      if (nargc < 1) argnerr(option,1);
      sscanf(pargv[0],"%lf",&delta_value);
      nargsused = 1;
    } else if (!strcmp(option, "--delta-val-off")) {
      if (nargc < 1) argnerr(option,1);
      sscanf(pargv[0],"%lf",&delta_off_value);
      nargsused = 1;
    } else if (!strcmp(option, "--spike")) {
      if (nargc < 1) argnerr(option,1);
      sscanf(pargv[0],"%d",&SpikeTP);
      nargsused = 1;
    } else {
      fprintf(stderr,"ERROR: Option %s unknown\n",option);
      if (singledash(option))
        fprintf(stderr,"       Did you really mean -%s ?\n",option);
      exit(-1);
    }
    nargc -= nargsused;
    pargv += nargsused;
  }
  return(0);
}
コード例 #26
0
int
main(int argc, char *argv[])
{
  char   **av, *in_fname;
  int    ac, nargs, i, j,  x, y, z, width, height, depth;
  MRI    *mri_flash[MAX_IMAGES], *mri_label, *mri_mask;
  int index;
  int    msec, minutes, seconds, nvolumes, nvolumes_total ;
  struct timeb start ;
  float max_val, min_val, value;
  float *LDAweight = NULL;
  float **LDAmeans = NULL; /* Centroid for each considered class */
  float *classSize =NULL; /* relative size of each class */
  MATRIX **SWs; /* Within class scatter-matrix for each considered class */
  MATRIX *AdjMatrix; /* Adjacency matrix of all classes */

  FILE *fp;

  int num_classes;
  double cnr;


  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mri_ms_compute_CNR.c,v 1.10 2011/03/02 00:04:55 nicks 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 < 2)
    usage_exit(1) ;

  printf("command line parsing finished\n");

  if (label_fname == NULL)
  {
    printf("Use -label option to specify file for segmentation \n");
    usage_exit(0);
  }


  if (have_weight == 1 && weight_fname == NULL)
  {
    printf("Use -weight option to specify file for input LDA weights \n") ;
    usage_exit(0);
  }

  if (have_weight == 1 && synth_fname == NULL)
  {
    printf("Use -synth option to specify file for output synthesized volume \n") ;
    usage_exit(0);
  }


  if (ldaflag)
  {
    MINLABEL = MIN(class1, class2);
    MAXLABEL = MAX(class1, class2);
  }

  num_classes = MAXLABEL - MINLABEL + 1;

  printf("Total of %d classes considered in LDA training\n", num_classes);

  if (num_classes <= 1)
  {
    printf("Need to specify at least two classes to evaluate CNR\n");
    usage_exit(0);
  }

  //////////////////////////////////////////////////////////////////////////////////
  /*** Read in the input multi-echo volumes ***/
  nvolumes = 0 ;
  for (i = 1 ; i < argc; i++)
  {
    in_fname = argv[i] ;
    printf("reading %s...\n", in_fname) ;

    mri_flash[nvolumes] = MRIread(in_fname) ;
    if (mri_flash[nvolumes] == NULL)
      ErrorExit(ERROR_NOFILE, "%s: could not read volume %s",
                Progname, in_fname) ;
    /* conform will convert all data to UCHAR, which will reduce data resolution*/
    printf("%s read in. \n", in_fname) ;
    if (conform)
    {
      MRI *mri_tmp ;

      printf("embedding and interpolating volume\n") ;
      mri_tmp = MRIconform(mri_flash[nvolumes]) ;
      mri_flash[nvolumes] = mri_tmp ;
    }

    /* Change all volumes to float type for convenience */
    if (mri_flash[nvolumes]->type != MRI_FLOAT)
    {
      printf("Volume %d type is %d\n", nvolumes+1, mri_flash[nvolumes]->type);
      MRI *mri_tmp;
      printf("Change data to float type \n");
      mri_tmp = MRIchangeType(mri_flash[nvolumes], MRI_FLOAT, 0, 1.0, 1);
      MRIfree(&mri_flash[nvolumes]);
      mri_flash[nvolumes] = mri_tmp; //swap
    }

    nvolumes++ ;
  }

  printf("All data read in\n");

  ///////////////////////////////////////////////////////////////////////////
  nvolumes_total = nvolumes ;   /* all volumes read in */

  for (i = 0 ; i < nvolumes ; i++)
  {
    for (j = i+1 ; j < nvolumes ; j++)
    {
      if ((mri_flash[i]->width != mri_flash[j]->width) ||
          (mri_flash[i]->height != mri_flash[j]->height) ||
          (mri_flash[i]->depth != mri_flash[j]->depth))
        ErrorExit(ERROR_BADPARM, "%s:\nvolumes %d (type %d) and %d (type %d) don't match (%d x %d x %d) vs (%d x %d x %d)\n",
                  Progname, i, mri_flash[i]->type, j, mri_flash[j]->type, mri_flash[i]->width,
                  mri_flash[i]->height, mri_flash[i]->depth,
                  mri_flash[j]->width, mri_flash[j]->height, mri_flash[j]->depth) ;
    }
  }

  width = mri_flash[0]->width;
  height = mri_flash[0]->height;
  depth = mri_flash[0]->depth;

  if (label_fname != NULL)
  {
    mri_label = MRIread(label_fname);
    if (!mri_label)
      ErrorExit(ERROR_NOFILE, "%s: could not read input volume %s\n",
                Progname, label_fname);

    if ((mri_label->width != mri_flash[0]->width) ||
        (mri_label->height != mri_flash[0]->height) ||
        (mri_label->depth != mri_flash[0]->depth))
      ErrorExit(ERROR_BADPARM, "%s: label volume size doesn't match data volumes\n", Progname);

    /* if(mri_label->type != MRI_UCHAR)
       ErrorExit(ERROR_BADPARM, "%s: label volume is not UCHAR type \n", Progname); */
  }

  if (mask_fname != NULL)
  {
    mri_mask = MRIread(mask_fname);
    if (!mri_mask)
      ErrorExit(ERROR_NOFILE, "%s: could not read input volume %s\n",
                Progname, mask_fname);

    if ((mri_mask->width != mri_flash[0]->width) ||
        (mri_mask->height != mri_flash[0]->height) ||
        (mri_mask->depth != mri_flash[0]->depth))
      ErrorExit(ERROR_BADPARM, "%s: mask volume size doesn't macth data volumes\n", Progname);

    if (mri_mask->type != MRI_UCHAR)
      ErrorExit(ERROR_BADPARM, "%s: mask volume is not UCHAR type \n", Progname);
  }
  else
  {
    mri_mask = MRIalloc(mri_flash[0]->width, mri_flash[0]->height, mri_flash[0]->depth, MRI_UCHAR);
    MRIcopyHeader(mri_flash[0], mri_mask);

    /* Simply set mask to be 1 everywhere */
    for (z=0; z < depth; z++)
      for (y=0; y< height; y++)
        for (x=0; x < width; x++)
        {
          MRIvox(mri_mask, x, y,z) = 1;
        }
  }


  if (debug_flag && window_flag)
  {
    /* Limit LDA to a local window */
    printf("Local window size = %d\n", window_size);
    window_size /= 2;
    for (z=0; z < depth; z++)
      for (y=0; y< height; y++)
        for (x=0; x < width; x++)
        {
          if (MRIvox(mri_mask, x, y,z) == 0) continue;

          if (z < (Gz - window_size) || z >(Gz + window_size)
              || y <(Gy - window_size) || y > (Gy + window_size)
              || x < (Gx - window_size) || x > (Gx + window_size))
            MRIvox(mri_mask, x, y,z) = 0;
        }

  }

  LDAweight = (float *)calloc(nvolumes_total, sizeof(float));

  /* Allocate memory */
  LDAmeans = (float **)malloc(num_classes*sizeof(float *));
  SWs = (MATRIX **)malloc(num_classes*sizeof(MATRIX *));
  classSize = (float *)malloc(num_classes*sizeof(float));
  for (i=0; i< num_classes; i++)
  {
    LDAmeans[i] = (float *)malloc(nvolumes_total*sizeof(float));
    SWs[i] = (MATRIX *)MatrixAlloc(nvolumes_total, nvolumes_total, MATRIX_REAL);
    if (SWs[i] == NULL || LDAmeans[i] == NULL)
      ErrorExit(ERROR_BADPARM, "%s: unable to allocate required memory \n", Progname);
  }

  if (ldaflag)
  {
    AdjMatrix = (MATRIX *)MatrixAlloc(num_classes, num_classes, MATRIX_REAL);

    /* The diagnoal entries of AdjMatrix is set to zero initially */
    for (i=1; i <= num_classes;i++)
      for (j=i; j <= num_classes; j++)
      {
        AdjMatrix->rptr[i][j] = 0.0;
        AdjMatrix->rptr[j][i] = 0.0;
      }

    AdjMatrix->rptr[class1-MINLABEL +1][class2-MINLABEL+1] = 1.0;
    AdjMatrix->rptr[class1-MINLABEL +1][class1-MINLABEL+1] = 1.0;
    AdjMatrix->rptr[class2-MINLABEL +1][class2-MINLABEL+1] = 1.0;
    AdjMatrix->rptr[class2-MINLABEL +1][class1-MINLABEL+1] = 1.0;
  }
  else if (MINLABEL <=2 && MAXLABEL >= 76)
  {
    printf("Manually set adjacent matrix \n");

    AdjMatrix = (MATRIX *)MatrixAlloc(num_classes, num_classes, MATRIX_REAL);

    /* The diagnoal entries of AdjMatrix is set to zero initially */
    for (i=1; i <= num_classes;i++)
      for (j=i; j <= num_classes; j++)
      {
        AdjMatrix->rptr[i][j] = 0.0;
        AdjMatrix->rptr[j][i] = 0.0;
      }

    for (index = 0; index < CNR_pairs; index++)
    {
      i = ilist[index] - MINLABEL;
      j = jlist[index] - MINLABEL;

      AdjMatrix->rptr[i+1][j+1] = 1.0;
      AdjMatrix->rptr[j+1][i+1] = 1.0;
    }

    /* left-hemisphere */
    /*
    AdjMatrix->rptr[2+1-MINLABEL][17+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[17+1-MINLABEL][18+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[3+1-MINLABEL][17+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[5+1-MINLABEL][17+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[4+1-MINLABEL][17+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[18+1-MINLABEL][2+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[18+1-MINLABEL][3+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[18+1-MINLABEL][5+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[18+1-MINLABEL][4+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[10+1-MINLABEL][11+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[10+1-MINLABEL][4+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[10+1-MINLABEL][12+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[10+1-MINLABEL][2+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[2+1-MINLABEL][3+1-MINLABEL] = 1.0;
    */

    /* right-hemisphere */
    /*
    AdjMatrix->rptr[53+1-MINLABEL][41+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[53+1-MINLABEL][54+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[53+1-MINLABEL][42+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[53+1-MINLABEL][44+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[53+1-MINLABEL][43+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[54+1-MINLABEL][41+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[54+1-MINLABEL][42+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[54+1-MINLABEL][44+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[54+1-MINLABEL][43+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[49+1-MINLABEL][50+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[49+1-MINLABEL][43+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[49+1-MINLABEL][51+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[49+1-MINLABEL][41+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[41+1-MINLABEL][42+1-MINLABEL] = 1.0;

    for(i=1; i < num_classes;i++)
      for(j=i+1; j <= num_classes; j++){
    if(AdjMatrix->rptr[i][j] > 0.5)
    AdjMatrix->rptr[j][i] = AdjMatrix->rptr[i][j];
    else
    AdjMatrix->rptr[i][j] = AdjMatrix->rptr[j][i];
      }
    */

    /*    AdjMatrix->rptr[2+1-MINLABEL][3+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[2+1-MINLABEL][10+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[2+1-MINLABEL][11+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[2+1-MINLABEL][12+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[2+1-MINLABEL][13+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[2+1-MINLABEL][17+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[2+1-MINLABEL][18+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[3+1-MINLABEL][12+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[3+1-MINLABEL][17+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[3+1-MINLABEL][18+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[4+1-MINLABEL][10+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[4+1-MINLABEL][11+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[10+1-MINLABEL][11+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[10+1-MINLABEL][13+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[12+1-MINLABEL][13+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[12+1-MINLABEL][26+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[17+1-MINLABEL][18+1-MINLABEL] = 1.0;
    */
    /* right-hemisphere */
    /* AdjMatrix->rptr[41+1-MINLABEL][42+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[41+1-MINLABEL][49+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[41+1-MINLABEL][50+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[41+1-MINLABEL][51+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[41+1-MINLABEL][52+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[41+1-MINLABEL][53+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[41+1-MINLABEL][54+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[42+1-MINLABEL][51+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[42+1-MINLABEL][53+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[42+1-MINLABEL][54+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[43+1-MINLABEL][49+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[43+1-MINLABEL][50+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[49+1-MINLABEL][50+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[49+1-MINLABEL][52+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[51+1-MINLABEL][52+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[51+1-MINLABEL][58+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[53+1-MINLABEL][54+1-MINLABEL] = 1.0;
    */
  }
  else
    AdjMatrix = ComputeAdjMatrix(mri_label, mri_mask, MINLABEL, MAXLABEL);
  /* AdjMatrix may need manual adjusted to avoid meaningless comparisons
   * such as computing CNR between left WM and right WM
   */


  for (i=1; i <= num_classes;i++)
    for (j=1; j <= num_classes; j++)
    {
      if (j==i) continue;
      /* the diagonal term will indicate whether the class is useful or not */
      AdjMatrix->rptr[i][i] +=  AdjMatrix->rptr[i][j] + AdjMatrix->rptr[j][i];
    }


  printf("Compute individual class statistics\n");
  /* Compute class means and covariance matrix */
  /* Note that here SWs will be covaraince matrix, not scatter matrix */
  for (i=0; i < num_classes; i++)
  {
    if (AdjMatrix->rptr[i+1][i+1] < 0.5) continue;
    computeClassStats(LDAmeans[i], SWs[i], &classSize[i], mri_flash, mri_label, mri_mask, nvolumes_total, MINLABEL + i);
  }
  printf("class statistics computed \n");

  if (fname != NULL)
    fp = fopen(fname, "w");
  else
    fp = 0;

  printf("compute pair-wise CNR/Mahalanobis distances \n");
  if (ldaflag)
  {
    for (i=0; i <num_classes-1;i++)
      for (j=i+1; j < num_classes; j++)
      {
        if (AdjMatrix->rptr[i+1][j+1] < 0.5) continue;
        cnr = computePairCNR(LDAmeans[i], LDAmeans[j], SWs[i], SWs[j], classSize[i],  classSize[j], nvolumes_total, LDAweight, 1);
        if (fp)
          fprintf(fp, "%9.4f ", (float)cnr);

        printf("CNR of class %d and class %d is %g\n", i+MINLABEL, j+MINLABEL, cnr);

      }

    if (fp)
    {
      fprintf(fp, "\n");
      fclose(fp);
    }

  }
  else
  {

    for (index = 0; index < CNR_pairs; index++)
    {
      i = ilist[index] - MINLABEL;
      j = jlist[index] - MINLABEL;

      if (AdjMatrix->rptr[i+1][j+1] < 0.5) continue;
      if (i== (2-MINLABEL) && j == (3-MINLABEL) && nvolumes_total > 1)
        cnr = computePairCNR(LDAmeans[i], LDAmeans[j], SWs[i], SWs[j], classSize[i],  classSize[j], nvolumes_total, LDAweight, 1);
      else
        cnr = computePairCNR(LDAmeans[i], LDAmeans[j], SWs[i], SWs[j], classSize[i], classSize[j], nvolumes_total, 0, 0);

      if (fp)
        fprintf(fp, "%9.4f ", (float)cnr);

      printf("CNR of class %d and class %d is %g\n", i+MINLABEL, j+MINLABEL, cnr);

    }

    if (fp)
    {
      fprintf(fp, "\n");
      fclose(fp);
    }
  }

  /* output weights for optimize CNR for class 2 and class 3 */
  if (weight_fname != NULL)
  {
    output_weights_to_file(LDAweight, weight_fname, nvolumes_total);
  }

  free(classSize);

  for (i=0; i< num_classes; i++)
  {
    free(LDAmeans[i]);
    MatrixFree(&SWs[i]);
  }
  free(LDAmeans);
  free(SWs);
  MatrixFree(&AdjMatrix);

  if (nvolumes_total > 1 && ((MINLABEL <=2 && MAXLABEL >= 3) || ldaflag))
  {
    if (ldaflag)
    {
      printf("LDA weights for %d-%d are: \n", class1, class2);
    }
    else
    {
      printf("LDA weights for 2-3 are: \n");
    }
    for (i=0; i < nvolumes_total; i++)
    {
      printf("%g ", LDAweight[i]);
    }
    printf("\n");

    if (synth_fname != NULL)
    {
      /* linear projection of input volumes to a 1D volume */
      min_val = 10000.0;
      max_val = -10000.0;
      for (z=0; z < depth; z++)
        for (y=0; y< height; y++)
          for (x=0; x < width; x++)
          {
            if (whole_volume == 0 && MRIvox(mri_mask, x, y, z) == 0) continue;

            value = 0.0;

            for (i=0; i < nvolumes_total; i++)
            {
              value += MRIFvox(mri_flash[i], x, y, z)*LDAweight[i];
            }



            if (max_val < value) max_val = value;
            if (min_val > value) min_val = value;

            /* Borrow mri_flash[0] to store the float values first */
            MRIFvox(mri_flash[0], x, y, z) = value;
          }

      printf("max_val = %g, min_val = %g \n", max_val, min_val);

      /* Scale output to [0, 255] */
      for (z=0; z < depth; z++)
        for (y=0; y< height; y++)
          for (x=0; x < width; x++)
          {
            if (whole_volume == 0 && MRIvox(mri_mask, x, y, z) == 0) continue;

            value = (MRIFvox(mri_flash[0], x, y, z) - min_val)*255.0/(max_val - min_val) + 0.5; /* +0.5 for round-off */

            if (value > 255.0) value = 255.0;
            if (value < 0) value = 0;

            /* Borrow mri_flash[0] to store the float values first */
            MRIvox(mri_mask, x, y, z) = (BUFTYPE) value;
          }

      /* Output synthesized volume */
      MRIwrite(mri_mask, synth_fname);
    }
  }

  free(LDAweight);

  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  printf("LDA took %d minutes and %d seconds.\n", minutes, seconds) ;

  MRIfree(&mri_mask);

  MRIfree(&mri_label);


  for (i=0; i < nvolumes_total; i++)
  {
    MRIfree(&mri_flash[i]);
  }
  exit(0);
}
コード例 #27
0
ファイル: mri_ms_LDA.c プロジェクト: ewong718/freesurfer
int
main(int argc, char *argv[]) {
  char   **av, *in_fname;
  int    ac, nargs, i, j,  x, y, z, width, height, depth;
  MRI    *mri_flash[MAX_IMAGES], *mri_label, *mri_mask, *mri_tmp;
  int    msec, minutes, seconds, nvolumes, nvolumes_total ;
  struct timeb start ;
  float max_val, min_val, value;
  float *LDAmean1, *LDAmean2, *LDAweight;
  int label;
  double sum_white, sum_gray;
  int count_white, count_gray;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mri_ms_LDA.c,v 1.4 2011/03/02 00:04:23 nicks 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 < 2)
    usage_exit(1) ;

  printf("command line parsing finished\n");

  if (have_weight == 0 && ldaflag == 0) {
    printf("Use -lda option to specify two class labels to optimize CNR on \n");
    usage_exit(0);
  }

  if (have_weight == 0 && label_fname == NULL) {
    printf("Use -label option to specify file for segmentation \n");
    usage_exit(0);
  }


  if (have_weight == 1 && weight_fname == NULL) {
    printf("Use -weight option to specify file for input LDA weights \n") ;
    usage_exit(0);
  }

  if (have_weight == 1 && synth_fname == NULL) {
    printf("Use -synth option to specify file for output synthesized volume \n") ;
    usage_exit(0);
  }

  //////////////////////////////////////////////////////////////////////////////////
  /*** Read in the input multi-echo volumes ***/
  nvolumes = 0 ;
  for (i = 1 ; i < argc; i++) {
    in_fname = argv[i] ;
    printf("reading %s...\n", in_fname) ;

    mri_flash[nvolumes] = MRIread(in_fname) ;
    if (mri_flash[nvolumes] == NULL)
      ErrorExit(ERROR_NOFILE, "%s: could not read volume %s",
                Progname, in_fname) ;
    /* conform will convert all data to UCHAR, which will reduce data resolution*/
    printf("%s read in. \n", in_fname) ;
    if (conform) {
      printf("embedding and interpolating volume\n") ;
      mri_tmp = MRIconform(mri_flash[nvolumes]) ;
      MRIfree(&mri_flash[nvolumes]);
      mri_flash[nvolumes] = mri_tmp ;
    }

    /* Change all volumes to float type for convenience */
    if (mri_flash[nvolumes]->type != MRI_FLOAT) {
      printf("Volume %d type is %d\n", nvolumes+1, mri_flash[nvolumes]->type);
      printf("Change data to float type \n");
      mri_tmp = MRIchangeType(mri_flash[nvolumes], MRI_FLOAT, 0, 1.0, 1);
      MRIfree(&mri_flash[nvolumes]);
      mri_flash[nvolumes] = mri_tmp; //swap
    }

    nvolumes++ ;
  }

  printf("All data read in\n");

  ///////////////////////////////////////////////////////////////////////////
  nvolumes_total = nvolumes ;   /* all volumes read in */

  for (i = 0 ; i < nvolumes ; i++) {
    for (j = i+1 ; j < nvolumes ; j++) {
      if ((mri_flash[i]->width != mri_flash[j]->width) ||
          (mri_flash[i]->height != mri_flash[j]->height) ||
          (mri_flash[i]->depth != mri_flash[j]->depth))
        ErrorExit(ERROR_BADPARM, "%s:\nvolumes %d (type %d) and %d (type %d) don't match (%d x %d x %d) vs (%d x %d x %d)\n",
                  Progname, i, mri_flash[i]->type, j, mri_flash[j]->type, mri_flash[i]->width,
                  mri_flash[i]->height, mri_flash[i]->depth,
                  mri_flash[j]->width, mri_flash[j]->height, mri_flash[j]->depth) ;
    }
  }

  width = mri_flash[0]->width;
  height = mri_flash[0]->height;
  depth = mri_flash[0]->depth;

  if (label_fname != NULL) {
    mri_label = MRIread(label_fname);
    if (!mri_label)
      ErrorExit(ERROR_NOFILE, "%s: could not read input volume %s\n",
                Progname, label_fname);

    if ((mri_label->width != mri_flash[0]->width) ||
        (mri_label->height != mri_flash[0]->height) ||
        (mri_label->depth != mri_flash[0]->depth))
      ErrorExit(ERROR_BADPARM, "%s: label volume size doesn't match data volumes\n", Progname);

    /* if(mri_label->type != MRI_UCHAR)
       ErrorExit(ERROR_BADPARM, "%s: label volume is not UCHAR type \n", Progname); */
  }

  if (mask_fname != NULL) {
    mri_mask = MRIread(mask_fname);
    if (!mri_mask)
      ErrorExit(ERROR_NOFILE, "%s: could not read input volume %s\n",
                Progname, mask_fname);

    if ((mri_mask->width != mri_flash[0]->width) ||
        (mri_mask->height != mri_flash[0]->height) ||
        (mri_mask->depth != mri_flash[0]->depth))
      ErrorExit(ERROR_BADPARM, "%s: mask volume size doesn't macth data volumes\n", Progname);

    if (mri_mask->type != MRI_UCHAR)
      ErrorExit(ERROR_BADPARM, "%s: mask volume is not UCHAR type \n", Progname);
  } else {

    if (have_weight == 1)
      noise_threshold = - 1e20;

    printf("Threshold input vol1 at %g to create mask \n", noise_threshold);
    printf("this threshold is useful to process skull-stripped data \n");

    mri_mask = MRIalloc(mri_flash[0]->width, mri_flash[0]->height, mri_flash[0]->depth, MRI_UCHAR);
    MRIcopyHeader(mri_flash[0], mri_mask);

    /* Simply set mask to be 1 everywhere */
    for (z=0; z < depth; z++)
      for (y=0; y< height; y++)
        for (x=0; x < width; x++) {

          if ((float)MRIgetVoxVal(mri_flash[0], x, y,z,0) < noise_threshold)
            MRIvox(mri_mask, x, y,z) = 0;
          else
            MRIvox(mri_mask, x, y,z) = 1;
        }
  }

  /* Normalize input volumes */
  if (normflag) {
    printf("Normalize input volumes to zero mean, variance 1\n");
    for (i=0; i <nvolumes_total; i++) {
      mri_flash[i] = MRInormalizeXH(mri_flash[i], mri_flash[i], mri_mask);
    }
    printf("Normalization done.\n");
  }

  if (0) {
    printf("Using both hemi-sphere by changing rh-labels\n");
    for (z=0; z < depth; z++)
      for (y=0; y< height; y++)
        for (x=0; x < width; x++) {
          label = (int)MRIgetVoxVal(mri_label, x, y,z,0);
          if (label == 41) /* white matter */
            MRIsetVoxVal(mri_label, x, y, z, 0, 2);
          else if (label == 42) /* gm */
            MRIsetVoxVal(mri_label, x, y, z, 0, 3);
        }
  }


  if (debug_flag && window_flag) {
    /* Limit LDA to a local window */
    printf("Local window size = %d\n", window_size);
    window_size /= 2;
    for (z=0; z < depth; z++)
      for (y=0; y< height; y++)
        for (x=0; x < width; x++) {
          if (MRIvox(mri_mask, x, y,z) == 0) continue;

          if (z < (Gz - window_size) || z >(Gz + window_size)
              || y <(Gy - window_size) || y > (Gy + window_size)
              || x < (Gx - window_size) || x > (Gx + window_size))
            MRIvox(mri_mask, x, y,z) = 0;
        }

  }

  LDAmean1 = (float *)malloc(nvolumes_total*sizeof(float));
  LDAmean2 = (float *)malloc(nvolumes_total*sizeof(float));
  LDAweight = (float *)malloc(nvolumes_total*sizeof(float));

  if (have_weight) {
    printf("Read in LDA weights from weight-file\n");
    input_weights_to_file(LDAweight, weight_fname, nvolumes_total);
  } else { /* compute LDA weights */
    printf("Compute LDA weights to maximize CNR for region %d and region %d\n", class1, class2);
    /* Compute class means */
    update_LDAmeans(mri_flash, mri_label, mri_mask, LDAmean1, LDAmean2, nvolumes_total, class1, class2);
    printf("class means computed \n");

    /* Compute Fisher's LDA weights */
    computeLDAweights(LDAweight, mri_flash, mri_label, mri_mask, LDAmean1, LDAmean2, nvolumes_total, class1, class2);

    if (weight_fname != NULL) {
      output_weights_to_file(LDAweight, weight_fname, nvolumes_total);
    }
  }

  printf("LDA weights are: \n");
  for (i=0; i < nvolumes_total; i++) {
    printf("%g ", LDAweight[i]);
  }
  printf("\n");

  if (synth_fname != NULL) {
    /* linear projection of input volumes to a 1D volume */
    min_val = 10000.0;
    max_val = -10000.0;
    for (z=0; z < depth; z++)
      for (y=0; y< height; y++)
        for (x=0; x < width; x++) {
          if (whole_volume == 0 && MRIvox(mri_mask, x, y, z) == 0) continue;

          value = 0.0;

          for (i=0; i < nvolumes_total; i++) {
            value += MRIFvox(mri_flash[i], x, y, z)*LDAweight[i];
          }

          //     if(value < 0) value = 0;

          if (max_val < value) max_val = value;
          if (min_val > value) min_val = value;

          /* Borrow mri_flash[0] to store the float values first */
          MRIFvox(mri_flash[0], x, y, z) = value;
        }

    printf("max_val = %g, min_val = %g \n", max_val, min_val);

    /* Check to make sure class1 has higher intensity than class2 */
    if (have_weight == 0) {
      sum_white =0;
      count_white = 0;
      sum_gray = 0;
      count_gray = 0;
      for (z=0; z < depth; z++) {
        if (count_white > 300 && count_gray > 300) break;
        for (y=0; y< height; y++) {
          for (x=0; x < width; x++) {

            if ((int)MRIgetVoxVal(mri_label, x, y,z,0) == class1) {
              sum_white += MRIFvox(mri_flash[0], x, y, z);
              count_white += 1;
            } else if ((int)MRIgetVoxVal(mri_label, x, y,z,0) == class2) {
              sum_gray += MRIFvox(mri_flash[0], x, y, z);
              count_gray += 1;
            }
          }
        }
      }

      if (count_white > 1 && count_gray > 1) {
        if (sum_white *count_gray < sum_gray*count_white) {
          for (z=0; z < depth; z++)
            for (y=0; y< height; y++)
              for (x=0; x < width; x++) {
                if (whole_volume == 0 && MRIvox(mri_mask, x, y, z) == 0) continue;
                value = MRIFvox(mri_flash[0], x, y, z);
                MRIFvox(mri_flash[0], x, y, z) = max_val - value;
              }
          max_val = max_val - min_val;
          min_val = 0;
        }
      }
    }

    /* The following is copied to be consistent with mri_synthesize */
    /* Don't know why add min_val, minus should make more sense */
    for (z=0; z < depth; z++)
      for (y=0; y< height; y++)
        for (x=0; x < width; x++) {
          if (whole_volume == 0 && MRIvox(mri_mask, x, y, z) == 0) {
            MRIFvox(mri_flash[0], x, y, z) = 0; /*background always set to 0 */
            continue;
          }
          /* Borrow mri_flash[0] to store the float values first */
          if (shift_value > 0) {
            value = MRIFvox(mri_flash[0], x, y, z) + shift_value;
            if (value < 0) value = 0;
            MRIFvox(mri_flash[0], x, y, z) = value;
          } else if (mask_fname != NULL)
            MRIFvox(mri_flash[0], x, y, z) -= min_val;
        }


    MRIfree(&mri_mask);
    if (mri_flash[0]->type == out_type) {
      mri_mask = MRIcopy(mri_flash[0], mri_mask);
    } else {
      mri_mask = MRIchangeType(mri_flash[0], out_type, 0.1, 0.99, 0);
    }

    /* Scale output to [0, 255] */
    if (0) {
      for (z=0; z < depth; z++)
        for (y=0; y< height; y++)
          for (x=0; x < width; x++) {
            if (whole_volume == 0 && MRIvox(mri_mask, x, y, z) == 0) continue;

            value = (MRIFvox(mri_flash[0], x, y, z) - min_val)*255.0/(max_val - min_val) + 0.5; /* +0.5 for round-off */

            if (value > 255.0) value = 255.0;
            if (value < 0) value = 0;

            /* Borrow mri_flash[0] to store the float values first */
            MRIvox(mri_mask, x, y, z) = (BUFTYPE) value;
          }
    }

    /* Output synthesized volume */
    MRIwrite(mri_mask, synth_fname);

  }

  free(LDAmean1);
  free(LDAmean2);
  free(LDAweight);

  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  printf("LDA took %d minutes and %d seconds.\n", minutes, seconds) ;

  MRIfree(&mri_mask);

  if (label_fname)
    MRIfree(&mri_label);


  for (i=0; i < nvolumes_total; i++) {
    MRIfree(&mri_flash[i]);
  }
  exit(0);
}
コード例 #28
0
int main(int argc, char *argv[]) {
  char **av;
  MRI *mri_T1, *mri_tmp, *mri_ctrl, *mri_in, *mri_out;
  MRI *mri_snr, *mri_bias;
  MRI *mri_mask1 = NULL;
  MRI *mri_mask2 = NULL;

  int ac, nargs;
  int  width, height, depth, x, y, z;
  int mask1_set = 0;
  int mask2_set = 0;
  int i, j, k, cx, cy, cz, count;
  LTA          *lta = 0;
  int          transform_type;
  double mean, std, value, src, bias, norm;
//  HISTOGRAM *h;
//  float bin_size;
//  int nbins, bin_no;
  double mean1, std1, mean2, std2, count1, count2, slope, offset;
  VOL_GEOM vgtmp;
  LT *lt = NULL;
  MATRIX *m_tmp = NULL;

  Progname = argv[0];

  nargs = handle_version_option
          (argc, argv,
           "$Id: mri_normalize_tp2.c,v 1.8 2011/03/02 00:04:23 nicks Exp $",
           "$Name: stable5 $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs ;

  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(1);

  if (tp1_ctrl_fname == NULL  || tp1_T1_fname == NULL) {
    printf("Use options to specify ctrl volume and T1 volume for tp1\n");
    usage(1);
  }

  mri_in = MRIread(argv[1]) ;
  if (!mri_in)
    ErrorExit(ERROR_BADPARM, "%s: could not read input volume %s",
              Progname, argv[1]) ;

  mri_T1 = MRIread(tp1_T1_fname) ;
  if (!mri_T1)
    ErrorExit(ERROR_BADPARM, "%s: could not read T1 volume for tp1 %s",
              Progname, tp1_T1_fname) ;

  mri_ctrl = MRIread(tp1_ctrl_fname) ;
  if (!mri_ctrl)
    ErrorExit(ERROR_BADPARM,
              "%s: could not read control points volume for tp1 %s",
              Progname, tp1_ctrl_fname) ;

  if ((mri_in->width != mri_T1->width) ||
      (mri_in->height != mri_T1->height) ||
      (mri_in->depth != mri_T1->depth) ||
      (mri_in->width != mri_ctrl->width) ||
      (mri_in->height != mri_ctrl->height) ||
      (mri_in->depth != mri_ctrl->depth)
     ) ErrorExit
         (ERROR_BADPARM,
          "%s: three input volumes have different sizes \n", Progname);

  if (mask1_fname) {
    mri_mask1 = MRIread(mask1_fname) ;
    if (!mri_mask1)
      ErrorExit(ERROR_BADPARM,
                "%s, could not read mask volume for tp1 %s",
                Progname, mask1_fname);
    mask1_set = 1;
    if ((mri_mask1->width != mri_in->width) ||
        (mri_mask1->height != mri_in->height) ||
        (mri_mask1->depth != mri_in->depth))
      ErrorExit
      (ERROR_BADPARM,
       "%s:  mask volumes have different sizes than other volumes \n",
       Progname);
  }
  if (mask2_fname) {
    mri_mask2 = MRIread(mask2_fname) ;
    if (!mri_mask2)
      ErrorExit
      (ERROR_BADPARM,
       "%s, could not read mask volume for tp2 %s",
       Progname, mask2_fname);
    mask2_set = 1;
    if ((mri_mask2->width != mri_T1->width) ||
        (mri_mask2->height != mri_T1->height) ||
        (mri_mask2->depth != mri_T1->depth)
       )
      ErrorExit
      (ERROR_BADPARM,
       "%s:  mask volumes have different sizes than other volumes \n",
       Progname);
  }

  width = mri_in->width ;
  height = mri_in->height ;
  depth = mri_in->depth ;

  //nbins = 200;
  //h = HISTOalloc(nbins);

  mri_out = MRIclone(mri_in, NULL) ;

  /* Read LTA transform and apply it to mri_ctrl */
  if (xform_fname != NULL) {
    // read transform
    transform_type =  TransformFileNameType(xform_fname);

    if (transform_type == MNI_TRANSFORM_TYPE ||
        transform_type == TRANSFORM_ARRAY_TYPE ||
        transform_type == REGISTER_DAT ||
        transform_type == FSLREG_TYPE
       ) {
      printf("Reading transform ...\n");
      lta = LTAreadEx(xform_fname) ;
      if (!lta)
        ErrorExit(ERROR_NOFILE, "%s: could not read transform file %s",
                  Progname, xform_fname) ;

      if (transform_type == FSLREG_TYPE) {
        if (lta_src == 0 || lta_dst == 0) {
          fprintf
          (stderr,
           "ERROR: fslmat does not have information "
           "on the src and dst volumes\n");
          fprintf
          (stderr,
           "ERROR: you must give options '-lta_src' and "
           "'-lta_dst' to specify the src and dst volume infos\n");
        }

        LTAmodifySrcDstGeom
        (lta, lta_src, lta_dst); // add src and dst information
        LTAchangeType(lta, LINEAR_VOX_TO_VOX); //this is necessary
      }

      if (lta->xforms[0].src.valid == 0) {
        if (lta_src == 0) {
          fprintf
          (stderr,
           "The transform does not have the valid src volume info.\n");
          fprintf
          (stderr,
           "Either you give src volume info by option -lta_src or\n");
          fprintf(stderr, "make the transform to have the valid src info.\n");
          ErrorExit(ERROR_BAD_PARM, "Bailing out...\n");
        } else {
          LTAmodifySrcDstGeom(lta, lta_src, NULL); // add src information
          //   getVolGeom(lta_src, &lt->src);
        }
      }
      if (lta->xforms[0].dst.valid == 0) {
        if (lta_dst == 0) {
          fprintf
          (stderr,
           "The transform does not have the valid dst volume info.\n");
          fprintf
          (stderr,
           "Either you give src volume info by option -lta_dst or\n");
          fprintf
          (stderr,
           "make the transform to have the valid dst info.\n");
          fprintf
          (stderr,
           "If the dst was average_305, then you can set\n");
          fprintf
          (stderr,
           "environmental variable USE_AVERAGE305 true\n");
          fprintf
          (stderr,
           "without giving the dst volume for RAS-to-RAS transform.\n");
          ErrorExit(ERROR_BAD_PARM, "Bailing out...\n");
        } else {
          LTAmodifySrcDstGeom(lta, NULL, lta_dst); // add  dst information
        }
      }
    } else {
      ErrorExit
      (ERROR_BADPARM,
       "transform is not of MNI, nor Register.dat, nor FSLMAT type");
    }

    if (invert) {
      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) {
        fprintf
        (stderr,
         "WARNING:***********************************************\n");
        fprintf
        (stderr,
         "WARNING: dst volume infor is invalid.  "
         "Most likely produce wrong inverse.\n");
        fprintf
        (stderr,
         "WARNING:***********************************************\n");
      }
      copyVolGeom(&lt->dst, &vgtmp);
      copyVolGeom(&lt->src, &lt->dst);
      copyVolGeom(&vgtmp, &lt->src);
    }

    //    LTAchangeType(lta, LINEAR_VOX_TO_VOX);

    /* apply lta to the ctrl volume */
    mri_tmp = MRIalloc(mri_ctrl->width,
                       mri_ctrl->height,
                       mri_ctrl->depth,
                       mri_ctrl->type) ;
    MRIcopyHeader(mri_in, mri_tmp) ;
    // this function doesn't do NEAREST at all!!
    // I found the bug, in LTAtransformInterp()
    mri_tmp = LTAtransformInterp(mri_ctrl, mri_tmp, lta, SAMPLE_NEAREST);

    MRIfree(&mri_ctrl);
    mri_ctrl = mri_tmp;

    if (mask1_fname != NULL && mask2_fname == NULL) {
      printf("map mask for tp1 to get mask for tp2 ...\n");
      mri_mask2 = MRIalloc(mri_in->width,
                           mri_in->height,
                           mri_in->depth,
                           mri_mask1->type) ;
      MRIcopyHeader(mri_in, mri_mask2) ;

      mri_mask2 = LTAtransformInterp(mri_mask1,
                                     mri_mask2,
                                     lta,
                                     SAMPLE_NEAREST);
      mask2_set = 1;
      if (debug_flag)
        MRIwrite(mri_mask2, "mri_mask2.mgz");
    } else if (mask2_fname != NULL && mask1_fname == NULL) {
      printf("map mask for tp2 to get mask for tp1 ...\n");
      //need to invert lta first
      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];

      copyVolGeom(&lt->dst, &vgtmp);
      copyVolGeom(&lt->src, &lt->dst);
      copyVolGeom(&vgtmp, &lt->src);

      mri_mask1 = MRIalloc(mri_T1->width,
                           mri_T1->height,
                           mri_T1->depth,
                           mri_mask2->type) ;
      MRIcopyHeader(mri_T1, mri_mask1) ;

      mri_mask1 = LTAtransformInterp(mri_mask2,
                                     mri_mask1,
                                     lta,
                                     SAMPLE_NEAREST);
      mask1_set = 1;
      if (debug_flag)
        MRIwrite(mri_mask1, "mri_mask1.mgz");
    }

    if (lta_src)
      MRIfree(&lta_src);
    if (lta_dst)
      MRIfree(&lta_dst);

    if (lta)
      LTAfree(&lta);
  }   /* if (xform_fname != NULL) */

  if (debug_flag) {
    //    MRIwrite(mri_snr, "snr.mgz");
    MRIwrite(mri_ctrl, "ctrl.mgz");
  }

  if (mask1_set == 0) {
    //create mask1
    mri_mask1 = MRIalloc(mri_T1->width,
                         mri_T1->height,
                         mri_T1->depth,
                         MRI_UCHAR) ;
    for (z=0; z < depth; z++)
      for (y=0; y< height; y++)
        for (x=0; x < width; x++) {
          if (MRIgetVoxVal(mri_T1, x, y, z, 0) < noise_threshold) {
            MRIvox(mri_mask1,x,y,z) = 0;
          } else
            MRIvox(mri_mask1,x,y,z) = 1;
        }
  }

  if (mask2_set == 0) {
    //create mask2
    mri_mask2 = MRIalloc(mri_in->width,
                         mri_in->height,
                         mri_in->depth,
                         MRI_UCHAR) ;
    for (z=0; z < depth; z++)
      for (y=0; y< height; y++)
        for (x=0; x < width; x++) {
          if (MRIgetVoxVal(mri_in, x, y, z, 0) < noise_threshold) {
            MRIvox(mri_mask2,x,y,z) = 0;
          } else
            MRIvox(mri_mask2,x,y,z) = 1;
        }
  }


#if 0
  /* compute the mean and std of T1 volume */
  /* Using only high SNR points */
  mri_snr = MRIalloc(mri_T1->width, mri_T1->height, mri_T1->depth, MRI_FLOAT) ;
  MRIcopyHeader(mri_T1, mri_snr) ;

  h->bin_size = bin_size = 0.5;
  for (bin_no = 0; bin_no < nbins; bin_no++)
    h->bins[bin_no] = (bin_no)*bin_size;

  for (z=0; z < depth; z++)
    for (y=0; y< height; y++)
      for (x=0; x < width; x++) {
        if (MRIgetVoxVal(mri_T1, x, y, z, 0) < noise_threshold) {
          MRIFvox(mri_snr,x,y,z) = 0;
          continue;
        }
        mean = 0;
        std = 0;
        count = 0;
        for (i=-1; i<=1; i++)
          for (j=-1; j<=1; j++)
            for (k=-1;k<=1;k++) {
              cx = x+i;
              cy = y+j, cz = z+k;

              if (cx < 0 ||
                  cx >= width ||
                  cy < 0 ||
                  cy >= height ||
                  cz < 0 ||
                  cz >= depth) continue;
              count++;
              value = MRIgetVoxVal(mri_T1, cx, cy, cz, 0);
              mean += value;
              std += value*value;
            }

        mean /= (count + 1e-30);
        std /=  (count + 1e-30);

        std = std - mean *mean;

        if (std <= 0)
          std = 0;
        value = mean/sqrt(std);

        MRIFvox(mri_snr,x,y,z) = value;
        bin_no = nint((float)value/(float)bin_size);
        if (bin_no >= nbins) bin_no = nbins - 1;
        h->counts[bin_no]++;
      }

  for (num = 0.0f, b = h->nbins - 1; b >= 1; b --) {
    num += h->counts[b];
    if (num > 20000) /* this may make me only use WM points,
                        is it good to use only WM to compute
                        scale of intensity?? */
      break;
  }

  printf("using SNR threshold %2.3f at bin %d\n", h->bins[b], b);

  mean1 = 0;
  std1 = 0;
  count1 = 0;
  for (z=0; z < depth; z++)
    for (y=0; y< height; y++)
      for (x=0; x < width; x++) {
        if (MRIgetVoxVal(mri_T1, x, y, z, 0) < noise_threshold) {
          continue;
        }

        value = MRIFvox(mri_snr,x,y,z);

        if (value < h->bins[b]) continue;

        value = MRIgetVoxVal(mri_T1, x, y, z, 0);
        count1++;
        mean1 += value;
        std1 += value*value;

      }

  MRIfree(&mri_snr);
#else
  printf("compute mean and std of tp1 volume within masked area...\n");
  mean1 = 0;
  std1 = 0;
  count1 = 0;
  for (z=0; z < depth; z++)
    for (y=0; y< height; y++)
      for (x=0; x < width; x++) {
        if (MRIgetVoxVal(mri_mask1, x, y, z, 0) <= 1e-30) {
          continue;
        }

        value = MRIgetVoxVal(mri_T1, x, y, z, 0);


        count1++;
        mean1 += value;
        std1 += value*value;

      }

#endif

  mean1 /= (count1 + 1e-30);
  std1 /= (count1 + 1e-30);
  std1 = std1 - mean1*mean1;
  if (std1 <= 0)
    printf("warning: negative std for T1 volume. \n");
  else
    printf("mean and variance for tp1 volume are %g and %g\n", mean1, std1);

  printf("now compute SNR and stats for input volume ... \n");
  mri_snr = MRIalloc(mri_in->width, mri_in->height, mri_in->depth, MRI_FLOAT) ;
  MRIcopyHeader(mri_in, mri_snr) ;
  //HISTOclear(h,h);
  //h->bin_size = bin_size = 0.5;
  //for (bin_no = 0; bin_no < nbins; bin_no++)
  //  h->bins[bin_no] = (bin_no)*bin_size;

  for (z=0; z < depth; z++)
    for (y=0; y< height; y++)
      for (x=0; x < width; x++) {
        if (MRIgetVoxVal(mri_in, x, y, z, 0) < noise_threshold) {
          MRIFvox(mri_snr,x,y,z) = 0;
          continue;
        }
        mean = 0;
        std = 0;
        count = 0;
        for (i=-1; i<=1; i++)
          for (j=-1; j<=1; j++)
            for (k=-1;k<=1;k++) {
              cx = x+i;
              cy = y+j, cz = z+k;

              if (cx < 0 ||
                  cx >= width ||
                  cy < 0 ||
                  cy >= height ||
                  cz < 0 ||
                  cz >= depth) continue;
              count++;
              value = MRIgetVoxVal(mri_in, cx, cy, cz, 0);
              mean += value;
              std += value*value;
            }

        mean /= (count + 1e-30);
        std /=  (count + 1e-30);

        std = std - mean *mean;

        if (std <= 0)
          std = 0;
        value = mean/sqrt(std);

        MRIFvox(mri_snr,x,y,z) = value;
        //bin_no = nint((float)value/(float)bin_size);
        //if (bin_no >= nbins) bin_no = nbins - 1;
        //h->counts[bin_no]++;
      }

#if 0
  for (num = 0.0f, b = h->nbins - 1; b >= 1; b --) {
    num += h->counts[b];
    if (num > 20000) /* this may make me only use WM points, is it good to
                        use only WM to compute scale of intensity?? */
      break;
  }

  printf("using SNR threshold %2.3f at bin %d\n", h->bins[b], b);

  mean2 = 0;
  std2 = 0;
  count2 = 0;
  for (z=0; z < depth; z++)
    for (y=0; y< height; y++)
      for (x=0; x < width; x++) {
        if (MRIgetVoxVal(mri_in, x, y, z, 0) < noise_threshold) {
          continue;
        }

        value = MRIFvox(mri_snr,x,y,z);

        if (value >= h->bins[b]) {
          count2++;
          mean2 += value;
          std2 += value*value;
        }
      }
#else
  printf("compute mean and std of tp2 volume within masked area\n");
  /* somehow mri_watershed seems to leave some unzero voxels around
  image border, so I will skip image boundaries
  no, that's not a problem of most recent mri_watershed;
  something wrong previously */
  mean2 = 0;
  std2 = 0;
  count2 = 0;
  for (z=0; z < depth; z++)
    for (y=0; y< height; y++)
      for (x=0; x < width; x++) {
        if (MRIgetVoxVal(mri_mask2, x, y, z, 0) <= 1e-30) {
          continue;
        }

        value = MRIgetVoxVal(mri_in, x, y, z, 0);

        count2++;
        mean2 += value;
        std2 += value*value;
      }
#endif

  mean2 /= (count2 + 1e-30);
  std2 /= (count2 + 1e-30);
  std2 = std2 - mean2*mean2;
  if (std2 <= 0)
    printf("warning: negative std for input volume. \n");
  else
    printf("mean and variance for input tp2 volume are %g and %g\n",
           mean2, std2);

  //compute intensity scale
  slope = sqrt(std1/std2);
  offset = mean1 - slope*mean2;

  printf("scale input volume by %g x + %g\n", slope, offset);
  // first change mri_in to FLOAT type
  mri_tmp = MRIchangeType(mri_in, MRI_FLOAT, 0, 1.0, 1);
  MRIfree(&mri_in);
  mri_in = mri_tmp;
  for (z=0; z < depth; z++)
    for (y=0; y< height; y++)
      for (x=0; x < width; x++) {
        value = MRIFvox(mri_in, x, y, z);
        MRIFvox(mri_in, x, y, z) = value*slope + offset;
      }


  //  printf("compute SNR map of tp2 volume\n"); //already done above
  //  mri_snr = MRIalloc(mri_ctrl->width,
  //     mri_ctrl->height, mri_ctrl->depth, MRI_FLOAT) ;

  for (z=0; z < depth; z++)
    for (y=0; y< height; y++)
      for (x=0; x < width; x++) {
        if (MRIgetVoxVal(mri_in, x, y, z, 0) < noise_threshold) {
          //    MRIFvox(mri_snr,x,y,z) = 0;
          continue;
        }

        value = MRIFvox(mri_snr,x,y,z);

        if (value < 20) MRIvox(mri_ctrl, x, y, z) = 0;
        else if (MRIvox(mri_ctrl, x, y, z) > 0) {
          MRIvox(mri_ctrl, x, y, z) = 1;
        }
      }
  if (debug_flag) {
    MRIwrite(mri_snr, "snr.mgz");
    //    MRIwrite(mri_ctrl, "ctrl.mgz");
  }

  // SNR >= 20 seems a good threshold

  // Now use ctrl points to normalize tp2
  printf("normalize tp2...\n");
  mri_bias = MRIbuildBiasImage(mri_in, mri_ctrl, NULL, bias_sigma) ;

  for (z = 0 ; z < depth ; z++) {
    for (y = 0 ; y < height ; y++) {
      for (x = 0 ; x < width ; x++) {
        src = MRIgetVoxVal(mri_in, x, y, z, 0) ;
        bias = MRIgetVoxVal(mri_bias, x, y, z, 0) ;
        if (!bias)   /* should never happen */
          norm = (float)src ;
        else
          norm = (float)src * 110.0 / (float)bias ;
        if (norm > 255.0f && mri_out->type == MRI_UCHAR)
          norm = 255.0f ;
        else if (norm < 0.0f && mri_out->type == MRI_UCHAR)
          norm = 0.0f ;
        MRIsetVoxVal(mri_out, x, y, z, 0, norm) ;
      }
    }
  }

  printf("writing normalized volume to %s...\n", argv[2]) ;
  MRIwrite(mri_out, argv[2]);

  MRIfree(&mri_in);
  MRIfree(&mri_bias);
  MRIfree(&mri_out);
  MRIfree(&mri_T1);
  MRIfree(&mri_ctrl);
  MRIfree(&mri_snr);
  //HISTOfree(&h);

  exit(0);

}  /*  end main()  */
コード例 #29
0
int
main(int argc, char *argv[]) {
  char        **av, *in_vol, *out_vol;
  int         ac, nargs;

  MRI         *mri_in, *mri_out, *mri_tmp ;
  LTA         *lta = 0;
  MATRIX *i_to_r_src = 0; /* src geometry of the input LTA */
  MATRIX *V_to_V = 0; /* Final voxel-to-voxel transform */
  MATRIX *r_to_i_dst = 0; /* dst geometry of the input LTA */
  MATRIX *m_tmp = 0;
  MATRIX *i_to_r_reg = 0; /* i_to_r of the volume after registration */
  MATRIX *r_to_i_out = 0; /* r_to_i of the final output volume */
  VOL_GEOM vgm_in;
  int x, y, z;
  double maxV, minV, value;
  int transform_type;
  //  MATRIX *i_to_r, *r_to_i;
  HISTOGRAM *h, *hsmooth ;
  float fmin, fmax, val, peak, smooth_peak;
  int i, nbins, bin;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mri_transform_to_COR.c,v 1.3 2011/03/02 00:04:25 nicks Exp $", "$Name: stable5 $");
  if (nargs && argc - nargs == 1)
    usage_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 < 3)
    usage_exit(0) ;

  in_vol = argv[1] ;
  out_vol = argv[2] ;

  printf("reading volume from %s...\n", in_vol) ;
  mri_in = MRIread(in_vol) ;
  if (!mri_in)
    ErrorExit(ERROR_NOFILE, "%s: could not read MRI volume %s", Progname,
              in_vol) ;

  /* Convert mri_in to float type */
  /* double would be more accurate */
  if (mri_in->type != MRI_FLOAT) {
    printf("Input volume type is %d\n", mri_in->type);
    printf("Change input volume to float type for convenience and accuracy");
    mri_tmp = MRIchangeType(mri_in, MRI_FLOAT, 0, 1.0, 1);
    MRIfree(&mri_in);
    mri_in = mri_tmp; //swap
  }

  /* Get input volume geometry, which is needed to compute i_to_r
   * and r_to_i of input volume. Note that i_to_r and r_to_i assumed
   * a certain prespecified c_r, c_a, c_s
   */
  getVolGeom(mri_in, &vgm_in);

  maxV = -10000.0;
  minV = 10000.0;
  for (z=0; z < mri_in->depth; z++)
    for (y=0; y< mri_in->height; y++)
      for (x=0; x < mri_in->width; x++) {
        if (MRIFvox(mri_in, x, y, z) > maxV )
          maxV = MRIFvox(mri_in, x, y,z) ;
        if (MRIFvox(mri_in, x, y, z) < minV )
          minV = MRIFvox(mri_in, x, y,z) ;
      }

  printf("Input volume has max = %g, min =%g\n", maxV, minV);

  printf("Scale input volume by %g \n", scale);

  maxV = -10000.0;
  minV = 10000.0;
  for (z=0; z < mri_in->depth; z++)
    for (y=0; y< mri_in->height; y++)
      for (x=0; x < mri_in->width; x++) {
        MRIFvox(mri_in, x, y, z) *= scale;
        if (MRIFvox(mri_in, x, y, z) > maxV )
          maxV = MRIFvox(mri_in, x, y,z) ;
        if (MRIFvox(mri_in, x, y, z) < minV )
          minV = MRIFvox(mri_in, x, y,z) ;
      }

  printf("Input volume after scaling has max = %g, min =%g\n", maxV, minV);

  /* Try to compute the Voxel_to_Voxel transform from the input volume
   * and the registration target/reference volume!
   * If no registration is involved, vox_to_vox is simply identity
   */
  /* Things become more complicated when allowing inverse transform */
  if (transform_flag) {


    printf("INFO: Applying transformation from file %s...\n",
           transform_fname);
    transform_type =  TransformFileNameType(transform_fname);

    /* Read in LTA transform file name */
    if (transform_type == MNI_TRANSFORM_TYPE ||
        transform_type == TRANSFORM_ARRAY_TYPE ||
        transform_type == REGISTER_DAT ||
        transform_type == FSLREG_TYPE
       ) {

      printf("Reading transform ...\n");
      lta = LTAreadEx(transform_fname) ;

      if (!lta)
        ErrorExit(ERROR_NOFILE, "%s: could not read transform file %s",
                  Progname, transform_fname) ;

      if (transform_type == FSLREG_TYPE) {
        if (lta_src == 0 || lta_dst == 0) {
          fprintf(stderr, "ERROR: fslmat does not have information on the src and dst volumes\n");
          fprintf(stderr, "ERROR: you must give options '-src' and '-dst' to specify the src and dst volume infos for the registration\n");
        }


        LTAmodifySrcDstGeom(lta, lta_src, lta_dst); // add src and dst information
        //The following is necessary to interpret FSLMAT correctly!!!
        LTAchangeType(lta, LINEAR_VOX_TO_VOX);
      }
      if (lta->xforms[0].src.valid == 0) {
        if (lta_src == 0) {
          fprintf(stderr, "The transform does not have the valid src volume info.\n");
          fprintf(stderr, "Either you give src volume info by option -src or\n");
          fprintf(stderr, "make the transform to have the valid src info.\n");
          ErrorExit(ERROR_BAD_PARM, "Bailing out...\n");
        } else {
          LTAmodifySrcDstGeom(lta, lta_src, NULL); // add src information
        }
      }
      if (lta->xforms[0].dst.valid == 0) {
        if (lta_dst == 0) {
          fprintf(stderr, "The transform does not have the valid dst volume info.\n");
          fprintf(stderr, "Either you give src volume info by option -dst or\n");
          fprintf(stderr, "make the transform to have the valid dst info.\n");
          fprintf(stderr, "If the dst was average_305, then you can set\n");
          fprintf(stderr, "environmental variable USE_AVERAGE305 true\n");
          fprintf(stderr, "instead.\n");
          ErrorExit(ERROR_BAD_PARM, "Bailing out...\n");
        } else {
          LTAmodifySrcDstGeom(lta, NULL, lta_dst); // add  dst information
        }
      }


      // The following procedure aims to apply an LTA computed from COR format to a volume in non-COR format, or vice versa, as long as they share the same RAS
      // first change to LINEAR RAS_TO_RAS using old info
      if (lta->type != LINEAR_RAS_TO_RAS) {
        LTAchangeType(lta, LINEAR_RAS_TO_RAS);
      }

      // now possiblly reset the src and dst
      if (lta_src != NULL) {
        //always trust the user
        LTAmodifySrcDstGeom(lta, lta_src, NULL);
      }
      if (lta_dst != NULL) {
        //always trust the user
        LTAmodifySrcDstGeom(lta, NULL, lta_dst);
      }

      if (lta->type == LINEAR_RAS_TO_RAS) {
        /* Convert it to VOX_TO_VOX */
        /* VOXELsrc_to_VOXELdst = R2Vdst*R2Rlta*V2Rsrc */
        /* Note whether the input should be identical to src or dst here depends
         * on whether the LTA here is the direct or inverse transform
         */
        i_to_r_src = vg_i_to_r(&lta->xforms[0].src);
        r_to_i_dst = vg_r_to_i(&lta->xforms[0].dst);

        if (!r_to_i_dst || !i_to_r_src)
          ErrorExit(ERROR_BADFILE, "%s: failed to extract volume geometries from input LTA file",Progname);
        m_tmp = MatrixMultiply(lta->xforms[0].m_L, i_to_r_src, NULL);
        V_to_V = MatrixMultiply(r_to_i_dst, m_tmp, NULL);
        MatrixFree(&m_tmp);

        MatrixFree(&i_to_r_src);
        MatrixFree(&r_to_i_dst);
      }
    } else {
      fprintf(stderr, "unknown transform type in file %s\n",
              transform_fname);
      exit(1);
    }

    if (invert_flag) {
      /* Geometry of input volume should match that of the dst of the LTA */
      if (MYvg_isEqual(&lta->xforms[0].dst, &vgm_in) == 0) {
        ErrorExit(ERROR_BADFILE, "%s: dst volume of lta doesn't match that of input volume",Progname);
      }

      i_to_r_reg = vg_i_to_r(&lta->xforms[0].src);

      if (!i_to_r_reg)
        ErrorExit(ERROR_BADFILE, "%s: failed to extract i_to_r of registered volume from LTA",Progname);

      m_tmp =  MatrixInverse(V_to_V, NULL);
      if (!m_tmp)
        ErrorExit(ERROR_BADPARM, "%s: transform is singular!", Progname);

      MatrixFree(&V_to_V);
      V_to_V = m_tmp;
    } else {
      /* Geometry of input volume should match that of the src of the LTA */
      if (MYvg_isEqual(&lta->xforms[0].src, &vgm_in) == 0) {
        ErrorExit(ERROR_BADFILE, "%s: src volume of lta doesn't match that of input volume",Progname);
      }

      i_to_r_reg = vg_i_to_r(&lta->xforms[0].dst);

      if (!i_to_r_reg)
        ErrorExit(ERROR_BADFILE, "%s: failed to extract i_to_r of registered volume from LTA",Progname);
    }

  } else {
    /* No registration transform need be applied */
    V_to_V = MatrixIdentity(4, NULL);
    i_to_r_reg = extract_i_to_r(mri_in);
    if (!i_to_r_reg)
      ErrorExit(ERROR_BADFILE, "%s: failed to extract i_to_r from input volume",Progname);
  }

  /* Now need to find the vox-to-vox transformation between registered volume
   * (or input volume itself if no registration involved) and the output
   * volume, either in COR format or as the out-like volume
   */
  /* Given a volume with a certain i_to_r, we need to compute the necessary
   * vox-to-voxel transform to change its i_to_r to like another volume.
   * The vox-to-vox is equal to R2V(r_to_i)_likevol*i_to_r_current_vol.
   */
  if (out_like_fname) {
    mri_tmp = MRIread(out_like_fname) ;
    if (!mri_tmp)
      ErrorExit(ERROR_NOFILE, "%s: could not read template volume from %s",out_like_fname) ;

    /* out_type = mri_tmp->type; */

    /* specify the out-type to float initially so as not to lose accuracy
     * during reslicing, will change type to correct type later.
     */
    mri_out = MRIalloc(mri_tmp->width, mri_tmp->height, mri_tmp->depth, MRI_FLOAT) ;

    MRIcopyHeader(mri_tmp, mri_out) ;
    MRIfree(&mri_tmp);
  } else  /* assume output is in COR format */
  {
    mri_out = MRIalloc(256, 256, 256, MRI_FLOAT) ;
    /* out_type = MRI_UCHAR; */

    /* Who says MRIlinearTransformInterp will change the header??
     * I don't think so!
     */
    //E/ set xyzc_ras to coronal ones.. - these'll get zorched
    //by MRIlinearTransformInterp() - copy again later - is there
    //any use in having them here now?  yes, so we can pass mri_out
    //to the ras2vox fns.


    mri_out->imnr0 = 1; /* what's this? */
    mri_out->imnr1 = 256; /* what's this? */
    mri_out->thick = 1.0;
    mri_out->ps = 1.0; /* what's this? */
    mri_out->xsize = mri_out->ysize = mri_out->zsize = 1.0;
    mri_out->xstart = mri_out->ystart = mri_out->zstart = -128.0;
    mri_out->xend = mri_out->yend = mri_out->zend = 128.0;
    mri_out->x_r =-1;
    mri_out->y_r = 0;
    mri_out->z_r = 0;
    mri_out->x_a = 0;
    mri_out->y_a = 0;
    mri_out->z_a = 1;
    mri_out->x_s = 0;
    mri_out->y_s =-1;
    mri_out->z_s = 0;

    /* In this case, the RAS itself is not fully determined, i.e., c_ras.
     * It's quite arbitrary, different values just change the final
     * sitting of the volume inside the RAS system.
     */
    /* NO! The C_RAS has to be set correctly, depending which target
     * volume the previous Vox_to_Vox transformation assumes!
     * When a registration is involved, the target volume is either
     * the src of LTA (direct) or the dst (inverse transform). When
     * just change format, the target volume is the input itself!!
     */
    if (transform_flag) {
      if (invert_flag) {
        mri_out->c_r = lta->xforms[0].src.c_r;
        mri_out->c_a = lta->xforms[0].src.c_a;
        mri_out->c_s = lta->xforms[0].src.c_s;

      } else {
        mri_out->c_r = lta->xforms[0].dst.c_r;
        mri_out->c_a = lta->xforms[0].dst.c_a;
        mri_out->c_s = lta->xforms[0].dst.c_s;
      }
    } else {
      mri_out->c_r = mri_in->c_r;
      mri_out->c_a = mri_in->c_a;
      mri_out->c_s = mri_in->c_s;
    }

    mri_out->ras_good_flag=1; /* What does this flag mean ? */

    /* since output is just transformed input */
    MRIcopyPulseParameters(mri_in, mri_out) ;

  }

  /* Compute the final input-to-output VOX_to_VOX transformation matrix */
  r_to_i_out = extract_r_to_i(mri_out);

  m_tmp = MatrixMultiply(r_to_i_out, i_to_r_reg, NULL);
  V_to_V = MatrixMultiply(m_tmp, V_to_V, V_to_V);
  MatrixFree(&m_tmp);

  printf("InterpMethod = %d\n", InterpMethod);

  /* Modify the MyMRIlinearTr... if I want to implement my cubic-B-spline
   * interpolation method. Otherwise, unnecessary
   */
  /* mri_out = MyMRIlinearTransformInterp(mri_in, mri_out, V_to_V, InterpMethod); */
  if (InterpMethod == SAMPLE_BSPLINE)
    mri_out = MRIlinearTransformInterpBSpline(mri_in, mri_out, V_to_V,
              SplineDegree);
  else
    mri_out = MRIlinearTransformInterp(mri_in, mri_out, V_to_V, InterpMethod);

  maxV = -10000.0;
  minV = 10000.0;
  for (z=0; z < mri_out->depth; z++)
    for (y=0; y< mri_out->height; y++)
      for (x=0; x < mri_out->width; x++) {
        if (MRIFvox(mri_out, x, y, z) > maxV )
          maxV = MRIFvox(mri_out, x, y,z) ;
        if (MRIFvox(mri_out, x, y, z) < minV )
          minV = MRIFvox(mri_out, x, y,z) ;
      }

  if (autoscale) {
    noscale = 1;

    /* compute histogram of output volume */

    fmin = minV;
    fmax = maxV;
    if (fmin < 0) fmin = 0;
    nbins = 256 ;
    h = HISTOalloc(nbins) ;
    hsmooth = HISTOcopy(h, NULL) ;
    HISTOclear(h, h) ;
    h->bin_size = (fmax-fmin)/255.0 ;

    for (i = 0 ; i < nbins ; i++)
      h->bins[i] = (i+1)*h->bin_size ;

    for (z=0; z < mri_out->depth; z++)
      for (y=0; y< mri_out->height; y++)
        for (x=0; x < mri_out->width; x++) {
          val = MRIFvox(mri_out, x, y, z);
          if (val <= 0) continue;

          bin = nint((val - fmin)/h->bin_size);
          if (bin >= h->nbins)
            bin = h->nbins-1;
          else if (bin < 0)
            bin = 0;

          h->counts[bin] += 1.0;
        }
    HISTOfillHoles(h) ;
    HISTOsmooth(h, hsmooth, 5)  ;
    peak =
      hsmooth->bins[HISTOfindHighestPeakInRegion(h, 1, h->nbins)] ;
    //   smooth_peak =
    //  hsmooth->bins[HISTOfindHighestPeakInRegion(hsmooth, 1, hsmooth->nbins)] ;

    smooth_peak =
      hsmooth->bins[HISTOfindLastPeak(hsmooth, 5, 0.8)] ;

    /*
      bin = nint((smooth_peak - fmin)/hsmooth->bin_size) ;

      printf("Highest peak has count = %d\n", (int)hsmooth->counts[bin]);

      bin = nint((420 - fmin)/hsmooth->bin_size) ;

      printf("bin at 420 has count = %d\n", (int)hsmooth->counts[bin]);
    */

    scale =  110.0/smooth_peak;
    printf("peak of output volume is %g, smooth-peak is %g, multiply by %g to scale it to 110\n", peak, smooth_peak, scale);
    for (z=0; z < mri_out->depth; z++)
      for (y=0; y< mri_out->height; y++)
        for (x=0; x < mri_out->width; x++) {
          val = MRIFvox(mri_out, x, y, z);
          MRIFvox(mri_out, x, y, z) = val*scale;
        }

  }


  printf("Output volume (before type-conversion) has max = %g, min =%g\n", maxV, minV);

  /* Finally change type to desired */
  if (mri_out->type != out_type) {
    printf("Change output volume to type %d\n", out_type);
    /* I need to modify the MIRchangeType function to make sure
     * it does roundoff instead of simple truncation!
     */
    /* Note if the last flag is set to 1, then it won't do scaling
       and small float numbers will become zero after convert to
       BYTE
    */
    if (out_type == 0 && noscale == 1) {
      //convert data to UCHAR
      mri_tmp = MRIalloc(mri_out->width, mri_out->height, mri_out->depth, out_type) ;
      MRIcopyHeader(mri_out, mri_tmp);
      for (z=0; z < mri_out->depth; z++)
        for (y=0; y< mri_out->height; y++)
          for (x=0; x < mri_out->width; x++) {
            value = floor(MRIgetVoxVal(mri_out, x, y, z, 0) + 0.5);
            if (value < 0 ) value = 0;
            if (value > 255) value = 255;
            MRIvox(mri_tmp,x,y,z) = (unsigned char)value;
          }
    } else
      mri_tmp = MRIchangeType(mri_out, out_type, thred_low, thred_high, noscale);

    MRIfree(&mri_out);
    mri_out = mri_tmp; //swap
  }

  MRIwrite(mri_out, out_vol) ;

  MRIfree(&mri_in);
  MRIfree(&mri_out);

  if (lta_src)
    MRIfree(&lta_src);
  if (lta_dst)
    MRIfree(&lta_dst);

  MatrixFree(&V_to_V);

  if (!r_to_i_out)
    MatrixFree(&r_to_i_out);

  if (!i_to_r_reg)
    MatrixFree(&i_to_r_reg);

  return(0) ;  /* for ansi */
}
コード例 #30
0
int
main(int argc, char *argv[])
{
  char         **av, fname[STRLEN], *out_fname, *subject_name, *cp, *tp1_name, *tp2_name ;
  char         s1_name[STRLEN], s2_name[STRLEN], *sname ;
  int          ac, nargs, i, n, options, max_index ;
  int          msec, minutes, seconds, nsubjects, input ;
  struct timeb start ;
  MRI          *mri_seg, *mri_tmp, *mri_in ;
  TRANSFORM    *transform ;
//  int          counts ;
  int          t;
  RANDOM_FOREST *rf = NULL ;
  GCA           *gca = NULL ;

  Progname = argv[0] ;

  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  TimerStart(&start) ;

  parms.width = parms.height = parms.depth = DEFAULT_VOLUME_SIZE ;
  parms.ntrees = 10 ;
  parms.max_depth = 10 ;
  parms.wsize = 1 ;
  parms.training_size = 100 ;
  parms.training_fraction = .5 ;
  parms.feature_fraction = 1 ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option
          (argc, argv,
           "$Id: mri_rf_long_train.c,v 1.5 2012/06/15 12:22:28 fischl Exp $",
           "$Name:  $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  // parse command line args
  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)) /* hasn't been set on command line */
  {
    cp = getenv("SUBJECTS_DIR") ;
    if (!cp)
      ErrorExit(ERROR_BADPARM, "%s: SUBJECTS_DIR not defined in environment",
                Progname);
    strcpy(subjects_dir, cp) ;
  }
  if (argc < 3)
    usage_exit(1) ;


  // options parsed.   subjects, tp1 and tp2 and rf name remaining
  out_fname = argv[argc-1] ;
  nsubjects = (argc-2)/3 ;
  for (options = i = 0 ; i < nsubjects ; i++)
  {
    if (argv[i+1][0] == '-')
    {
      nsubjects-- ;
      options++ ;
    }
  }

  printf("training on %d subject and writing results to %s\n",
         nsubjects, out_fname) ;

  // rf_inputs can be T1, PD, ...per subject
  if (parms.nvols == 0)
    parms.nvols = ninputs ;
  /* gca reads same # of inputs as we read
     from command line - not the case if we are mapping to flash */
  n = 0 ;

  //////////////////////////////////////////////////////////////////
  // set up gca direction cosines, width, height, depth defaults

  gca = GCAread(gca_name) ;
  if (gca == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not read GCA from %s", Progname, gca_name) ;
  
  
  /////////////////////////////////////////////////////////////////////////
  // weird way options and subject name are mixed here
  
  /////////////////////////////////////////////////////////
  // first calculate mean
  ////////////////////////////////////////////////////////
  // going through the subject one at a time
  max_index = nsubjects+options ;
  nargs = 0 ;
  mri_in = NULL ; 
#ifdef HAVE_OPENMP
  subject_name = NULL ; sname = NULL ; t = 0 ;
//  counts = 0 ;   would be private
  input = 0 ;
  transform = NULL ;
  tp1_name = tp2_name = NULL ;
  mri_tmp = mri_seg = NULL ;
#pragma omp parallel for firstprivate(tp1_name, tp2_name, mri_in,mri_tmp, input, xform_name, transform, subjects_dir, force_inputs, conform, Progname, mri_seg, subject_name, s1_name, s2_name, sname, t, fname) shared(mri_inputs, transforms, mri_segs,argv) schedule(static,1)
#endif
  for (i = 0 ; i < max_index ; i++)
  {
    subject_name = argv[3*i+1] ;
    tp1_name = argv[3*i+2] ;
    tp2_name = argv[3*i+3] ;
    sprintf(s1_name, "%s_%s.long.%s_base", subject_name, tp1_name, subject_name) ;
    sprintf(s2_name, "%s_%s.long.%s_base", subject_name, tp2_name, subject_name) ;

    //////////////////////////////////////////////////////////////
    printf("***************************************"
	   "************************************\n");
    printf("processing subject %s, %d of %d (%s and %s)...\n", subject_name,i+1-nargs,
	   nsubjects, s1_name,s2_name);

    for (t = 0 ; t < 2 ; t++)
    {
      sname = t == 0 ? s1_name : s2_name;

      // reading this subject segmentation
      sprintf(fname, "%s/%s/mri/%s", subjects_dir, sname, seg_dir) ;
      if (Gdiag & DIAG_SHOW && DIAG_VERBOSE_ON)
	fprintf(stderr, "Reading segmentation from %s...\n", fname) ;
      mri_seg = MRIread(fname) ;
      if (!mri_seg)
	ErrorExit(ERROR_NOFILE, "%s: could not read segmentation file %s",
		  Progname, fname) ;

      if ((mri_seg->type != MRI_UCHAR) && (make_uchar != 0))
      {
	MRI *mri_tmp ;
	mri_tmp = MRIchangeType(mri_seg, MRI_UCHAR, 0, 1,1);
	MRIfree(&mri_seg) ;
	mri_seg = mri_tmp ;
      }

      if (wmsa_fname)
      {
	MRI *mri_wmsa ;
	sprintf(fname, "%s/%s/mri/%s", subjects_dir, sname, wmsa_fname) ;
	printf("reading WMSA labels from %s...\n", fname) ;
	mri_wmsa = MRIread(fname) ;
	if (mri_wmsa == NULL)
	  ErrorExit(ERROR_NOFILE, "%s: could not read WMSA file %s", fname) ;
	MRIbinarize(mri_wmsa, mri_wmsa,  1, 0, WM_hypointensities) ;
	MRIcopyLabel(mri_wmsa, mri_seg, WM_hypointensities) ;
	lateralize_hypointensities(mri_seg) ;
	if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON )
	{
	  char s[STRLEN] ;
	  sprintf(s, "%s/%s/mri/seg_%s",
		  subjects_dir, subject_name, wmsa_fname) ;
	  MRIwrite(mri_seg, s) ;
	}
      }
      if (binarize)
      {
	int j ;
	for (j = 0 ; j < 256 ; j++)
	{
	  if (j == binarize_in)
	    MRIreplaceValues(mri_seg, mri_seg, j, binarize_out) ;
	  else
	    MRIreplaceValues(mri_seg, mri_seg, j, 0) ;
	}
      }
      if (insert_fname)
      {
	MRI *mri_insert ;
	
	sprintf(fname, "%s/%s/mri/%s",
		subjects_dir, subject_name, insert_fname) ;
	mri_insert = MRIread(fname) ;
	if (mri_insert == NULL)
	  ErrorExit(ERROR_NOFILE,
		    "%s: could not read volume from %s for insertion",
		    Progname, insert_fname) ;
	
	MRIbinarize(mri_insert, mri_insert, 1, 0, insert_label) ;
	MRIcopyLabel(mri_insert, mri_seg, insert_label) ;
	MRIfree(&mri_insert) ;
      }
      
      replaceLabels(mri_seg) ;
      MRIeraseBorderPlanes(mri_seg, 1) ;

      ////////////////////////////////////////////////////////////
      if (DIAG_VERBOSE_ON)
	fprintf(stderr,
		"Gather all input volumes for the subject %s.\n",
		subject_name);
      // inputs must be coregistered
      // note that inputs are T1, PD, ... per subject (same TE, TR, FA)
      for (input = 0 ; input < ninputs ; input++)
      {
	//////////// set the gca type //////////////////////////////
	// is this T1/PD training?
	// how can we allow flash data training ???????
	// currently checks the TE, TR, FA to be the same for all inputs
	// thus we cannot allow flash data training.
	////////////////////////////////////////////////////////////
	
	sprintf(fname, "%s/%s/mri/%s", subjects_dir, sname,input_names[input]);
	if (DIAG_VERBOSE_ON)
	  printf("reading co-registered input from %s...\n", fname) ;
	fprintf(stderr, "   reading input %d: %s\n", input, fname);
	mri_tmp = MRIread(fname) ;
	if (!mri_tmp)
	  ErrorExit
	    (ERROR_NOFILE,
	     "%s: could not read image from file %s", Progname, fname) ;
	// input check 1
	if (getSliceDirection(mri_tmp) != MRI_CORONAL)
	{
	  ErrorExit
	    (ERROR_BADPARM,
	     "%s: must be in coronal direction, but it is not\n",
	     fname);
	}
	// input check 2
	if (conform &&
	    (mri_tmp->xsize != 1 || mri_tmp->ysize != 1 || mri_tmp->zsize != 1))
	{
	  ErrorExit
	    (ERROR_BADPARM,
	     "%s: must have 1mm voxel size, but have (%f, %f, %f)\n",
	     fname, mri_tmp->xsize, mri_tmp->ysize, mri_tmp->ysize);
	}
	// input check 3 is removed.  now we can handle c_(ras) != 0 case
	// input check 4
	if (i == 0)
	{
	  TRs[input] = mri_tmp->tr ;
	  FAs[input] = mri_tmp->flip_angle ;
	  TEs[input] = mri_tmp->te ;
	}
	else if ((force_inputs == 0) &&
		 (!FEQUAL(TRs[input],mri_tmp->tr) ||
		  !FEQUAL(FAs[input],mri_tmp->flip_angle) ||
		  !FEQUAL(TEs[input], mri_tmp->te)))
	  ErrorExit
	    (ERROR_BADPARM,
	     "%s: subject %s input volume %s: sequence parameters "
	     "(%2.1f, %2.1f, %2.1f)"
	     "don't match other inputs (%2.1f, %2.1f, %2.1f)",
	     Progname, subject_name, fname,
	     mri_tmp->tr, DEGREES(mri_tmp->flip_angle), mri_tmp->te,
	     TRs[input], DEGREES(FAs[input]), TEs[input]) ;
	// first time do the following
	if (input == 0)
	{
	  int nframes = ninputs ;
	  
	  ///////////////////////////////////////////////////////////
	  mri_in = MRIallocSequence(mri_tmp->width, mri_tmp->height, mri_tmp->depth,
				    mri_tmp->type, nframes) ;
	  if (!mri_in)
	    ErrorExit
	      (ERROR_NOMEMORY,
	       "%s: could not allocate input volume %dx%dx%dx%d",
	       mri_tmp->width, mri_tmp->height, mri_tmp->depth,nframes) ;
	  MRIcopyHeader(mri_tmp, mri_in) ;
	}
	// -mask option ////////////////////////////////////////////
	if (mask_fname)
	{
	  MRI *mri_mask ;
	  
	  sprintf(fname, "%s/%s/mri/%s",
		  subjects_dir, subject_name, mask_fname);
	  printf("reading volume %s for masking...\n", fname) ;
	  mri_mask = MRIread(fname) ;
	  if (!mri_mask)
	  ErrorExit(ERROR_NOFILE, "%s: could not open mask volume %s.\n",
		    Progname, fname) ;
	
	  MRImask(mri_tmp, mri_mask, mri_tmp, 0, 0) ;
	  MRIfree(&mri_mask) ;
	}
	MRIcopyFrame(mri_tmp, mri_in, 0, input) ;
	MRIfree(&mri_tmp) ;

      }// end of inputs per subject
    
    
      /////////////////////////////////////////////////////////
      // xform_name is given, then we can use the consistent c_(r,a,s) for gca
      /////////////////////////////////////////////////////////
      if (xform_name)
      {
	// we read talairach.xfm which is a RAS-to-RAS
	sprintf(fname, "%s/%s/mri/transforms/%s", subjects_dir, sname, xform_name) ;
	if (Gdiag & DIAG_SHOW && DIAG_VERBOSE_ON)
	  printf("INFO: reading transform file %s...\n", fname);
	if (!FileExists(fname))
	{
	  fprintf(stderr,"ERROR: cannot find transform file %s\n",fname);
	  exit(1);
	}
	transform = TransformRead(fname);
	if (!transform)
	  ErrorExit(ERROR_NOFILE, "%s: could not read transform from file %s",
		    Progname, fname);
	
//        modify_transform(transform, mri_in, gca);
	// Here we do 2 things
	// 1. modify gca direction cosines to
	// that of the transform destination (both linear and non-linear)
	// 2. if ras-to-ras transform,
      // then change it to vox-to-vox transform (linear case)
	
      // modify transform to store inverse also
	TransformInvert(transform, mri_in) ;
      }
      else
      {
//        GCAreinit(mri_in, gca);
	// just use the input value, since dst = src volume
	transform = TransformAlloc(LINEAR_VOXEL_TO_VOXEL, NULL) ;
      }
      
      /////////////////////////////////////////////////////////
      if (do_sanity_check)
      {
	// conduct a sanity check of particular labels, most importantly
	// hippocampus, that such labels do not exist in talairach coords
	// where they are known not to belong (indicating a bad manual edit)
	int errs = check(mri_seg, subjects_dir, subject_name);
	if (errs) 
	{
	  printf(
	    "ERROR: mri_ca_train: possible bad training data! subject:\n"
	    "\t%s/%s\n\n", subjects_dir, subject_name);
	  fflush(stdout) ;
	  sanity_check_badsubj_count++;
	}
      }
      
      mri_segs[i][t] = mri_seg ;
      mri_inputs[i][t] = mri_in ;
      transforms[i][t] = transform ;
    }
  }
  rf = train_rforest(mri_inputs, mri_segs, transforms, nsubjects, gca, &parms, wm_thresh,wmsa_whalf, 2) ;
  printf("writing random forest to %s\n", out_fname) ;
  if (RFwrite(rf, out_fname) != NO_ERROR)
    ErrorExit
      (ERROR_BADFILE, "%s: could not write rf to %s", Progname, out_fname) ;
  
  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  printf("classifier array training took %d minutes and %d seconds.\n", minutes, seconds) ;
  exit(0) ;
  return(0) ;
  }