int
main(int argc, char *argv[]) {
  char        **av, *out_vol ;
  int         ac, nargs ;
  MRI         *mri_time1, *mri_time2, *mri_tmp, *mri_atrophy ;
  TRANSFORM   *transform1, *transform2 ;

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

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

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

  if (argc < 6)
    usage_exit() ;

  out_vol = argv[argc-1] ;

  printf("reading volume from %s...\n", argv[1]) ;
  mri_time1 = MRIread(argv[1]) ;
  if (!mri_time1)
    ErrorExit(ERROR_NOFILE, "%s: could not read MRI volume %s", Progname, argv[2]) ;
  mri_time2 = MRIread(argv[2]) ;
  if (!mri_time2)
    ErrorExit(ERROR_NOFILE, "%s: could not read MRI volume %s", Progname, argv[2]) ;

  transform1 = TransformRead(argv[3]) ;
  if (!transform1)
    ErrorExit(ERROR_NOFILE, "%s: could not read transform from %s", Progname, argv[3]) ;

  transform2 = TransformRead(argv[4]) ;
  if (!transform2)
    ErrorExit(ERROR_NOFILE, "%s: could not read transform from %s", Progname, argv[4]) ;

  mri_tmp = TransformApplyType(transform1, mri_time1, NULL, SAMPLE_NEAREST);
  MRIfree(&mri_time1) ;
  mri_time1 = mri_tmp ;
  mri_tmp = TransformApplyType(transform2, mri_time2, NULL, SAMPLE_NEAREST);
  MRIfree(&mri_time2) ;
  mri_time2 = mri_tmp ;
  mri_atrophy = make_atrophy_map(mri_time1, mri_time2, NULL, transform1, transform2, gray_labels, ngray, csf_labels, ncsf) ;

  MRIwrite(mri_atrophy, out_vol) ;

  exit(0) ;
  return(0) ;  /* for ansi */
}
int
main(int argc, char *argv[]) {
  char   **av ;
  int    ac, nargs ;
  MRI    *mri_src, *mri_dst ;
  char   *in_fname, *out_fname ;
  int    label, nvox ;

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

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

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

  if (argc < 2)
    ErrorExit(ERROR_BADPARM, "%s: no input name specified", Progname) ;
  in_fname = argv[1] ;

  if (argc < 3)
    ErrorExit(ERROR_BADPARM, "%s: no value specified", Progname) ;
  label = atoi(argv[2]) ;

  if (argc < 4)
    ErrorExit(ERROR_BADPARM, "%s: no output name specified", Progname) ;
  out_fname = argv[3] ;

  fprintf(stderr, "reading from %s...\n", in_fname) ;
  mri_src = MRIread(in_fname) ;
  if (!mri_src)
    ErrorExit(ERROR_NOFILE, "%s: could not read input volume %s",
              Progname, in_fname) ;
  mri_dst = MRIread(out_fname) ;
  if (!mri_dst)
    ErrorExit(ERROR_NOFILE, "%s: could not read destination volume %s",
              Progname, out_fname) ;
  nvox = MRIcopyLabel(mri_src, mri_dst, label) ;
  fprintf(stderr, "%d voxels copied from input to output volume...\n", nvox);

  fprintf(stderr, "writing to %s...\n", out_fname) ;
  MRIwrite(mri_dst, out_fname) ;
  MRIfree(&mri_dst) ;
  MRIfree(&mri_src) ;
  exit(0) ;
  return(0) ;
}
int
main(int argc, char *argv[]) {
  char   **av ;
  int    ac, nargs ;
  MRI    *mri_src, *mri_ref, *mri_tmp ;
  double accuracy ;
  MRI_REGION box ;

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

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

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

  if (argc < 3)
    usage_exit(1) ;

  mri_src = MRIread(argv[1]) ;
  if (mri_src == NULL)
    ErrorExit(ERROR_BADPARM, "%s: could not read input volume %s\n", Progname,argv[1]);
  MRIboundingBox(mri_src, 0, &box) ;
  mri_tmp = MRIextractRegionAndPad(mri_src, NULL, &box, PAD) ;
  MRIfree(&mri_src) ; mri_src = mri_tmp ;
  if (mri_src->type == MRI_SHORT)
  {
    mri_tmp = MRIchangeType(mri_src, MRI_FLOAT, 0, 0, 0) ;
    MRIfree(&mri_src) ; mri_src = mri_tmp ;
  }

  mri_ref = MRIread(argv[2]) ;
  if (mri_ref == NULL)
    ErrorExit(ERROR_BADPARM, "%s: could not read reference volume %s\n", Progname,argv[1]);
  MRIboundingBox(mri_ref, 0, &box) ;
  mri_tmp = MRIextractRegionAndPad(mri_ref, NULL, &box, PAD) ;
  MRIfree(&mri_ref) ; mri_ref = mri_tmp ;

  accuracy = MRIcomputeLabelAccuracy(mri_src, mri_ref, MRI_MEAN_MIN_DISTANCE, stdout) ;

  if (Gdiag_fp)
    fclose(Gdiag_fp) ;
  exit(0) ;
  return(0) ;
}
Exemple #4
0
int
main(int argc, char *argv[]) {
  char   **av ;
  int    ac, nargs ;
  MRI    *mri_src, *mri_dst = NULL ;
  char   *in_fname, *out_fname ;

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

  if (argc < 1)
    ErrorExit(ERROR_BADPARM, "%s: no input name specified", Progname) ;
  in_fname = argv[1] ;

  if (argc < 2)
    ErrorExit(ERROR_BADPARM, "%s: no output name specified", Progname) ;
  out_fname = argv[2] ;

  if (verbose)
    fprintf(stderr, "reading from %s...", in_fname) ;
  mri_src = MRIread(in_fname) ;
  if (!mri_src)
    ErrorExit(ERROR_NO_FILE, "%s: could not open source file %s",
              Progname, in_fname) ;

  if (verbose)
    fprintf(stderr, "done.\ncalculating plane of least variance...") ;
  mri_dst = MRIcentralPlaneOfLeastVarianceNormal(mri_src, NULL, window_size) ;
  if (!mri_dst)
    ErrorExit(ERROR_BADPARM, "%s: plane of least variance calculation failed",
              Progname) ;

  if (verbose)
    fprintf(stderr, "\ndone. writing output to %s", out_fname) ;
  MRIwrite(mri_dst, out_fname) ;
  if (verbose)
    fprintf(stderr, "\n") ;
  exit(0) ;
  return(0) ;
}
Exemple #5
0
int
main(int argc, char *argv[]) {
  char   **av ;
  int    ac, nargs, i ;
  MRI    *mri_src, *mri_dst = NULL ;
  char   *in_fname, *out_fname ;

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

  if (argc < 1)
    ErrorExit(ERROR_BADPARM, "%s: no input name specified", Progname) ;
  in_fname = argv[1] ;

  if (argc < 2)
    ErrorExit(ERROR_BADPARM, "%s: no output name specified", Progname) ;
  out_fname = argv[2] ;

  fprintf(stderr, "reading from %s...", in_fname) ;
  mri_src = MRIread(in_fname) ;

  i = 0 ;
  do {
    if (i)
      mri_src = MRIcopy(mri_dst, NULL) ;
    fprintf(stderr, "\nreducing by 2");

    mri_dst = MRIallocSequence(mri_src->width/2, mri_src->height/2, mri_src->depth/2, MRI_FLOAT, mri_src->nframes);
    MRIreduce(mri_src, mri_dst) ;
    MRIfree(&mri_src) ;
  } while (++i < reductions) ;

  fprintf(stderr, "\nwriting to %s", out_fname) ;
  MRIwrite(mri_dst, out_fname) ;
  fprintf(stderr, "\n") ;
  exit(0) ;
  return(0) ;
}
Exemple #6
0
int
main(int argc, char *argv[]) {
  char         **av ;
  int          ac, nargs, nsize ;
  MRI_SURFACE  *mris ;
  MRI          *mri ;

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

  Gx = Gy = Gz = -1 ;
  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(1) ;

  mris = MRISread(argv[1]) ;
  if (mris == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not read surface from %s", Progname, argv[1]) ;
  MRIScomputeMetricProperties(mris) ;
  MRISstoreMetricProperties(mris) ;

  mri = MRIread(argv[2]) ;
  if (mri == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not read volume from %s", Progname, argv[2]) ;

  target_vnos[nvertices] = atoi(argv[3]) ;
  target_vals[nvertices] = atof(argv[4]) ;
  nsize = atoi(argv[5]) ;

  printf("nudging %d vertex region around vertex %d to target val %2.1f\n", 
         nsize, target_vnos[nvertices], target_vals[nvertices]) ;
  nvertices++ ;

  MRISerodeRipped(mris, nsize) ;
  MRISrepositionSurface(mris, mri, target_vnos, target_vals, nvertices, nsize, sigma) ;

  MRISunrip(mris) ;
  printf("writing repositioned surface to %s\n", argv[6]) ;
  MRISwrite(mris, argv[6]) ;
  return(0) ;
}
Exemple #7
0
int main(int argc, char *argv[]) {
  MRI *src;
  MRI *dst;
  int label=2;
  float max_distance=10.;
  int mode=1;

  if (argc < 1) {
    fprintf(stderr, "Usage: ctest <volume>\n");
    return -1;
  }
  src = MRIread(argv[1]);
  dst = MRIextractDistanceMap(src, NULL, label, max_distance, mode,NULL);
  return 0;
}
Exemple #8
0
/***-------------------------------------------------------****/
int main(int argc, char *argv[])
{
  int  nargs, index, ac, nvolumes;
  char **av ;
  MRI  *mri_and = NULL, *mri ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, vcid, "$Name:  $");
  if (nargs && argc - nargs == 1)
    exit (0);
  Progname = argv[0] ;
  argc -= nargs;
  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++)
  {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  nvolumes = argc-2 ;
  if (nvolumes <= 0)
    usage_exit() ;
  printf("processing %d input files\n", nvolumes) ;

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

  for (index = 0 ; index < nvolumes ; index++)
  {
    char *fname = argv[index+1] ;
    printf("processing input volume %d of %d: %s\n",
           index+1, nvolumes, fname) ;
    mri = MRIread(fname) ;
    if (index == 0)
      mri_and = MRIcopy(mri, NULL) ;
    else
      MRIand(mri, mri_and, mri_and, 0) ;

    MRIfree(&mri) ;
  }

  printf("writing output to %s\n", argv[argc-1]) ;
  MRIwrite(mri_and, argv[argc-1]) ;
  exit(0);

} /* end main() */
/*----------------------------------------------------------------------
            Parameters:

           Description:
----------------------------------------------------------------------*/
static int
get_option(int argc, char *argv[])
{
  int  nargs = 0 ;
  char *option ;

  option = argv[1] + 1 ;            /* past '-' */
  switch (toupper(*option))
  {
  case 'N':
    no_write = 1 ;
    printf("not saving final warp (specify -a to save warped volume)\n") ;
    break ;
  case 'A':
    mri_in = MRIread(argv[2]) ;
    if (mri_in == NULL)
      ErrorExit(ERROR_NOFILE, "%s: could not read volume %s", Progname, argv[2]) ;
    out_fname = argv[3] ;
    nargs = 2 ;
    break ;
    case 'V':
      Gdiag_no = atoi(argv[2]) ;
      nargs = 1 ;
      break ;
  case 'I':
    niter = atoi(argv[2]) ;
    printf("using %d soap bubble iterations\n", niter) ;
    nargs = 1 ;
    break ;
  case 'L':
    like_vol_name = argv[2] ;
    printf("using volume %s to specify geometry of volumetric warp field\n", like_vol_name) ;
    nargs = 1 ;
    break ;
  case '?':
  case 'U':
    usage_exit(0) ;
    break ;
  default:
    fprintf(stderr, "unknown option %s\n", argv[1]) ;
    exit(1) ;
    break ;
  }

  return(nargs) ;
}
int
main(int argc, char *argv[])
{
  double           thresh ;
  MRI              *mri, *mri_abs ;
  char             *out_stem, fname[STRLEN] ;
  MRI_SEGMENTATION *mriseg ;
  int              s ;
  LABEL            *area ;

  Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;
  mri = MRIread(argv[1]) ;
  if (mri == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not load MRI from %s\n", Progname, argv[1]) ;

  if (use_abs)
    mri_abs = MRIabs(mri, NULL) ;
  else
    mri_abs = MRIcopy(mri, NULL) ;

  thresh = atof(argv[2]) ;
  out_stem = argv[3] ;

  mriseg = MRIsegment(mri, thresh, 1e10) ;
  MRIremoveSmallSegments(mriseg, size_thresh) ;
  printf("segmenting volume at threshold %2.1f yields %d segments\n", thresh, mriseg->nsegments) ;

  for (s = 0 ; s < mriseg->nsegments ; s++)
  {
    area = MRIsegmentToLabel(mriseg, mri_abs, s) ;
    sprintf(fname, "%s.%3.3d.label", out_stem, s) ;
    LabelWrite(area, fname) ;
    
  }
  return(0) ;
}
Exemple #11
0
static int
get_option(int argc, char *argv[])
{
  int  nargs = 0 ;
  char *option ;

  option = argv[1] + 1 ;            /* past '-' */
  StrUpper(option) ;
  if (!stricmp(option, "debug_voxel"))
    {
      Gsx = Gx = atoi(argv[2]) ;
      Gsy = Gy = atoi(argv[3]) ;
      Gsz = Gz = atoi(argv[4]) ;
      nargs = 3 ;
      printf("debugging voxel (%d, %d, %d)\n", Gx, Gy, Gz) ;
    }
  else if (!stricmp(option, "debug_node"))
    {
      Gx = atoi(argv[2]) ;
      Gy = atoi(argv[3]) ;
      Gz = atoi(argv[4]) ;
      nargs = 3 ;
      printf("debugging node (%d, %d, %d)\n", Gx, Gy, Gz) ;
    }
  else if (!stricmp(option, "OPTIMAL"))
    {
      mp.integration_type = GCAM_INTEGRATE_OPTIMAL ;
      printf("using optimal time-step integration\n") ;
    }
  else if (!stricmp(option, "NONEG")) {
    mp.noneg = atoi(argv[2]) ;
    nargs = 1 ;
    printf("%s allowing temporary folds during numerical minimization\n",
           mp.noneg ? "not" : "") ;
  }
  else if (!stricmp(option, "renormalize"))  {
    renormalize = atoi(argv[2]) ;
    nargs = 1 ;
    printf("%srenormalizing intensities\n", renormalize ? "" : "not ");
    if (renormalize == 0)
      {
	match_mean_intensity = match_peak_intensity_ratio = 0 ;
      }
  }
  else if (!stricmp(option, "aseg"))  {
    match_mean_intensity = match_peak_intensity_ratio = 0 ;
    use_aseg = 1 ; 
    mp.l_dtrans = 1 ;
    mp.l_log_likelihood = 0 ;
    renormalize = 0 ;
    printf("treating inputs as segmentations\n") ;
    mp.dtrans_labels = dtrans_labels ;
    mp.ndtrans = NDTRANS_LABELS ;
  }
  else if (!stricmp(option, "diag2"))  {
    mp.mri_diag2 = MRIread(argv[2]) ;
    if (mp.mri_diag2 == NULL)
      ErrorExit(ERROR_NOFILE, "%s: could not read diag volume from %s", Progname, argv[2]) ;
    nargs = 1 ;
    printf("writing d2 diagnostics for input volume %s\n", argv[2]) ;
  }
  else if (!stricmp(option, "MOMENTUM") || !stricmp(option, "FIXED"))
    {
      mp.integration_type = GCAM_INTEGRATE_FIXED ;
      printf("using optimal time-step integration\n") ;
    }
  else if (!stricmp(option, "distance"))
    {
      distance = atof(argv[2]) ;
      nargs = 1 ;
      printf("expanding border by %2.1f mm every outer cycle\n", distance);
    }
  else if (!stricmp(option, "dtrans"))
    {
      mp.l_dtrans = atof(argv[2]) ;
      nargs = 1 ;
      printf("setting distance transform coefficient to %2.3f\n", mp.l_dtrans) ;
    }
  else if (!stricmp(option, "match_peak"))
    {
      match_peak_intensity_ratio = 1 ;
      match_mean_intensity = 0 ;
      printf("matching peak of intensity ratio histogram\n") ;
    }
  else if (!stricmp(option, "erode"))
    {
      erosions = atoi(argv[2]) ;
      nargs = 1 ;
      printf("eroding source and target image %d times before morphing\n",
	     erosions) ;
    }
  else if (!stricmp(option, "match_mean"))
    {
      match_peak_intensity_ratio = 0 ;
      match_mean_intensity = atoi(argv[2]) ;
      nargs = 1 ;
      printf("%smatching peak of intensity ratio histogram\n",
	     match_mean_intensity ? "" : "not ") ;
    }
  else if (!stricmp(option, "intensity") ||!stricmp(option, "ll"))
    {
      mp.l_log_likelihood = atof(argv[2]) ;
      nargs = 1 ;
      printf("setting l_log_likelihood = %2.3f\n", mp.l_log_likelihood );
    }
  else if (!stricmp(option, "noregrid"))
    {
      regrid = 0 ;
      mp.regrid = False ;
      printf("disabling regridding...\n") ;
    }
  else if (!stricmp(option, "regrid"))
    {
      regrid = 1 ;
      mp.regrid = True ;
      printf("enabling regridding...\n") ;
    }
  else if (!stricmp(option, "view"))
    {
      Gsx = atoi(argv[2]) ;
      Gsy = atoi(argv[3]) ;
      Gsz = atoi(argv[4]) ;
      nargs = 3 ;
      printf("viewing voxel (%d, %d, %d)\n", Gsx, Gsy, Gsz) ;
    }
  else if (!stricmp(option, "LEVELS"))
    {
      mp.levels = atoi(argv[2]) ;
      nargs = 1 ;
      printf("levels = %d\n", mp.levels) ;
    }
  else if (!stricmp(option, "area_smoothness") || !stricmp(option, "asmooth"))
    {
      mp.l_area_smoothness = atof(argv[2]) ;
      nargs = 1 ;
      printf("using l_area_smoothness=%2.3f\n", mp.l_area_smoothness) ;
    }
  else if (!stricmp(option, "area"))
    {
      mp.l_area = atof(argv[2]) ;
      nargs = 1 ;
      printf("using l_area=%2.3f\n", mp.l_area) ;
    }
  else if (!stricmp(option, "area_intensity"))
    {
      mp.l_area_intensity = atof(argv[2]) ;
      nargs = 1 ;
      printf("using l_area_intensity=%2.3f\n", mp.l_area_intensity) ;
    }
  else if (!stricmp(option, "tol"))
    {
      mp.tol = atof(argv[2]) ;
      nargs = 1 ;
      printf("using tol=%2.3f\n", mp.tol) ;
    }
  else if (!stricmp(option, "sigma"))
    {
      mp.sigma = atof(argv[2]) ;
      nargs = 1 ;
      printf("using sigma=%2.3f\n", mp.sigma) ;
    }
  else if (!stricmp(option, "min_sigma"))
    {
      mp.min_sigma = atof(argv[2]) ;
      nargs = 1 ;
      printf("using min sigma=%2.3f\n", mp.min_sigma) ;
    }
  else if (!stricmp(option, "ribbon"))
    {
      ribbon_name = argv[2] ;
      printf("reading ribbon from %s and inserting into aseg\n", ribbon_name) ;
      nargs = 1 ;
    }
  else if (!stricmp(option, "rthresh"))
    {
      mp.ratio_thresh = atof(argv[2]) ;
      mp.uncompress = 1 ;
      nargs = 1 ;
      printf("using compression ratio threshold = %2.3f...\n", mp.ratio_thresh) ;
    }
  else if (!stricmp(option, "scale"))
    {
      scale_values = atof(argv[2]) ;
      nargs = 1 ;
      printf("scaling input values by %2.3f\n", scale_values) ;
    }
  else if (!stricmp(option, "dt"))
    {
      mp.dt = atof(argv[2]) ;
      nargs = 1 ;
      printf("using dt = %2.3f\n", mp.dt) ;
    }
  else if (!stricmp(option, "passes"))
    {
      mp.npasses = atoi(argv[2]) ;
      nargs = 1 ;
      printf("integrating in %d passes (default=3)\n", mp.npasses) ;
    }
  else if (!stricmp(option, "skip"))
    {
      skip = atoi(argv[2]);
      printf("skipping %d voxels in source data...\n", skip) ;
      nargs = 1 ;
    }
  else if (!stricmp(option, "apply"))
    {
      apply_transform = atoi(argv[2]) ;
      nargs = 1 ;
      printf("%sapplying transform after registration\n", apply_transform ? "" : "not ") ;
    }
  else switch (*option)
    {
    case 'D':
      mp.l_distance = atof(argv[2]) ;
      nargs = 1 ;
      printf("using l_distance = %2.3f\n", mp.l_distance) ;
      break ;
    case 'M':
      mp.momentum = atof(argv[2]) ;
      nargs = 1 ;
      printf("momentum = %2.2f\n", mp.momentum) ;
      break ;
    case 'N':
      mp.niterations = atoi(argv[2]) ;
      nargs = 1 ;
      printf("using niterations = %d\n", mp.niterations) ;
      break ;
    case 'S':
      mp.l_smoothness = atof(argv[2]) ;
      nargs = 1 ;
      printf("using l_smoothness = %2.3f\n", mp.l_smoothness) ;
      break ;
    case 'T':
      printf("reading transform from %s...\n", argv[2]) ;
      transform = TransformRead(argv[2]) ;
      if (transform == NULL)
	ErrorExit(ERROR_NOFILE,"%s: could not read transform from %s\n",Progname,argv[2]);
      nargs = 1 ;
      if (transform->type == LINEAR_VOX_TO_VOX)
	{
	  printf("converting transform to ras....\n") ;
	  LTAvoxelToRasXform((LTA *)(transform->xform), NULL, NULL) ;
	}
      break ;
    case 'I':
      printf("reading transform from %s...\n", argv[2]) ;
      transform = TransformRead(argv[2]) ;
      if (transform == NULL)
	ErrorExit(ERROR_NOFILE,"%s: could not read transform from %s\n",Progname,argv[2]);
      TransformInvert(transform, NULL) ;
      TransformSwapInverse(transform) ;
      if (transform->type == LINEAR_VOX_TO_VOX)
	{
	  printf("converting transform to ras....\n") ;
	  LTAvoxelToRasXform((LTA *)(transform->xform), NULL, NULL) ;
	}
      nargs = 1 ;
      break ;
    case 'B':
      mp.l_binary = atof(argv[2]) ;
      nargs = 1 ;
      printf("using l_binary=%2.3f\n", mp.l_binary) ;
      break ;
    case 'J':
      mp.l_jacobian = atof(argv[2]) ;
      nargs = 1 ;
      printf("using l_jacobian=%2.3f\n", mp.l_jacobian) ;
      break ;
    case 'Z':
      nozero = (atoi(argv[2]) == 0) ;
      printf("%sdisabling zero image locations\n", nozero ? "" : "not ") ;
      nargs = 1 ;
      break ;
    case 'A':
      mp.navgs = atoi(argv[2]) ;
      nargs = 1 ;
      printf("smoothing gradient with %d averages...\n", mp.navgs) ;
      break ;
    case 'K':
      mp.exp_k = atof(argv[2]) ;
      printf("setting exp_k to %2.2f (default=%2.2f)\n",
	     mp.exp_k, EXP_K) ;
      nargs = 1 ;
      break ;
    case 'W':
      mp.write_iterations = atoi(argv[2]) ;
      Gdiag |= DIAG_WRITE ;
      nargs = 1 ;
      printf("setting write iterations = %d\n", mp.write_iterations) ;
      break ;
    case '?':
    case 'U':
      usage_exit(1);
      break ;
    default:
      printf("unknown option %s\n", argv[1]) ;
      usage_exit(1) ;
      break ;
    }
  return(nargs) ;
}
Exemple #12
0
int
main(int argc, char *argv[])
{
  char         **av, *source_fname, *target_fname, *out_fname, fname[STRLEN] ;
  int          ac, nargs, new_transform = 0, pad ;
  MRI          *mri_target, *mri_source, *mri_orig_source ;
  MRI_REGION   box ;
  struct timeb start ;
  int          msec, minutes, seconds ;
  GCA_MORPH    *gcam ;
  MATRIX       *m_L/*, *m_I*/ ;
  LTA          *lta ;


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

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

  if (argc < 4)
    usage_exit(1) ;

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

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

  mp.max_grad = 0.3*mri_source->xsize ;

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

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

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

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

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

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

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

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

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

  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  printf("registration took %d minutes and %d seconds.\n", 
	 minutes, seconds) ;
  exit(0) ;
  return(0) ;
}
Exemple #13
0
int main(int argc, char *argv[])
{

  char **av;
  MRI *mri_before, *mri_after, *mri_in, *mri_out;
  int ac, nargs;
  int  width, height, depth, x, y, z, f,nframes ;
  double v_before, v_after, v_in, v_out;
  double gain;

  Progname = argv[0];

  nargs = handle_version_option (argc, argv, "$Id: mri_apply_INU.c,v 1.3 2011/03/02 00:04:55 nicks Exp $", "$Name:  $");
  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 (fname_before == NULL  || fname_after == NULL)
  {
    printf("Use options to specify template volumes for gain field computation\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_before = MRIread(fname_before) ;
  if (!mri_before)
    ErrorExit(ERROR_BADPARM, "%s: could not read tempate volume %s",
              Progname, fname_before) ;

  mri_after = MRIread(fname_after) ;
  if (!mri_after)
    ErrorExit(ERROR_BADPARM, "%s: could not read tempate volume %s",
              Progname, fname_after) ;

  if ((mri_in->width != mri_after->width) ||
      (mri_in->height != mri_after->height) ||
      (mri_in->depth != mri_after->depth) ||
      (mri_in->width != mri_before->width) ||
      (mri_in->height != mri_before->height) ||
      (mri_in->depth != mri_before->depth)

     )
    ErrorExit(ERROR_BADPARM, "%s: three input volumes have different sizes \n", Progname);

  mri_out = MRIclone(mri_in, NULL) ;

  width = mri_in->width ;
  height = mri_in->height ;
  depth = mri_in->depth ;
  nframes = mri_in->nframes ;
  if (nframes == 0) nframes = 1;

  for (f = 0 ; f < nframes ; f++)
  {
    for (z = 0 ; z < depth ; z++)
    {
      for (y = 0 ; y < height ; y++)
      {
        for (x = 0 ; x < width ; x++)
        {
          v_in = (double) MRIgetVoxVal(mri_in,x,y,z,f);
          v_before = (double) MRIgetVoxVal(mri_before,x,y,z,f);
          v_after = (double) MRIgetVoxVal(mri_after,x,y,z,f);
          gain = v_after/(v_before + 1e-15);
          v_out = gain*v_in;

          MRIsetVoxVal(mri_out,x,y,z,f,(float)v_out);
        }
      }
    }
  }

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

  MRIfree(&mri_in);
  MRIfree(&mri_out);
  MRIfree(&mri_before);
  MRIfree(&mri_after);

  exit(0);

}  /*  end main()  */
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;
  //  MATRIX *i_to_r, *r_to_i;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mri_transform_to_COR.c,v 1.8 2011/03/02 00:04:55 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)
  {
    int transform_type;

    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 */
    HISTOGRAM *h, *hsmooth ;
    float fmin, fmax, val, peak, smooth_peak;
    int i, nbins, bin;

    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 */
}
int main(int argc, char *argv[]) {
  char *inner_mris_fname_lh,*outer_mris_fname_lh,
    *inner_mris_fname_rh,*outer_mris_fname_rh,
    *input_mri_pref,*output_mri_pref,*mask_mri_pref;
  MRI *mri,*mri_src,*mri_mask;
  MRI_SURFACE *inner_mris_lh,*outer_mris_lh,*inner_mris_rh,*outer_mris_rh;
  int nargs;

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

  /* Set command-line parameters */
  if (argc < 7) {
    usage();
    exit(-1);
  }
  Progname=argv[0];

  inner_mris_fname_lh=argv[1]; // lh.white
  outer_mris_fname_lh=argv[2]; // lh.pial
  inner_mris_fname_rh=argv[3]; // rh.white
  outer_mris_fname_rh=argv[4]; // rh.pial
  input_mri_pref=argv[5];      // volume
  output_mri_pref=argv[6];     // output
  if (argc==8)
    mask_mri_pref=argv[7];     // cma mask
  else
    mask_mri_pref=NULL;

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

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

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

  /* Read surface information from right outer surface file */
  printf("Reading right outer surface file %s.\n",outer_mris_fname_rh);
  outer_mris_rh=MRISread(outer_mris_fname_rh);
  if (!outer_mris_rh) {
    fprintf(stderr,"Could not read surface file %s.\n",outer_mris_fname_rh);
    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) {
    fprintf(stderr,"Could not read MRI volume directory %s.\n",input_mri_pref);
    exit(1);
  }

  /* Read example volume from file */
  if (argc==8) {
    printf("Reading MRI volume directory %s.\n",mask_mri_pref);
    mri_mask=MRIread(mask_mri_pref);
    if (!mri_mask) {
      fprintf(stderr,"Could not read MRI volume directory %s.\n",
              mask_mri_pref);
      exit(1);
    }
  } else
    mri_mask=NULL;

  /* Extract ribbon */
  printf("Extracting ribbon.\n");
  mri=MRISpartialribbon(inner_mris_lh,
                        outer_mris_lh,
                        inner_mris_rh,
                        outer_mris_rh,
                        mri_src,
                        NULL,
                        mri_mask);

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

  MRIfree(&mri);
  MRIfree(&mri_src);
  if (mri_mask)
    MRIfree(&mri_mask);
  MRISfree(&inner_mris_lh);
  MRISfree(&outer_mris_lh);
  MRISfree(&inner_mris_rh);
  MRISfree(&outer_mris_rh);

  return 0;
}
int
main(int argc, char *argv[]) {
  char   **av ;
  int    label, ac, nargs ;
  int          msec, minutes, seconds/*, wrong, total, correct*/ ;
  struct timeb start ;
  MRI    *mri_T1, *mri_labeled ;
  FILE   *log_fp ;
  HISTOGRAM *histo ;

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

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

  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_T1 = MRIread(argv[1]) ;
  if (!mri_T1)
    ErrorExit(ERROR_NOFILE, "%s: could not read volume from %s",Progname,
              argv[1]) ;
  mri_labeled = MRIread(argv[2]) ;
  if (!mri_labeled)
    ErrorExit(ERROR_NOFILE, "%s: could not read volume from %s",Progname,
              argv[2]) ;

  if (log_fname) {
    log_fp = fopen(log_fname, "a+") ;
    if (!log_fp)
      ErrorExit(ERROR_BADFILE, "%s: could not open %s for writing",
                Progname, log_fname) ;
  } else
    log_fp = NULL ;


  label = atoi(argv[3]) ;
  printf("generating histogram for label %d...\n", label) ;
  histo = MRIhistogramLabel(mri_T1, mri_labeled, label, 0) ;

  HISTOplot(histo, argv[4]) ;

  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;

  if (DIAG_VERBOSE_ON)
    fprintf(stderr, "overlap calculation took %d minutes and %d seconds.\n",
            minutes, seconds) ;

  exit(0) ;
  return(0) ;
}
/*--------------------------------------------------*/
int main(int argc, char **argv)
{
    int nargs, err, asegid, c, r, s, nctx, annot,vtxno,nripped;
    int annotid, IsCortex=0, IsWM=0, IsHypo=0, hemi=0, segval=0;
    int RibbonVal=0,nbrute=0;
    float dmin=0.0, lhRibbonVal=0, rhRibbonVal=0;

    /* 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();
    }

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

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

    /* ------ Load subject's lh white surface ------ */
    sprintf(tmpstr,"%s/%s/surf/lh.white",SUBJECTS_DIR,subject);
    printf("\nReading lh white surface \n %s\n",tmpstr);
    lhwhite = MRISread(tmpstr);
    if (lhwhite == NULL)
    {
        fprintf(stderr,"ERROR: could not read %s\n",tmpstr);
        exit(1);
    }
    /* ------ Load subject's lh pial surface ------ */
    sprintf(tmpstr,"%s/%s/surf/lh.pial",SUBJECTS_DIR,subject);
    printf("\nReading lh pial surface \n %s\n",tmpstr);
    lhpial = MRISread(tmpstr);
    if (lhpial == NULL)
    {
        fprintf(stderr,"ERROR: could not read %s\n",tmpstr);
        exit(1);
    }
    if (lhwhite->nvertices != lhpial->nvertices)
    {
        printf("ERROR: lh white and pial have a different number of "
               "vertices (%d,%d)\n",
               lhwhite->nvertices,lhpial->nvertices);
        exit(1);
    }

    /* ------ Load lh annotation ------ */
    sprintf(annotfile,"%s/%s/label/lh.%s.annot",SUBJECTS_DIR,subject,annotname);
    printf("\nLoading 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 white surface ------ */
    sprintf(tmpstr,"%s/%s/surf/rh.white",SUBJECTS_DIR,subject);
    printf("\nReading rh white surface \n %s\n",tmpstr);
    rhwhite = MRISread(tmpstr);
    if (rhwhite == NULL)
    {
        fprintf(stderr,"ERROR: could not read %s\n",tmpstr);
        exit(1);
    }
    /* ------ Load subject's rh pial surface ------ */
    sprintf(tmpstr,"%s/%s/surf/rh.pial",SUBJECTS_DIR,subject);
    printf("\nReading rh pial surface \n %s\n",tmpstr);
    rhpial = MRISread(tmpstr);
    if (rhpial == NULL)
    {
        fprintf(stderr,"ERROR: could not read %s\n",tmpstr);
        exit(1);
    }
    if (rhwhite->nvertices != rhpial->nvertices)
    {
        printf("ERROR: rh white and pial have a different "
               "number of vertices (%d,%d)\n",
               rhwhite->nvertices,rhpial->nvertices);
        exit(1);
    }

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

    if (lhwhite->ct)
    {
        printf("Have color table for lh white annotation\n");
    }
    if (rhwhite->ct)
    {
        printf("Have color table for rh white annotation\n");
    }
    //print_annotation_table(stdout);

    if (UseRibbon)
    {
        sprintf(tmpstr,"%s/%s/mri/lh.ribbon.mgz",SUBJECTS_DIR,subject);
        printf("Loading lh ribbon mask from %s\n",tmpstr);
        lhRibbon = MRIread(tmpstr);
        if (lhRibbon == NULL)
        {
            printf("ERROR: loading %s\n",tmpstr);
            exit(1);
        }
        sprintf(tmpstr,"%s/%s/mri/rh.ribbon.mgz",SUBJECTS_DIR,subject);
        printf("Loading rh ribbon mask from %s\n",tmpstr);
        rhRibbon = MRIread(tmpstr);
        if (rhRibbon == NULL)
        {
            printf("ERROR: loading  %s\n",tmpstr);
            exit(1);
        }
    }

    if (UseNewRibbon)
    {
        sprintf(tmpstr,"%s/%s/mri/ribbon.mgz",SUBJECTS_DIR,subject);
        printf("Loading ribbon segmentation from %s\n",tmpstr);
        RibbonSeg = MRIread(tmpstr);
        if (RibbonSeg == NULL)
        {
            printf("ERROR: loading %s\n",tmpstr);
            exit(1);
        }
    }

    if (LabelHypoAsWM)
    {
        sprintf(tmpstr,"%s/%s/mri/filled.mgz",SUBJECTS_DIR,subject);
        printf("Loading filled from %s\n",tmpstr);
        filled = MRIread(tmpstr);
        if (filled == NULL)
        {
            printf("ERROR: loading filled %s\n",tmpstr);
            exit(1);
        }
    }

    // ------------ Rip -----------------------
    if (RipUnknown)
    {
        printf("Ripping vertices labeled as unkown\n");
        nripped = 0;
        for (vtxno = 0; vtxno < lhwhite->nvertices; vtxno++)
        {
            annot = lhwhite->vertices[vtxno].annotation;
            CTABfindAnnotation(lhwhite->ct, annot, &annotid);
            // Sometimes the annotation will be "none" indicated by
            // annotid = -1. We interpret this as "unknown".
            if (annotid == 0 || annotid == -1)
            {
                lhwhite->vertices[vtxno].ripflag = 1;
                lhpial->vertices[vtxno].ripflag = 1;
                nripped++;
            }
        }
        printf("Ripped %d vertices from left hemi\n",nripped);
        nripped = 0;
        for (vtxno = 0; vtxno < rhwhite->nvertices; vtxno++)
        {
            annot = rhwhite->vertices[vtxno].annotation;
            CTABfindAnnotation(rhwhite->ct, annot, &annotid);
            if (annotid == 0 || annotid == -1)
            {
                rhwhite->vertices[vtxno].ripflag = 1;
                rhpial->vertices[vtxno].ripflag = 1;
                nripped++;
            }
        }
        printf("Ripped %d vertices from right hemi\n",nripped);
    }


    printf("\n");
    printf("Building hash of lh white\n");
    lhwhite_hash = MHTfillVertexTableRes(lhwhite, NULL,CURRENT_VERTICES,hashres);
    printf("\n");
    printf("Building hash of lh pial\n");
    lhpial_hash = MHTfillVertexTableRes(lhpial, NULL,CURRENT_VERTICES,hashres);
    printf("\n");
    printf("Building hash of rh white\n");
    rhwhite_hash = MHTfillVertexTableRes(rhwhite, NULL,CURRENT_VERTICES,hashres);
    printf("\n");
    printf("Building hash of rh pial\n");
    rhpial_hash = MHTfillVertexTableRes(rhpial, NULL,CURRENT_VERTICES,hashres);

    /* ------ 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("\nLoading 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,1);
    MRIfree(&ASeg);
    ASeg = mritmp;

    if (CtxSegFile)
    {
        printf("Loading Ctx Seg File %s\n",CtxSegFile);
        CtxSeg = MRIread(CtxSegFile);
        if (CtxSeg == NULL)
        {
            exit(1);
        }
    }

    AParc = MRIclone(ASeg,NULL);
    if (OutDistFile != NULL)
    {
        Dist = MRIclone(ASeg,NULL);
        mritmp = MRIchangeType(Dist,MRI_FLOAT,0,0,0);
        if (mritmp == NULL)
        {
            printf("ERROR: could change type\n");
            exit(1);
        }
        MRIfree(&Dist);
        Dist = mritmp;
    }

    Vox2RAS = MRIxfmCRS2XYZtkreg(ASeg);
    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;

    if (crsTest)
    {
        printf("Testing point %d %d %d\n",ctest,rtest,stest);
        err = FindClosestLRWPVertexNo(ctest,rtest,stest,
                                      &lhwvtx, &lhpvtx,
                                      &rhwvtx, &rhpvtx, Vox2RAS,
                                      lhwhite,  lhpial,
                                      rhwhite, rhpial,
                                      lhwhite_hash, lhpial_hash,
                                      rhwhite_hash, rhpial_hash);

        printf("Result: err = %d\n",err);
        exit(err);
    }

    printf("\nLabeling Slice\n");
    nctx = 0;
    annot = 0;
    annotid = 0;
    nbrute = 0;

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

                asegid = MRIgetVoxVal(ASeg,c,r,s,0);
                if (asegid == 3 || asegid == 42)
                {
                    IsCortex = 1;
                }
                else
                {
                    IsCortex = 0;
                }
                if (asegid >= 77 && asegid <= 82)
                {
                    IsHypo = 1;
                }
                else
                {
                    IsHypo = 0;
                }
                if (asegid == 2 || asegid == 41)
                {
                    IsWM = 1;
                }
                else
                {
                    IsWM = 0;
                }
                if (IsHypo && LabelHypoAsWM && MRIgetVoxVal(filled,c,r,s,0))
                {
                    IsWM = 1;
                }

                // integrate surface information
                //
                // Only Do This for GM,WM or Unknown labels in the ASEG !!!
                //
                // priority is given to the ribbon computed from the surface
                // namely
                //  ribbon=GM => GM
                //  aseg=GM AND ribbon=WM => WM
                //  ribbon=UNKNOWN => UNKNOWN
                if (UseNewRibbon && ( IsCortex || IsWM || asegid==0 ) )
                {
                    RibbonVal = MRIgetVoxVal(RibbonSeg,c,r,s,0);
                    MRIsetVoxVal(ASeg,c,r,s,0, RibbonVal);
                    if (RibbonVal==2 || RibbonVal==41)
                    {
                        IsWM = 1;
                        IsCortex = 0;
                    }
                    else if (RibbonVal==3 || RibbonVal==42)
                    {
                        IsWM = 0;
                        IsCortex = 1;
                    }
                    if (RibbonVal==0)
                    {
                        IsWM = 0;
                        IsCortex = 0;
                    }
                }

                // If it's not labeled as cortex or wm in the aseg, skip
                if (!IsCortex && !IsWM)
                {
                    continue;
                }

                // If it's wm but not labeling wm, skip
                if (IsWM && !LabelWM)
                {
                    continue;
                }

                // Check whether this point is in the ribbon
                if (UseRibbon)
                {
                    lhRibbonVal = MRIgetVoxVal(lhRibbon,c,r,s,0);
                    rhRibbonVal = MRIgetVoxVal(rhRibbon,c,r,s,0);
                    if (IsCortex)
                    {
                        // ASeg says it's in cortex
                        if (lhRibbonVal < 0.5 && rhRibbonVal < 0.5)
                        {
                            // but it is not part of the ribbon,
                            // so set it to unknown (0) and go to the next voxel.
                            MRIsetVoxVal(ASeg,c,r,s,0,0);
                            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, lh.pial, rh.white, rh.pial
                if (UseHash)
                {
                    lhwvtx = MHTfindClosestVertexNo(lhwhite_hash,lhwhite,&vtx,&dlhw);
                    lhpvtx = MHTfindClosestVertexNo(lhpial_hash, lhpial, &vtx,&dlhp);
                    rhwvtx = MHTfindClosestVertexNo(rhwhite_hash,rhwhite,&vtx,&drhw);
                    rhpvtx = MHTfindClosestVertexNo(rhpial_hash, rhpial, &vtx,&drhp);
                    if (lhwvtx < 0 && lhpvtx < 0 && rhwvtx < 0 && rhpvtx < 0)
                    {
                        /*
                        printf("  Could not map to any surface with hash table:\n");
                        printf("  crs = %d %d %d, ras = %6.4f %6.4f %6.4f \n",
                        c,r,s,vtx.x,vtx.y,vtx.z);
                        printf("  Using brute force search %d ... \n",nbrute);
                        fflush(stdout);
                        */
                        lhwvtx = MRISfindClosestVertex(lhwhite,vtx.x,vtx.y,vtx.z,&dlhw);
                        lhpvtx = MRISfindClosestVertex(lhpial,vtx.x,vtx.y,vtx.z,&dlhp);
                        rhwvtx = MRISfindClosestVertex(rhwhite,vtx.x,vtx.y,vtx.z,&drhw);
                        rhpvtx = MRISfindClosestVertex(rhpial,vtx.x,vtx.y,vtx.z,&drhp);
                        nbrute ++;
                        //exit(1);
                    }
                }
                else
                {
                    lhwvtx = MRISfindClosestVertex(lhwhite,vtx.x,vtx.y,vtx.z,&dlhw);
                    lhpvtx = MRISfindClosestVertex(lhpial,vtx.x,vtx.y,vtx.z,&dlhp);
                    rhwvtx = MRISfindClosestVertex(rhwhite,vtx.x,vtx.y,vtx.z,&drhw);
                    rhpvtx = MRISfindClosestVertex(rhpial,vtx.x,vtx.y,vtx.z,&drhp);
                }

                if (lhwvtx < 0)
                {
                    dlhw = 1000000000000000.0;
                }
                if (lhpvtx < 0)
                {
                    dlhp = 1000000000000000.0;
                }
                if (rhwvtx < 0)
                {
                    drhw = 1000000000000000.0;
                }
                if (rhpvtx < 0)
                {
                    drhp = 1000000000000000.0;
                }

                if (dlhw <= dlhp && dlhw < drhw && dlhw < drhp && lhwvtx >= 0)
                {
                    annot = lhwhite->vertices[lhwvtx].annotation;
                    hemi = 1;
                    if (lhwhite->ct)
                    {
                        CTABfindAnnotation(lhwhite->ct, annot, &annotid);
                    }
                    else
                    {
                        annotid = annotation_to_index(annot);
                    }
                    dmin = dlhw;
                }
                if (dlhp < dlhw && dlhp < drhw && dlhp < drhp && lhpvtx >= 0)
                {
                    annot = lhwhite->vertices[lhpvtx].annotation;
                    hemi = 1;
                    if (lhwhite->ct)
                    {
                        CTABfindAnnotation(lhwhite->ct, annot, &annotid);
                    }
                    else
                    {
                        annotid = annotation_to_index(annot);
                    }
                    dmin = dlhp;
                }

                if (drhw < dlhp && drhw < dlhw && drhw <= drhp && rhwvtx >= 0)
                {
                    annot = rhwhite->vertices[rhwvtx].annotation;
                    hemi = 2;
                    if (rhwhite->ct)
                    {
                        CTABfindAnnotation(rhwhite->ct, annot, &annotid);
                    }
                    else
                    {
                        annotid = annotation_to_index(annot);
                    }
                    dmin = drhw;
                }
                if (drhp < dlhp && drhp < drhw && drhp < dlhw && rhpvtx >= 0)
                {
                    annot = rhwhite->vertices[rhpvtx].annotation;
                    hemi = 2;
                    if (rhwhite->ct)
                    {
                        CTABfindAnnotation(rhwhite->ct, annot, &annotid);
                    }
                    else
                    {
                        annotid = annotation_to_index(annot);
                    }
                    dmin = drhp;
                }

                // Sometimes the annotation will be "none" indicated by
                // annotid = -1. We interpret this as "unknown".
                if (annotid == -1)
                {
                    annotid = 0;
                }

                // why was this here in the first place?
                /*
                       if (annotid == 0 &&
                           lhwvtx >= 0 &&
                           lhpvtx >= 0 &&
                           rhwvtx >= 0 &&
                           rhpvtx >= 0) {
                         printf("%d %d %d %d\n",
                                lhwhite->vertices[lhwvtx].ripflag,
                                lhpial->vertices[lhpvtx].ripflag,
                                rhwhite->vertices[rhwvtx].ripflag,
                                rhpial->vertices[rhpvtx].ripflag);
                  } */

                if ( IsCortex && hemi == 1)
                {
                    segval = annotid+1000 + baseoffset;  //ctx-lh
                }
                if ( IsCortex && hemi == 2)
                {
                    segval = annotid+2000 + baseoffset;  //ctx-rh
                }
                if (!IsCortex && hemi == 1)
                {
                    segval = annotid+3000 + baseoffset;  // wm-lh
                }
                if (!IsCortex && hemi == 2)
                {
                    segval = annotid+4000 + baseoffset;  // wm-rh
                }

                if (!IsCortex && dmin > dmaxctx && hemi == 1)
                {
                    segval = 5001;
                }
                if (!IsCortex && dmin > dmaxctx && hemi == 2)
                {
                    segval = 5002;
                }

                // This is a hack for getting the right cortical seg with --rip-unknown
                // The aparc+aseg should be passed as CtxSeg.
                if (IsCortex && CtxSeg)
                {
                    segval = MRIgetVoxVal(CtxSeg,c,r,s,0);
                }

                MRIsetVoxVal(ASeg,c,r,s,0,segval);
                MRIsetVoxVal(AParc,c,r,s,0,annot);
                if (OutDistFile != NULL)
                {
                    MRIsetVoxVal(Dist,c,r,s,0,dmin);
                }

                if (debug || annotid == -1)
                {
                    // Gets here when there is no label at the found vertex.
                    // This is different than having a vertex labeled as "unknown"
                    if (!debug)
                    {
                        continue;
                    }
                    printf("\n");
                    printf("Found closest vertex, but it has no label.\n");
                    printf("aseg id = %d\n",asegid);
                    printf("crs = %d %d %d, ras = %6.4f %6.4f %6.4f \n",
                           c,r,s,vtx.x,vtx.y,vtx.z);
                    if (lhwvtx > 0) printf("lhw  %d  %7.5f     %6.4f  %6.4f  %6.4f\n",
                                               lhwvtx, dlhw,
                                               lhwhite->vertices[lhwvtx].x,
                                               lhwhite->vertices[lhwvtx].y,
                                               lhwhite->vertices[lhwvtx].z);
                    if (lhpvtx > 0) printf("lhp  %d  %7.5f     %6.4f  %6.4f  %6.4f\n",
                                               lhpvtx, dlhp,
                                               lhpial->vertices[lhpvtx].x,
                                               lhpial->vertices[lhpvtx].y,
                                               lhpial->vertices[lhpvtx].z);
                    if (rhwvtx > 0) printf("rhw  %d  %7.5f     %6.4f  %6.4f  %6.4f\n",
                                               rhwvtx, drhw,
                                               rhwhite->vertices[rhwvtx].x,
                                               rhwhite->vertices[rhwvtx].y,
                                               rhwhite->vertices[rhwvtx].z);
                    if (rhpvtx > 0) printf("rhp  %d  %7.5f     %6.4f  %6.4f  %6.4f\n",
                                               rhpvtx, drhp,
                                               rhpial->vertices[rhpvtx].x,
                                               rhpial->vertices[rhpvtx].y,
                                               rhpial->vertices[rhpvtx].z);
                    printf("annot = %d, annotid = %d\n",annot,annotid);
                    CTABprintASCII(lhwhite->ct,stdout);
                    continue;
                }

                nctx++;
            }
        }
    }
    printf("nctx = %d\n",nctx);
    printf("Used brute-force search on %d voxels\n",nbrute);

    if (FixParaHipWM)
    {
        /* This is a bit of a hack. There are some vertices that have been
           ripped because they are "unkown". When the above alorithm finds
           these, it searches for the closest known vertex. If this is
           less than dmax away, then the wm voxel gets labeled
           accordingly.  However, there are often some voxels near
           ventralDC that are just close enough in 3d space to parahip to
           get labeled even though they are very far away along the
           surface. These voxels end up forming an island. CCSegment()
           will eliminate any islands. Unforunately, CCSegment() uses
           6-neighbor (face) definition of connectedness, so some voxels
           may be eliminated.
         */
        printf("Fixing Parahip LH WM\n");
        CCSegment(ASeg, 3016, 5001); //3016 = lhphwm, 5001 = unsegmented WM left
        printf("Fixing Parahip RH WM\n");
        CCSegment(ASeg, 4016, 5002); //4016 = rhphwm, 5002 = unsegmented WM right
    }

    printf("Writing output aseg to %s\n",OutASegFile);
    MRIwrite(ASeg,OutASegFile);

    if (OutAParcFile != NULL)
    {
        printf("Writing output aparc to %s\n",OutAParcFile);
        MRIwrite(AParc,OutAParcFile);
    }
    if (OutDistFile != NULL)
    {
        printf("Writing output dist file to %s\n",OutDistFile);
        MRIwrite(Dist,OutDistFile);
    }


    return(0);
}
int
main(int argc, char *argv[]) {
  char          **av, *hemi, *subject_name, *cp, fname[STRLEN];
  char          *parc_name, *annot_name ;
  int           ac, nargs, vno, i ;
  MRI_SURFACE   *mris ;
  MRI           *mri_parc ;
  VERTEX        *v ;
  double        d ;
  Real          x, y, z, xw, yw, zw ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv,
                                 "$Id: mris_sample_parc.c,v 1.31 2016/12/11 14:33:38 fischl Exp $", "$Name:  $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

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

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

  if (argc < 4)
    usage_exit() ;

  subject_name = argv[1] ;
  hemi = argv[2] ;
  parc_name = argv[3] ;
  annot_name = argv[4] ;

  if (strlen(sdir) == 0)  /* if not specified explicitly as option */
  {
    cp = getenv("SUBJECTS_DIR") ;
    if (!cp)
      ErrorExit(ERROR_BADPARM,
                "%s: SUBJECTS_DIR not defined in environment.\n", Progname) ;
    strcpy(sdir, cp) ;
  }

  if (parc_name[0] == '/')  // full path specified
    strcpy(fname, parc_name) ;
  else
    sprintf(fname, "%s/%s/mri/%s", sdir, subject_name, parc_name) ;
  printf("reading parcellation volume from %s...\n", fname) ;
  mri_parc = MRIread(fname) ;
  if (!mri_parc)
    ErrorExit(ERROR_NOFILE, "%s: could not read input volume %s",
              Progname, fname) ;

  if (mask_fname) {
    MRI *mri_mask, *mri_tmp ;

    mri_tmp = MRIread(mask_fname) ;
    if (mri_tmp == NULL)
      ErrorExit(ERROR_BADPARM, "%s: could not load mask volume %s", Progname, mask_fname) ;
    mri_mask = MRIclone(mri_tmp, NULL) ;
    MRIcopyLabel(mri_tmp, mri_mask, mask_val) ;
    MRIdilate(mri_mask, mri_mask) ;
    MRIdilate(mri_mask, mri_mask) ;
    MRIdilate(mri_mask, mri_mask) ;
    MRIdilate(mri_mask, mri_mask) ;
    MRIfree(&mri_tmp) ;
    mri_tmp = MRIclone(mri_parc, NULL) ;
    MRIcopyLabeledVoxels(mri_parc, mri_mask, mri_tmp, mask_val) ;
    MRIfree(&mri_parc) ;
    mri_parc = mri_tmp ;
    if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
      MRIwrite(mri_parc, "p.mgz") ;
    MRIfree(&mri_mask) ;
  }

  for (i = 0 ; i < ntrans ; i++) {
    MRIreplaceValues(mri_parc, mri_parc, trans_in[i], trans_out[i]) ;
  }
  sprintf(fname, "%s/%s/surf/%s.%s", sdir, subject_name, hemi, surf_name) ;
  printf("reading input surface %s...\n", fname) ;
  mris = MRISread(fname) ;
  if (!mris)
    ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
              Progname, fname) ;
  MRISsaveVertexPositions(mris, ORIGINAL_VERTICES) ;
  MRIScomputeMetricProperties(mris) ;
  if (avgs > 0)
    MRISaverageVertexPositions(mris, avgs) ;

  if (FZERO(proj_mm)) {
    if (MRISreadCurvatureFile(mris, thickness_name) != NO_ERROR)
      ErrorExit(ERROR_NOFILE, "%s: could not read thickness file %s",
                Progname, thickness_name) ;
  }

  if (color_table_fname) {
    mris->ct = CTABreadASCII(color_table_fname) ;
    if (mris->ct == NULL)
      ErrorExit(ERROR_NOFILE, "%s: could not read color file %s",
                Progname, color_table_fname) ;
  }

  if (sample_from_vol_to_surf) // sample from volume to surface */
  {
    MRIsampleParcellationToSurface(mris, mri_parc) ;
  } else  /* sample from surface to volume */
  {
    for (vno = 0 ; vno < mris->nvertices ; vno++) {
      v = &mris->vertices[vno] ;
      if (v->ripflag)
        continue ;
      if (vno == Gdiag_no)
        DiagBreak() ;

      if (!FZERO(proj_mm))
        d = proj_mm ;
      else
        d = v->curv*proj_frac ;  /* halfway out */
      x = v->x+d*v->nx ;
      y = v->y+d*v->ny ;
      z = v->z+d*v->nz ;
      MRIsurfaceRASToVoxel(mri_parc, x, y, z, &xw, &yw, &zw) ;
      v->annotation = v->val =
                        MRIfindNearestNonzero(mri_parc, wsize, xw, yw, zw, ((float)wsize-1)/2) ;
      if (v->val == 0xffffffff)
        DiagBreak() ;
    }
  }
  if (replace_label)
    replace_vertices_with_label(mris, mri_parc, replace_label, proj_mm);
  if (unknown_label >= 0) {
    LABEL **labels, *label ;
    int   nlabels, i, biggest_label, most_vertices, nzero ;

#define TMP_LABEL 1000
    for (nzero = vno = 0 ; vno < mris->nvertices ; vno++) {
      v = &mris->vertices[vno] ;
      if (v->annotation == 0) {
        v->annotation = TMP_LABEL;
        nzero++ ;
      }
    }
    printf("%d unknown vertices found\n", nzero) ;
    MRISsegmentAnnotated(mris, &labels, &nlabels, 10) ;
    most_vertices = 0 ;
    biggest_label = -1 ;
    for (i = 0 ; i < nlabels ; i++) {
      label = labels[i] ;
      if (mris->vertices[label->lv[0].vno].annotation == TMP_LABEL) {
        if (label->n_points > most_vertices) {
          biggest_label = i ;
          most_vertices = label->n_points ;
        }
      }
    }
    if (biggest_label >= 0) {
      label = labels[biggest_label] ;
      printf("replacing label # %d with %d vertices "
             "(vno=%d) with label %d\n",
             biggest_label,
             label->n_points,
             label->lv[0].vno,
             unknown_label) ;
      for (i = 0 ; i < label->n_points ; i++) {
        v = &mris->vertices[label->lv[i].vno] ;
        v->annotation = v->val = unknown_label ;
      }
    }
    for (nzero = vno = 0 ; vno < mris->nvertices ; vno++) {
      v = &mris->vertices[vno] ;
      if (v->annotation == TMP_LABEL) {
        v->annotation = 0;
        nzero++ ;
      }
    }
    printf("after replacement, %d unknown vertices found\n", nzero) ;
    MRISmodeFilterZeroVals(mris) ;  /* get rid of the rest
                                    of the unknowns by mode filtering */
    for (i = 0 ; i < nlabels ; i++)
      LabelFree(&labels[i]) ;
    free(labels) ;
  }

  MRIScopyValsToAnnotations(mris) ;
  if (fix_topology != 0)
    fix_label_topology(mris, fix_topology) ;

  if (mode_filter) {
    printf("mode filtering sample labels...\n") ;
#if 0
    MRISmodeFilterZeroVals(mris) ;
#else
    MRISmodeFilterVals(mris, mode_filter) ;
#endif
    for (vno = 0 ; vno < mris->nvertices ; vno++) {
      v = &mris->vertices[vno] ;
      if (v->ripflag)
        continue ;
      v->annotation = v->val ;
    }
  }

  /* this will fill in the v->annotation field from the v->val ones */
  translate_indices_to_annotations(mris, translation_fname) ;

  if (label_index >= 0)
  {
    int index ;
    LABEL *area ;

    printf("writing label to %s...\n", annot_name) ;
    MRISclearMarks(mris) ;
    for (vno = 0 ; vno < mris->nvertices ; vno++)
    {
      if (vno == Gdiag_no)
        DiagBreak() ;
      v = &mris->vertices[vno] ;
      if (v->annotation > 0)
        DiagBreak() ;
      CTABfindAnnotation(mris->ct, v->annotation, &index);
      if (index == label_index)
        v->marked = 1 ;
    }
    area = LabelFromMarkedSurface(mris) ;
    if (nclose > 0)
    {
      LabelDilate(area, mris, nclose, CURRENT_VERTICES) ;
      LabelErode(area, mris, nclose) ;
    }
    LabelWrite(area, annot_name) ;
  }
  else
  {
    printf("writing annotation to %s...\n", annot_name) ;
    MRISwriteAnnotation(mris, annot_name) ;
  }
  /*  MRISreadAnnotation(mris, fname) ;*/
  exit(0) ;

  return(0) ;  /* for ansi */
}
int main(int argc, char *argv[]) {
  char   **av;
  MRI *mri_seg;
  int ac, nargs;

  int x, y, z;
  int target_value = 255;


  Progname = argv[0];

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

  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 (!stricmp(hemi, "lh")) {
    target_value = lh_label;
  } else {
    target_value = rh_label;
  }

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

  for (z = 0; z < mri_seg->depth; z++)
    for (y = 0; y < mri_seg->height; y++)
      for (x = 0; x < mri_seg->width; x++) {
        if (MRIgetVoxVal(mri_seg, x, y, z, 0) < threshold)
          MRIsetVoxVal(mri_seg, x, y, z, 0, 0);
        else
          MRIsetVoxVal(mri_seg, x, y, z, 0, 255);
      }

  GetLargestCC6(mri_seg);

  for (z = 0; z < mri_seg->depth; z++)
    for (y = 0; y < mri_seg->height; y++)
      for (x = 0; x < mri_seg->width; x++) {
        if (MRIgetVoxVal(mri_seg, x, y, z, 0) > 0)
          MRIsetVoxVal(mri_seg, x, y, z, 0, target_value);
      }

  MRIwrite(mri_seg, argv[2]);

  exit(0);

}  /*  end main()  */
Exemple #20
0
int
main(int argc,
     char* argv[])
{
  IoParams params;
  try
  {
    params.parse(argc,argv);
  }
  catch (const std::exception& excp)
  {
    std::cerr << " Exception while parsing cmd-line\n"
    << excp.what() << std::endl;
    exit(1);
  }
  catch (...)
  {
    std::cerr << " unhandled exception caught while parsing cmd line\n";
    exit(1);
  }


  boost::shared_ptr<gmp::VolumeMorph> pmorph(new gmp::VolumeMorph);

  if ( !params.strTemplate.empty() )
  {
    MRI* mri = MRIread( const_cast<char*>(params.strTemplate.c_str()) );
    if (!mri)
      std::cerr << " Failed to open template mri "
                << params.strTemplate << std::endl;
    else
      pmorph->set_volGeom_fixed(mri);
    MRIfree(&mri);
  }
  if ( !params.strSubject.empty() )
  {
    MRI* mri = MRIread( const_cast<char*>(params.strSubject.c_str()) );
    if (!mri)
      std::cerr << " Failed to open subject mri "
                << params.strSubject << std::endl;
    else
      pmorph->set_volGeom_moving(mri);
    MRIfree(&mri);
  }

  IoParams::MorphContainerType::iterator it;
  for ( it = params.items.begin();
        it != params.items.end();
        ++it )
  {
    if ( it->type == "affine" )
    {
      boost::shared_ptr<gmp::AffineTransform3d>
      paffine( new gmp::AffineTransform3d);
      float* pf = read_transform( it->file.c_str() );
      if ( !pf )
      {
        std::cerr << " failed to read transform\n";
        exit(1);
      }
      paffine->set_pars( pf);
      pmorph->m_transforms.push_back( paffine );

    }
    else if ( it->type == "volume" )
    {
      boost::shared_ptr<gmp::DeltaTransform3d>
      pvol( new gmp::DeltaTransform3d);
      MRI* field = MRIread
                   ( const_cast<char*>( it->file.c_str() ) );
      if ( !field )
      {
        std::cerr << " failed to read field "  << std::endl;
        exit(1);
      }
      pvol->set_field(field);

      pmorph->m_transforms.push_back( pvol );
    }
    else if ( it->type == "gcam" )
    {
      boost::shared_ptr<gmp::DeltaTransform3d>
      pvol( new gmp::DeltaTransform3d);
      GCA_MORPH* gcam = GCAMread( const_cast<char*>( it->file.c_str() ) );
      if ( !gcam )
      {
        std::cerr << " failed to read GCAM " << std::endl;
        exit(1);
      }
      // create bogus MRI to hold the geometry
      MRI* mri_template = MRIread( const_cast<char*>
                                   ( params.strTemplate.c_str() ) );
      MRI* mriBuf = MRIalloc( gcam->image.width,
                              gcam->image.height,
                              gcam->image.depth,
                              MRI_UCHAR);
      useVolGeomToMRI( &gcam->image, mriBuf );
      GCAMrasToVox(gcam, mriBuf );
      MRIfree( &mriBuf );

      std::cout << " atlas geometry = "
      << gcam->atlas.width << " , " << gcam->atlas.height
      << " , " << gcam->atlas.depth << std::endl
      << " image geometry = "
      << gcam->image.width << " , " << gcam->image.height
      << " , " << gcam->image.depth << std::endl;


      MRI* mri = MRIallocSequence( mri_template->width,
                                   mri_template->height,
                                   mri_template->depth,
                                   MRI_FLOAT,
                                   3);
      MRIcopyHeader(mri_template, mri);
      g_vDbgCoords = params.vDbgCoords;
      try
      {
        //MRI* mask =
        CopyGcamToDeltaField(gcam, mri);

        pvol->set_field(mri);
        //pvol->set_mask(mask);
        pmorph->m_transforms.push_back( pvol );
      }
      catch (const std::string& e)
      {
        std::cerr << " Exception caught while processing GCAM node\n"
        << e << std::endl;
        exit(1);
      }
      MRIfree(&mri_template);
    }
    else if ( it->type == "morph" )
    {
      boost::shared_ptr<gmp::VolumeMorph> tmpMorph(new gmp::VolumeMorph);
      try
      {
        tmpMorph->load( it->file.c_str() );
      }
      catch (const char* msg)
      {
        std::cerr << " Exception caught while loading morph in file "
        << it->file << std::endl;
        exit(1);
      }
      for ( gmp::VolumeMorph::TransformContainerType::iterator transformIter
            = tmpMorph->m_transforms.begin();
            transformIter != tmpMorph->m_transforms.end();
            ++transformIter )
        pmorph->m_transforms.push_back( *transformIter );

    }
    else if ( it->type == "mesh" )
    {
      boost::shared_ptr<gmp::FemTransform3d> pfem(new gmp::FemTransform3d);
      boost::shared_ptr<CMesh3d> pmesh(new CMesh3d);
      pmesh->load( it->file.c_str() );
      pfem->m_sharedMesh = pmesh;
      pmorph->m_transforms.push_back(pfem);
    }
    else
    {
      std::cerr << " unhandled transform type "
      << it->type << std::endl;
    }
  } // next it

  // finally write morph file
  try
  {
    pmorph->save( params.strOut.c_str() );
  }
  catch (const char* msg)
  {
    std::cerr << " Exception caught while saving morph\n"
    << msg << std::endl;
    exit(1);
  }

  return 0;
}
int
main(int argc, char *argv[])
{
  char        **av, *in_fname, *out_fname ;
  int         ac, nargs, i, label ;
  MRI         *mri_in, *mri_out, *mri_kernel, *mri_smoothed ;

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

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

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

  if (argc < 4)
    usage_exit() ;

  in_fname = argv[1] ;
  out_fname = argv[argc-1] ;

  printf("reading volume from %s...\n", in_fname) ;
  mri_in = MRIread(in_fname) ;
  if (!mri_in)
    ErrorExit(ERROR_NOFILE, "%s: could not read MRI volume %s", Progname,
              in_fname) ;
  if (out_like_fname)
  {
    MRI *mri_tmp = MRIread(out_like_fname) ;
    if (!mri_tmp)
      ErrorExit
      (ERROR_NOFILE,
       "%s: could not read template volume from %s",
       out_like_fname) ;
    mri_out = MRIalloc(mri_tmp->width,
                       mri_tmp->height,
                       mri_tmp->depth,
                       mri_tmp->type) ;
    /*    MRIcopyHeader(mri_tmp, mri_out) ;*/
    MRIfree(&mri_tmp) ;
  }
  else
    mri_out = MRIclone(mri_in, NULL) ;

  for (i = 2 ; i < argc-1 ; i++)
  {
    label = atoi(argv[i]) ;
    printf("extracting label %d (%s)\n", label, cma_label_to_name(label)) ;
    extract_labeled_image(mri_in, transform, label, mri_out) ;
  }
  if (!FZERO(sigma))
  {
    printf("smoothing extracted volume...\n") ;
    mri_kernel = MRIgaussian1d(sigma, 10*sigma) ;
    mri_smoothed = MRIconvolveGaussian(mri_out, NULL, mri_kernel) ;
    MRIfree(&mri_out) ;
    mri_out = mri_smoothed ;
  }
  /* removed for gcc3.3
   * vsprintf(out_fname, out_fname, (va_list) &label) ;
   */
  if (dilate > 0)
  {
    int i ;
    printf("dilating output volume %d times...\n", dilate) ;
    for (i = 0 ; i < dilate ; i++)
      MRIdilate(mri_out, mri_out) ;
  }
  if (erode > 0)
  {
    int i ;
    printf("eroding output volume %d times...\n", erode) ;
    for (i = 0 ; i < erode ; i++)
      MRIerode(mri_out, mri_out) ;
  }
  printf("writing output to %s.\n", out_fname) ;
  MRIwrite(mri_out, out_fname) ;

  if (exit_none_found && (nvoxels == 0))
  {
    printf("No voxels with specified label were found!\n");
    exit(1);
  }

  exit(0) ;
  return(0) ;  /* for ansi */
}
int
main(int argc, char *argv[]) 
{
  char   **av, fname[STRLEN], *cp ;
  int    ac, nargs ;
  char   *subject, *out_fname, *hemi, *ohemi ;
  int    msec, minutes, seconds ;
  struct timeb start ;
  MRI          *mri, *mri_features, *mri_ribbon, *mri_aseg, *mri_aparc ;
  MRI_SURFACE  *mris, *mris_contra ;
  LABEL        *cortex ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mri_extract_fcd_features.c,v 1.1 2016/06/15 17:51:09 fischl Exp $", "$Name:  $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

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

  TimerStart(&start) ;

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

  if (argc < 4)
    usage_exit(1) ;

  subject = argv[1] ;
  hemi = argv[2] ;
  if (strcmp(hemi, "lh") == 0)
    ohemi = "rh" ;
  else
    ohemi = "lh" ;

  out_fname = argv[3] ;
  printf("reading data for subject %s and writing output to %s\n", subject, out_fname) ;

  if (!strlen(sdir))
  {
    cp = getenv("SUBJECTS_DIR") ;
    if (!cp)
      ErrorExit(ERROR_BADPARM,
                "%s: SUBJECTS_DIR not defined in environment.\n", Progname) ;
    strcpy(sdir, cp) ;
  }

  sprintf(fname, "%s/%s/surf/%s.%s", sdir, subject, hemi, white_name) ;
  printf("reading %s\n", fname) ;
  mris  = MRISread(fname) ;
  if (mris == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not read surface from %s\n", Progname, fname) ;
  MRISsaveVertexPositions(mris, WHITE_VERTICES) ;
  

  sprintf(fname, "%s/%s/surf/%s.%s", sdir, subject, ohemi, white_name) ;
  printf("reading %s\n", fname) ;
  mris_contra  = MRISread(fname) ;
  if (mris_contra == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not read surface from %s\n", Progname, fname) ;
  MRISsaveVertexPositions(mris_contra, WHITE_VERTICES) ;

  sprintf(fname, "%s/%s/mri/%s", sdir, subject, ribbon_name) ;
  printf("reading %s\n", fname) ;
  mri_ribbon  = MRIread(fname) ;
  if (mri_ribbon == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not read ribbon from %s\n", Progname, fname) ;

  sprintf(fname, "%s/%s/mri/%s", sdir, subject, aparc_name) ;
  printf("reading %s\n", fname) ;
  mri_aparc  = MRIread(fname) ;
  if (mri_aparc == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not read ribbon from %s\n", Progname, fname) ;

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

  sprintf(fname, "%s/%s/surf/%s.%s", sdir, subject, hemi, pial_name) ;
  if (MRISreadPialCoordinates(mris, fname) != NO_ERROR)
    ErrorExit(ERROR_NOFILE, "%s: could not read pial coordinates from %s\n", Progname, fname) ;

  sprintf(fname, "%s/%s/surf/%s.%s", sdir, subject, hemi, sphere_name) ;
  if (MRISreadCanonicalCoordinates(mris, fname) != NO_ERROR)
    ErrorExit(ERROR_NOFILE, "%s: could not read left/right spherical coordinates from %s\n", Progname, fname) ;
  

  sprintf(fname, "%s/%s/surf/%s.%s", sdir, subject, ohemi, pial_name) ;
  if (MRISreadPialCoordinates(mris_contra, fname) != NO_ERROR)
    ErrorExit(ERROR_NOFILE, "%s: could not read pial coordinates from %s\n", Progname, fname) ;

  sprintf(fname, "%s/%s/label/%s.%s", sdir, subject, hemi, cortex_label) ;
  cortex = LabelRead(NULL, fname) ;
  if (cortex == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not read cortical label from %s\n", Progname, fname) ;
  LabelRipRestOfSurface(cortex, mris) ;
  LabelFree(&cortex) ;

  sprintf(fname, "%s/%s/surf/%s.%s", sdir, subject, ohemi, sphere_name) ;
  if (MRISreadCanonicalCoordinates(mris_contra, fname) != NO_ERROR)
    ErrorExit(ERROR_NOFILE, "%s: could not read left/right spherical coordinates from %s\n", Progname, fname) ;
  

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

  if (0)
    mri_features = MRIcomputeSurfaceDistanceProbabilities(mris, mri_ribbon, mri, mri_aseg) ;
  else
  {
    MRI *mri_ohemi_features, *mri_ohemi_mapped_to_hemi_features ;

    mri_features = MRIcomputeSurfaceDistanceIntensities(mris, mri_ribbon, mri_aparc, mri, mri_aseg, whalf) ;
    mri_ohemi_features = MRIcomputeSurfaceDistanceIntensities(mris_contra, mri_ribbon, mri_aparc, mri, mri_aseg, whalf) ;
    mri_ohemi_mapped_to_hemi_features = MRISmapToSurface(mris_contra, mris, mri_ohemi_features, NULL) ; // map contra feature to this surface
//    MRIwrite(mri_ohemi_mapped_to_hemi_features, "test.mgz") ;
    MRIsubtract(mri_features, mri_ohemi_mapped_to_hemi_features, mri_features) ;
  }
 
  if (navgs > 0)
  {
    MRI *mri_tmp ;
    mri_tmp = MRISsmoothMRI(mris, mri_features, navgs, NULL, NULL);
    MRIfree(&mri_features) ;
    mri_features = mri_tmp ;
  }
  printf("writing output to %s\n", out_fname) ;
  if (Gdiag_no >= 0)
    printf("feature(%d) = %f\n", Gdiag_no, MRIgetVoxVal(mri_features, Gdiag_no, 0, 0, 0)) ;


  MRIwrite(mri_features, out_fname) ;

  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  fprintf(stderr, "feature extraction took %d minutes and %d seconds.\n", minutes, seconds) ;
  exit(0) ;
  return(0) ;
}
int
main(int argc, char *argv[])
{
  char         *in_fname, *out_fname, **av, *xform_fname, fname[STRLEN] ;
  MRI          *mri_in, *mri_tmp ;
  int          ac, nargs, msec, minutes, seconds;
  int          input, ninputs ;
  struct timeb start ;
  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_fuse_intensity_images.c,v 1.2 2011/06/02 14:05:10 fischl Exp $",
     "$Name:  $", cmdline);

  /* rkt: check for and handle version tag */
  nargs = handle_version_option
    (argc, argv,
     "$Id: mri_fuse_intensity_images.c,v 1.2 2011/06/02 14:05:10 fischl Exp $",
     "$Name:  $");
  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 < 5)
    ErrorExit
      (ERROR_BADPARM,
       "usage: %s [<options>] <longitudinal time point file> <in vol> <transform file> <out vol> \n",
       Progname) ;
  in_fname = argv[2] ;
  xform_fname = argv[3] ;
  out_fname = argv[4] ;

  transform = TransformRead(xform_fname) ;
  if (transform == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not read transform from %s", Progname, xform_fname) ;
  TimerStart(&start) ;

  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", Progname, 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 (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) ;

  // try to bring the images closer to each other at each voxel where they seem to come from the same distribution
  {
    MRI   *mri_frame1, *mri_frame2 ;
    double rms_after ;

    mri_frame1 = MRIcopyFrame(mri_in, NULL, 0, 0) ;
    mri_frame2 = MRIcopyFrame(mri_in, NULL, 1, 0) ;
    rms_after = MRIrmsDiff(mri_frame1, mri_frame2) ;
    printf("RMS before intensity cohering  = %2.2f\n", rms_after) ;
    MRIfree(&mri_frame1) ; MRIfree(&mri_frame2) ; 
    if (0)
      normalize_timepoints(mri_in, 2.0, cross_time_sigma) ;
    else
      normalize_timepoints_with_parzen_window(mri_in, cross_time_sigma) ;
      
    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 (sigma=%2.2f)\n", rms_after, cross_time_sigma) ;
  }

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

  MRIfree(&mri_in) ;

  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) ;
}
Exemple #24
0
/*---------------------------------------------------------------*/
int main(int argc, char *argv[]) {
    int nargs,n;
    MRIS *SurfReg[100];
    MRI *SrcVal, *TrgVal;
    char *base;

    nargs = handle_version_option (argc, argv, vcid, "$Name:  $");
    if (nargs && argc - nargs == 1) exit (0);
    argc -= nargs;
    cmdline = argv2cmdline(argc,argv);
    uname(&uts);
    getcwd(cwd,2000);

    Progname = argv[0] ;
    argc --;
    argv++;
    ErrorInit(NULL, NULL, NULL) ;
    DiagInit(NULL, NULL, NULL) ;
    if (argc == 0) usage_exit();
    parse_commandline(argc, argv);
    check_options();
    if (checkoptsonly) return(0);
    dump_options(stdout);

    printf("Loading %s\n",SrcValFile);
    SrcVal = MRIread(SrcValFile);
    if(SrcVal==NULL) exit(1);

    if(DoSynthRand) {
        if (SynthSeed < 0) SynthSeed = PDFtodSeed();
        printf("INFO: synthesizing, seed = %d\n",SynthSeed);
        srand48(SynthSeed);
        MRIrandn(SrcVal->width, SrcVal->height, SrcVal->depth,
                 SrcVal->nframes,0, 1, SrcVal);
    }
    if(DoSynthOnes != 0) {
        printf("INFO: filling input with all 1s\n");
        MRIconst(SrcVal->width, SrcVal->height, SrcVal->depth,
                 SrcVal->nframes, 1, SrcVal);
    }

    for(n=0; n<nsurfs; n++) {
        printf("%d Loading %s\n",n+1,SurfRegFile[n]);
        base = fio_basename(SurfRegFile[n],".tri");
        if(strcmp(base,"ic7")==0) {
            // Have to do it this way to rescale. Need to find a better more robust way.
            printf("   reading as ico 7, rescaling radius to 100\n");
            SurfReg[n] = ReadIcoByOrder(7, 100);
        }
        else
            SurfReg[n] = MRISread(SurfRegFile[n]);
        free(base);
        if(SurfReg[n]==NULL) exit(1);
    }

    TrgVal = MRISapplyReg(SrcVal, SurfReg, nsurfs,ReverseMapFlag,DoJac,UseHash);
    if(TrgVal == NULL) exit(1);

    printf("Writing %s\n",TrgValFile);
    MRIwrite(TrgVal,TrgValFile);

    printf("mris_apply_reg done\n");
    return 0;
}
Exemple #25
0
int main(int argc, char *argv[]) {
  tesselation_parms *parms;
  MRIS **mris_table, *mris,*mris_corrected;
  MRI *mri;

  char cmdline[CMD_LINE_LEN] ;

  make_cmd_version_string 
    (argc, argv, 
     "$Id: mri_mc.c,v 1.22 2011/03/02 00:04:23 nicks Exp $", "$Name: stable5 $", 
     cmdline);
  Progname=argv[0];

  if (argc > 1 && (stricmp(argv[1], "-d") == 0)) {
    downsample = atoi(argv[2]) ;
    argc -= 2;
    argv += 2 ;
    printf("downsampling input volume %d times\n", downsample) ;
  }

  if (argc < 4) {
    fprintf(stderr,"\n\nUSAGE: mri_mc input_volume "
            "label_value output_surface [connectivity]");
    fprintf(stderr,
            "\noption connectivity: 1=6+,2=18,3=6,4=26 (default=1)\n\n");
    exit(-1);
  }

  parms=(tesselation_parms*)calloc(1,sizeof(tesselation_parms));
  if (!parms)
    ErrorExit(ERROR_NOMEMORY, "tesselation parms\n") ;
  mri=MRIread(argv[1]);
  if (downsample > 0) {
    MRI *mri_tmp ;
    mri_tmp = MRIdownsample2(mri, NULL) ;
    MRIfree(&mri) ;
    mri = mri_tmp ;
  }
  {
    MRI *mri_tmp ;
    mri_tmp = MRIalloc(mri->width+2, mri->height+2, mri->depth+2, mri->type) ;
    MRIextractInto(mri, mri_tmp, 
                   0, 0, 0, 
                   mri->width, mri->height, mri->depth, 
                   1, 1, 1) ;
    MRIfree(&mri) ;
    mri = mri_tmp ;
  }
  MRIreInitCache(mri);
  if (mri->type != MRI_UCHAR) {
    MRI *mri_tmp ;
    float min_val, max_val ;

    MRIvalRange(mri, &min_val, &max_val) ;
    if (min_val < 0 || max_val > 255)
      ErrorExit
        (ERROR_UNSUPPORTED, 
         "%s: input volume (val range [%2.1f %2.1f]) must be "
         "convertible to UCHAR",
         Progname, min_val, max_val) ;
    printf("changing type of input volume to 8 bits/voxel...\n") ;
    mri_tmp = MRIchangeType(mri, MRI_UCHAR, 0.0, 0.999, TRUE) ;
    MRIfree(&mri) ;
    mri = mri_tmp ;
  }

  parms->mri=mri;

  parms->number_of_labels=1; //only one single label
  parms->label_values=(int*)malloc(sizeof(int));
  parms->label_values[0]=atoi(argv[2]);//label;
  parms->ind=0;
  mris_table=(MRIS**)malloc(sizeof(MRIS*)); //final surface information
  parms->mris_table=mris_table;
  if ((!parms->label_values) || (!mris_table))
    ErrorExit(ERROR_NOMEMORY, "labels/surfaces tables\n") ;

  if (argc==5) parms->connectivity=atoi(argv[4]);//connectivity;
  else parms->connectivity=1;

  initTesselationParms(parms);

  generateMCtesselation(parms);

  free(parms->label_values);
  mris=parms->mris_table[0];
  free(parms->mris_table);
  freeTesselationParms(&parms);

  {
    float dist,max_e=0.0;
    int n,p,vn0,vn2;
    VERTEX *v,*vp;
    fprintf(stderr,"computing the maximum edge length...");
    for (n = 0 ; n < mris->nvertices ; n++) {
      v=&mris->vertices[n];
      for (p = 0 ; p < v->vnum ; p++) {
        vp = &mris->vertices[v->v[p]];
        dist=SQR(vp->x-v->x)+SQR(vp->y-v->y)+SQR(vp->z-v->z);
        if (dist>max_e) max_e=dist;
      }
    }
    fprintf(stderr,"%f mm",sqrt(max_e));
    fprintf(stderr,"\nreversing orientation of faces...");
    for (n = 0 ; n < mris->nfaces ; n++) {
      vn0=mris->faces[n].v[0];
      vn2=mris->faces[n].v[2];
      /* vertex 0 becomes vertex 2 */
      v=&mris->vertices[vn0];
      for (p = 0 ; p < v->num ; p++)
        if (v->f[p]==n)
          v->n[p]=2;
      mris->faces[n].v[2]=vn0;
      /* vertex 2 becomes vertex 0 */
      v=&mris->vertices[vn2];
      for (p = 0 ; p < v->num ; p++)
        if (v->f[p]==n)
          v->n[p]=0;
      mris->faces[n].v[0]=vn2;
    }
  }

  fprintf(stderr,"\nchecking orientation of surface...");
  MRISmarkOrientationChanges(mris);
  mris_corrected=MRISextractMainComponent(mris,0,1,0);

  MRISfree(&mris);

  fprintf(stderr,"\nwriting out surface...");
  MRISaddCommandLine(mris_corrected, cmdline) ;
  if (mriConformed(mri) == 0) {
    printf("input volume is not conformed - using useRealRAS=1\n") ;
    mris_corrected->useRealRAS = 1 ;
  }
  //  getVolGeom(mri, &mris_corrected->vg);
  MRISwrite(mris_corrected,argv[3]);
  fprintf(stderr,"done\n");

  MRIfree(&mri);
  MRISfree(&mris_corrected);

  return 0;
}
Exemple #26
0
/*---------------------------------------------------------------*/
int main(int argc, char *argv[]) {
  int nargs, n, Ntp, nsearch, nsearch2=0;
  double fwhm = 0, nresels, voxelvolume, nvoxperresel, reselvolume;
  double car1mn, rar1mn,sar1mn,cfwhm,rfwhm,sfwhm, ftmp;
  double car2mn, rar2mn,sar2mn;
  double gmean, gstd, gmax;
  FILE *fp;

  sprintf(tmpstr, "S%sER%sRONT%sOR", "URF", "_F", "DO") ;
  setenv(tmpstr,"1",0);

  nargs = handle_version_option (argc, argv, vcid, "$Name:  $");
  if (nargs && argc - nargs == 1) exit (0);
  argc -= nargs;
  cmdline = argv2cmdline(argc,argv);
  uname(&uts);
  getcwd(cwd,2000);

  Progname = argv[0] ;
  argc --;
  argv++;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;
  if (argc == 0) usage_exit();
  parse_commandline(argc, argv);
  check_options();
  if (checkoptsonly) return(0);

  if (SynthSeed < 0) SynthSeed = PDFtodSeed();
  if (debug) dump_options(stdout);

  // ------------- load or synthesize input ---------------------
  InVals = MRIreadType(inpath,InValsType);
  if(InVals == NULL) exit(1);
  if(SetTR){
    printf("Setting TR to %g ms\n",TR);
    InVals->tr = TR;
  }
  if((nframes < 0 && synth) || !synth) nframes = InVals->nframes;
  if(nframes < nframesmin && !SmoothOnly && !sum2file) {
    printf("ERROR: nframes = %d, need at least %d\n",
	   nframes,nframesmin);
    exit(1);
  }
  if (InVals->type != MRI_FLOAT) {
    mritmp = MRISeqchangeType(InVals, MRI_FLOAT, 0, 0, 0);
    MRIfree(&InVals);
    InVals = mritmp;
  }
  if(synth) {
    printf("Synthesizing %d frames, Seed = %d\n",nframes,SynthSeed);
    mritmp = MRIcloneBySpace(InVals,MRI_FLOAT,nframes);
    MRIfree(&InVals);
    MRIrandn(mritmp->width, mritmp->height, mritmp->depth, 
	     nframes, 0, 1, mritmp);
    InVals = mritmp;
  }
  voxelvolume = InVals->xsize * InVals->ysize * InVals->zsize ;
  printf("voxelvolume %g mm3\n",voxelvolume);

  if(DoSqr){
    printf("Computing square of input\n");
    MRIsquare(InVals,NULL,InVals);
  }

  // -------------------- handle masking ------------------------
  if (maskpath) {
    printf("Loading mask %s\n",maskpath);
    mask = MRIread(maskpath);
    if(mask==NULL) exit(1);
    if(MRIdimMismatch(mask,InVals,0)){
      printf("ERROR: dimension mismatch between mask and input\n");
      exit(1);
    }
    MRIbinarize2(mask, mask, maskthresh, 0, 1);
  }
  if (automask) {
    RFglobalStats(InVals, NULL, &gmean, &gstd, &gmax);
    maskthresh = gmean * automaskthresh;
    printf("Computing mask, relative threshold = %g, gmean = %g, absthresh = %g\n",
           automaskthresh,gmean,maskthresh);
    mritmp = MRIframeMean(InVals,NULL);
    //MRIwrite(mritmp,"fmean.mgh");
    mask = MRIbinarize2(mritmp, NULL, maskthresh, 0, 1);
    MRIfree(&mritmp);
  }
  if (mask) {
    if (maskinv) {
      printf("Inverting mask\n");
      MRImaskInvert(mask,mask);
    }
    nsearch = MRInMask(mask);
    if (nsearch == 0) {
      printf("ERROR: no voxels found in mask\n");
      exit(1);
    }
    // Erode the mask -----------------------------------------------
    if (nerode > 0) {
      printf("Eroding mask %d times\n",nerode);
      for (n=0; n<nerode; n++) MRIerode(mask,mask);
      nsearch2 = MRInMask(mask);
      if (nsearch2 == 0) {
        printf("ERROR: no voxels found in mask after eroding\n");
        exit(1);
      }
      printf("%d voxels in mask after eroding\n",nsearch2);
    }
    //---- Save mask -----
    if (outmaskpath) MRIwrite(mask,outmaskpath);
  } else nsearch = InVals->width * InVals->height * InVals->depth;
  printf("Search region is %d voxels = %lf mm3\n",nsearch,nsearch*voxelvolume);

  if( (infwhm > 0 || infwhmc > 0 || infwhmr > 0 || infwhms > 0) && SmoothOnly) {
    if(SaveUnmasked) mritmp = NULL;
    else             mritmp = mask;
    if(infwhm > 0) {
      printf("Smoothing input by fwhm=%lf, gstd=%lf\n",infwhm,ingstd);
      MRImaskedGaussianSmooth(InVals, mritmp, ingstd, InVals);
    }
    if(infwhmc > 0 || infwhmr > 0 || infwhms > 0) {
      printf("Smoothing input by fwhm=(%lf,%lf,%lf) gstd=(%lf,%lf,%lf)\n",
	     infwhmc,infwhmr,infwhms,ingstdc,ingstdr,ingstds);
      MRIgaussianSmoothNI(InVals, ingstdc, ingstdr, ingstds, InVals);
    }
    printf("Saving to %s\n",outpath);
    MRIwrite(InVals,outpath);
    printf("SmoothOnly requested, so exiting now\n");
    exit(0);
  }

  // Make a copy, if needed, prior to doing anything to data
  if(outpath) InValsCopy = MRIcopy(InVals,NULL);

  // Compute variance reduction factor -------------------
  if(sum2file){
    ftmp = MRIsum2All(InVals);
    fp = fopen(sum2file,"w");
    if(fp == NULL){
      printf("ERROR: opening %s\n",sum2file);
      exit(1);
    }
    printf("sum2all: %20.10lf\n",ftmp);
    printf("vrf: %20.10lf\n",1/ftmp);
    fprintf(fp,"%20.10lf\n",ftmp);
    exit(0);
  }

  //------------------------ Detrend ------------------
  if(DetrendOrder >= 0) {
    Ntp = InVals->nframes;
    printf("Polynomial detrending, order = %d\n",DetrendOrder);
    X = MatrixAlloc(Ntp,DetrendOrder+1,MATRIX_REAL);
    for (n=0;n<Ntp;n++) X->rptr[n+1][1] = 1.0;
    ftmp = Ntp/2.0;
    if (DetrendOrder >= 1)
      for (n=0;n<Ntp;n++) X->rptr[n+1][2] = (n-ftmp)/ftmp;
    if (DetrendOrder >= 2)
      for (n=0;n<Ntp;n++) X->rptr[n+1][3] = pow((n-ftmp),2.0)/(ftmp*ftmp);
  }
  if(X){
    printf("Detrending\n");
    if (X->rows != InVals->nframes) {
      printf("ERROR: dimension mismatch between X and input\n");
      exit(1);
    }
    mritmp = fMRIdetrend(InVals,X);
    if (mritmp == NULL) exit(1);
    MRIfree(&InVals);
    InVals = mritmp;
  }

  // ------------ Smooth Input BY infwhm -------------------------
  if(infwhm > 0) {
    printf("Smoothing input by fwhm=%lf, gstd=%lf\n",infwhm,ingstd);
    MRImaskedGaussianSmooth(InVals, mask, ingstd, InVals);
  }
  // ------------ Smooth Input BY infwhm -------------------------
  if(infwhmc > 0 || infwhmr > 0 || infwhms > 0) {
    printf("Smoothing input by fwhm=(%lf,%lf,%lf) gstd=(%lf,%lf,%lf)\n",
	   infwhmc,infwhmr,infwhms,ingstdc,ingstdr,ingstds);
    MRIgaussianSmoothNI(InVals, ingstdc, ingstdr, ingstds, InVals);
  }

  // ------------ Smooth Input TO fwhm -------------------------
  if (tofwhm > 0) {
    printf("Attempting to smooth to %g +/- %g mm fwhm (nitersmax=%d)\n",
           tofwhm,tofwhmtol,tofwhmnitersmax);
    mritmp = MRImaskedGaussianSmoothTo(InVals, mask, tofwhm,
                                       tofwhmtol, tofwhmnitersmax,
                                       &byfwhm, &tofwhmact, &tofwhmniters,
                                       InVals);
    if (mritmp == NULL) exit(1);
    printf("Smoothed by %g to %g in %d iterations\n",
           byfwhm,tofwhmact,tofwhmniters);
    if (tofwhmfile) {
      fp = fopen(tofwhmfile,"w");
      if (!fp) {
        printf("ERROR: opening %s\n",tofwhmfile);
        exit(1);
      }
      fprintf(fp,"tofwhm    %lf\n",tofwhm);
      fprintf(fp,"tofwhmtol %lf\n",tofwhmtol);
      fprintf(fp,"tofwhmact %lf\n",tofwhmact);
      fprintf(fp,"byfwhm    %lf\n",byfwhm);
      fprintf(fp,"niters    %d\n",tofwhmniters);
      fprintf(fp,"nitersmax %d\n",tofwhmnitersmax);
      fclose(fp);
    }
  }

  // ------ Save smoothed/detrended ------------------------------
  if(outpath) {
    // This is a bit of a hack in order to be able to save undetrended
    // Operates on InValsCopy, which has not been modified (requires
    // smoothing twice, which is silly:).
    printf("Saving to %s\n",outpath);
    // Smoothed output will not be masked
    if (SaveDetrended && X) {
      mritmp = fMRIdetrend(InValsCopy,X);
      if (mritmp == NULL) exit(1);
      MRIfree(&InValsCopy);
      InValsCopy = mritmp;
    }
    if (SaveUnmasked) mritmp = NULL;
    else             mritmp = mask;
    if(infwhm > 0)
      MRImaskedGaussianSmooth(InValsCopy, mritmp, ingstd, InValsCopy);
    if(infwhmc > 0 || infwhmr > 0 || infwhms > 0) 
      MRIgaussianSmoothNI(InValsCopy, ingstdc, ingstdr, ingstds, InValsCopy);
    if(tofwhm > 0) {
      bygstd = byfwhm/sqrt(log(256.0));
      MRImaskedGaussianSmooth(InValsCopy, mritmp, bygstd, InValsCopy);
    }
    MRIwrite(InValsCopy,outpath);
    MRIfree(&InValsCopy);
  }


  // ----------- Compute smoothness -----------------------------
  printf("Computing spatial AR1 in volume.\n");
  ar1 = fMRIspatialAR1(InVals, mask, NULL);
  if (ar1 == NULL) exit(1);
  fMRIspatialAR1Mean(ar1, mask, &car1mn, &rar1mn, &sar1mn);

  cfwhm = RFar1ToFWHM(car1mn, InVals->xsize);
  rfwhm = RFar1ToFWHM(rar1mn, InVals->ysize);
  sfwhm = RFar1ToFWHM(sar1mn, InVals->zsize);
  fwhm = sqrt((cfwhm*cfwhm + rfwhm*rfwhm + sfwhm*sfwhm)/3.0);
  printf("ar1mn = (%lf,%lf,%lf)\n",car1mn,rar1mn,sar1mn);
  printf("colfwhm   = %lf\n",cfwhm);
  printf("rowfwhm   = %lf\n",rfwhm);
  printf("slicefwhm = %lf\n",sfwhm);
  printf("outfwhm = %lf\n",fwhm);

  reselvolume = cfwhm*rfwhm*sfwhm;
  nvoxperresel = reselvolume/voxelvolume;
  nresels = voxelvolume*nsearch/reselvolume;
  printf("reselvolume %lf\n",reselvolume);
  printf("nresels %lf\n",nresels);
  printf("nvoxperresel %lf\n",nvoxperresel);

  if(DoAR2){
    printf("Computing spatial AR2 in volume.\n");
    fMRIspatialAR2Mean(InVals, mask, &car2mn, &rar2mn, &sar2mn);
    printf("ar2mn = (%lf,%lf,%lf)\n",car2mn,rar2mn,sar2mn);
  }

  if(ar1path) MRIwrite(ar1,ar1path);

  fflush(stdout);

  // ---------- Save summary file ---------------------
  if(sumfile) {
    fp = fopen(sumfile,"w");
    if (fp == NULL) {
      printf("ERROR: opening %s\n",sumfile);
      exit(1);
    }
    dump_options(fp);
    fprintf(fp,"nsearch2        %d\n",nsearch2);
    fprintf(fp,"searchspace_vox %d\n",nsearch);
    fprintf(fp,"searchspace_mm3 %lf\n",nsearch*voxelvolume);
    fprintf(fp,"voxelvolume_mm3 %g\n",voxelvolume);
    fprintf(fp,"voxelsize_mm %g %g %g\n",InVals->xsize,InVals->ysize,InVals->zsize);
    fprintf(fp,"ar1mn  %lf %lf %lf\n",car1mn,rar1mn,sar1mn);
    fprintf(fp,"colfwhm_mm      %lf\n",cfwhm);
    fprintf(fp,"rowfwhm_mm      %lf\n",rfwhm);
    fprintf(fp,"slicefwhm_mm    %lf\n",sfwhm);
    fprintf(fp,"outfwhm_mm      %lf\n",fwhm);
    fprintf(fp,"reselvolume_mm3 %lf\n",reselvolume);
    fprintf(fp,"nresels         %lf\n",nresels);
    fprintf(fp,"nvox_per_resel  %lf\n",nvoxperresel);
    fclose(fp);
  }

  if(datfile) {
    fp = fopen(datfile,"w");
    if(fp == NULL) {
      printf("ERROR: opening %s\n",datfile);
      exit(1);
    }
    fprintf(fp,"%lf\n",fwhm);
    fclose(fp);
  }


  printf("mri_fwhm done\n");

  return 0;
}
Exemple #27
0
/*---------------------------------------------------------------*/
int main(int argc, char *argv[]) {
  int nargs, n, err;
  char tmpstr[2000], *signstr=NULL,*SUBJECTS_DIR, fname[2000];
  //char *OutDir = NULL;
  RFS *rfs;
  int nSmoothsPrev, nSmoothsDelta;
  MRI *z, *zabs=NULL, *sig=NULL, *p=NULL;
  int FreeMask = 0;
  int nthSign, nthFWHM, nthThresh;
  double sigmax, zmax, threshadj, csize, csizeavg, searchspace,avgvtxarea;
  int csizen;
  int nClusters, cmax,rmax,smax;
  SURFCLUSTERSUM *SurfClustList;
  struct timeb  mytimer;
  LABEL *clabel;
  FILE *fp, *fpLog=NULL;

  nargs = handle_version_option (argc, argv, vcid, "$Name: stable5 $");
  if (nargs && argc - nargs == 1) exit (0);
  argc -= nargs;
  cmdline = argv2cmdline(argc,argv);
  uname(&uts);
  getcwd(cwd,2000);

  Progname = argv[0] ;
  argc --;
  argv++;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;
  if (argc == 0) usage_exit();
  parse_commandline(argc, argv);
  check_options();
  if (checkoptsonly) return(0);
  dump_options(stdout);

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

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

  SUBJECTS_DIR = getenv("SUBJECTS_DIR");

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

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

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

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

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

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

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

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

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

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

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

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

 finish:

  SaveOutput();

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

  if(DoneFile){
    fp = fopen(DoneFile,"w");
    fprintf(fp,"%g\n",msecTime/(1000*60.0));
    fclose(fp);
  }
  printf("mri_mcsim done\n");
  if(fpLog){
    fprintf(fpLog,"mri_mcsim done\n");
    fclose(fpLog);
  }
  exit(0);
}
Exemple #28
0
int
main(int argc, char *argv[])
{
  char         **av, *in_surf_fname, *out_fname, fname[STRLEN], *cp ;
  int          ac, nargs, msec, err ;
  MRI_SURFACE  *mris ;
  struct timeb then ;
  float        max_dim ;

  char cmdline[CMD_LINE_LEN] ;

  make_cmd_version_string
  (argc, argv,
   "$Id: mris_sphere.c,v 1.57 2011/03/02 00:04:34 nicks Exp $",
   "$Name: stable5 $", cmdline);

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

#ifdef FS_CUDA
  /* print GPU device info */
  MRISCdeviceInfo();
#endif // FS_CUDA

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

  memset(&parms, 0, sizeof(parms)) ;
  parms.dt = .05 ;
  parms.projection = PROJECT_ELLIPSOID ;
  parms.tol = .5 /*1e-1*/ ;
  parms.n_averages = 1024 ;
  parms.min_averages = 0 ;
  parms.l_angle = 0.0 /* L_ANGLE */ ;
  parms.l_area = 0.0 /* L_AREA */ ;
  parms.l_neg = 0.0 ;
  parms.l_dist = 1.0 ;
  parms.l_spring = 0.0 ;
  parms.l_area = 1.0 ;
  parms.l_boundary = 0.0 ;
  parms.l_curv = 0.0 ;
  parms.niterations = 25 ;
  parms.write_iterations = 1000 ;
  parms.a = parms.b = parms.c = 0.0f ;  /* ellipsoid parameters */
  parms.dt_increase = 1.01 /* DT_INCREASE */;
  parms.dt_decrease = 0.99 /* 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.Hdesired = 0.0 ;   /* a flat surface */
  parms.nbhd_size = 7 ;
  parms.max_nbrs = 8 ;

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

  parms.scale = scale ;

  if (argc != 3) // catches args beyond the expected two
  {
    usage_exit() ;
  }

  parms.base_dt = base_dt_scale * parms.dt ;
  in_surf_fname = argv[1] ;
  out_fname = argv[2] ;

  printf("%s\n",vcid);
  printf("  %s\n",MRISurfSrcVersion());
  fflush(stdout);

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

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

  MRISaddCommandLine(mris, cmdline) ;

  fprintf(stderr, "reading original vertex positions...\n") ;
  if (!FZERO(disturb))
  {
    mrisDisturbVertices(mris, disturb) ;
  }
  if (quick == 0)
  {
    // don't need original properties unless preserving metric
    err = MRISreadOriginalProperties(mris, orig_name) ;
    if(err)
    {
      exit(1);
    }
  }
  if (smooth_avgs > 0)
  {
    MRISsaveVertexPositions(mris, TMP_VERTICES) ;
    MRISrestoreVertexPositions(mris, ORIGINAL_VERTICES) ;
    MRISaverageVertexPositions(mris, smooth_avgs) ;
    MRISsaveVertexPositions(mris, ORIGINAL_VERTICES) ;
    MRISrestoreVertexPositions(mris, TMP_VERTICES) ;
  }

  if (!FZERO(ralpha) || !FZERO(rbeta) || !FZERO(rgamma))
  {
    MRISrotate(mris,mris,RADIANS(ralpha),RADIANS(rbeta),RADIANS(rgamma)) ;
    //                if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
    MRISwrite(mris, "rot") ;
  }
  fprintf(stderr, "unfolding cortex into spherical form...\n");
  if (talairach)
  {
    MRIStalairachTransform(mris, mris) ;
    MRISwrite(mris, "tal") ;
  }

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

    lta = LTAread(xform_fname) ;
    if (lta == NULL)
    {
      ErrorExit(ERROR_NOFILE, "%s: could not load %s", xform_fname) ;
    }
    mri = MRIread(vol_fname) ;
    if (mri == NULL)
    {
      ErrorExit(ERROR_NOFILE, "%s: could not load %s", vol_fname) ;
    }
    transform.type = lta->type ;
    transform.xform = (void *)lta ;
    MRIStransform(mris, mri, &transform, mri) ;
    MRIfree(&mri) ;
    LTAfree(&lta) ;
    MRISwrite(mris, "xfm") ;
  }
#if 0
  max_dim = MAX(abs(mris->xlo), abs(mris->xhi)) ;
  max_dim = MAX(abs(max_dim), abs(mris->ylo)) ;
  max_dim = MAX(abs(max_dim), abs(mris->yhi)) ;
  max_dim = MAX(abs(max_dim), abs(mris->zlo)) ;
  max_dim = MAX(abs(max_dim), abs(mris->zhi)) ;
#else
  max_dim = MAX(abs(mris->xhi-mris->xlo), abs(mris->yhi-mris->ylo)) ;
  max_dim = MAX(max_dim,abs(mris->zhi-mris->zlo)) ;
#endif
  if (max_dim > .75*DEFAULT_RADIUS)
  {
    float ratio = .75*DEFAULT_RADIUS / (max_dim) ;
    printf("scaling brain by %2.3f...\n", ratio) ;
    MRISscaleBrain(mris, mris, ratio) ;
  }

  if (target_radius < 0)
  {
    target_radius = sqrt(mris->total_area / (4*M_PI)) ;
    printf("setting target radius to be %2.3f to match surface areas\n",
           target_radius) ;
  }
  //  MRISsampleAtEachDistance(mris, parms.nbhd_size, parms.max_nbrs) ;
  if (!load && inflate)
  {
    INTEGRATION_PARMS inflation_parms ;

    MRIScenter(mris, mris) ;
    memset(&inflation_parms, 0, sizeof(INTEGRATION_PARMS)) ;
    strcpy(inflation_parms.base_name, parms.base_name) ;
    inflation_parms.write_iterations = parms.write_iterations ;
    inflation_parms.niterations = inflate_iterations ;
    inflation_parms.l_spring_norm = l_spring_norm ;
    inflation_parms.l_spring = inflate_spring ;
    inflation_parms.l_nlarea = inflate_nlarea ;
    inflation_parms.l_area = inflate_area ;
    inflation_parms.n_averages = inflate_avgs ;
    inflation_parms.l_expand = l_expand ;
    inflation_parms.l_tspring = inflate_tspring ;
    inflation_parms.l_sphere = l_sphere ;
    inflation_parms.l_convex = l_convex ;
#define SCALE_UP 2
    inflation_parms.a = SCALE_UP*DEFAULT_RADIUS ;
    inflation_parms.tol = inflate_tol ;
    inflation_parms.integration_type = INTEGRATE_MOMENTUM ;
    inflation_parms.momentum = 0.9 ;
    inflation_parms.dt = inflate_dt ;

    /* store the inflated positions in the v->c? field so that they can
      be used in the repulsive term.
    */
    /*    inflation_parms.l_repulse_ratio = .1 ;*/
    MRISsaveVertexPositions(mris, CANONICAL_VERTICES) ;
    if (l_expand > 0)
    {
      MRISexpandSurface(mris, target_radius/2, &inflation_parms, 0, 1) ;
      l_expand = parms.l_expand = 0 ;
    }
    MRIScenter(mris, mris) ;
    mris->x0 = mris->xctr ;
    mris->y0 = mris->yctr ;
    mris->z0 = mris->zctr ;
    MRISinflateToSphere(mris, &inflation_parms) ;
    if (inflation_parms.l_expand > 0)
    {
      inflation_parms.l_expand = 0 ;
      inflation_parms.niterations += (inflate_iterations*.1) ;
      MRISinflateToSphere(mris, &inflation_parms) ;
    }
    MRISscaleBrain(mris, mris, target_radius/(DEFAULT_RADIUS*SCALE_UP)) ;
    parms.start_t = inflation_parms.start_t ;
    MRISresetNeighborhoodSize(mris, nbrs) ;
  }

  if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
  {
    MRISwrite(mris, "before") ;
  }
  MRISprojectOntoSphere(mris, mris, target_radius) ;
  if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
  {
    MRISwrite(mris, "after") ;
  }
  fprintf(stderr,"surface projected - minimizing metric distortion...\n");
  MRISsetNeighborhoodSize(mris, nbrs) ;
  if (quick)
  {
    if (!load)
    {
#if 0
      parms.n_averages = 32 ;
      parms.tol = .1 ;
      parms.l_parea = parms.l_dist = 0.0 ;
      parms.l_nlarea = 1 ;
#endif
      MRISprintTessellationStats(mris, stderr) ;
      MRISquickSphere(mris, &parms, max_passes) ;
    }
  }
  else
  {
    MRISunfold(mris, &parms, max_passes) ;
  }
  if (remove_negative)
  {
    parms.niterations = 1000 ;
    MRISremoveOverlapWithSmoothing(mris,&parms) ;
  }
  if (!load)
  {
    fprintf(stderr, "writing spherical brain to %s\n", out_fname) ;
    MRISwrite(mris, out_fname) ;
  }

  msec = TimerStop(&then) ;
  fprintf(stderr, "spherical transformation took %2.2f hours\n",
          (float)msec/(1000.0f*60.0f*60.0f));
  exit(0) ;
  return(0) ;  /* for ansi */
}
/***-------------------------------------------------------****/
int main(int argc, char *argv[])
{
  int  nargs, ac, nvolumes;
  char **av ;
  MRI  *outmri0 = NULL, *outmri1 = NULL, *outmri2 = NULL, *outmri3 = NULL, *outmri4 = NULL, *segmri ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, vcid, "$Name:  $");
  if (nargs && argc - nargs == 1)
    exit (0);
  Progname = argv[0] ;
  argc -= nargs;
  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++)
  {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  nvolumes = argc-1 ;
  printf("processing %d input files\n", nvolumes) ;
  if (nvolumes != 2)
    usage_exit() ;
  printf("processing %d input files\n", nvolumes) ;

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

  char *fname = argv[1] ;
  printf("processing segmentation input volume %s\n", fname) ;
  segmri = MRIread(fname) ;
  //int width  = segmri->width ;
  //int height = segmri->height ;
  //int depth  = segmri->depth ;

  char *outputfname = argv[2] ;
  printf("output fname %s\n", outputfname) ;

  // GM/WM
  outmri0 = MRIcopy(segmri, NULL) ;
  // MRIwrite(outmri0, "/tmp/segmri.mgz") ;
  correct_gmwm_boundaries(segmri, outmri0);
  // MRIwrite(outmri0, "/tmp/outmri0.mgz") ;
  // putamen / pallidum
  outmri1 = MRIcopy(outmri0, NULL) ;
  correct_putamen_pallidum_boundaries(outmri0, outmri1);
  // MRIwrite(outmri1, "/tmp/outmri1.mgz") ;
  // GM / WM
  outmri2 = MRIcopy(outmri1, NULL) ;
  correct_gmwm_boundaries_2(outmri1, outmri2);
  // MRIwrite(outmri2, "/tmp/outmri2.mgz") ;
  // find largest connected components and close holes 
  outmri3 = MRIcopy(segmri, NULL) ;
  MRIvalueFill(outmri3, 0);
  correct_largestCC_and_fill_holes(outmri2, outmri3);
  // MRIwrite(outmri3, "/tmp/outmri3.mgz") ;
  // fill leftover voxels in origiinal mask
  outmri4 = MRIcopy(outmri3, NULL) ;
  fill_leftover_voxels(segmri, outmri3, outmri4);
  // MRIwrite(outmri4, "/tmp/outmri4.mgz") ;

  //
  outmri0 = MRIcopy(outmri4, NULL) ;
  correct_gmwm_boundaries(outmri4, outmri0);
  // MRIwrite(outmri0, "/tmp/redone-outmri0.mgz") ;
  outmri1 = MRIcopy(outmri0, NULL) ;
  correct_putamen_pallidum_boundaries(outmri0, outmri1);
  // MRIwrite(outmri1, "/tmp/redone-outmri1.mgz") ;
  outmri2 = MRIcopy(outmri1, NULL) ;
  correct_gmwm_boundaries_2(outmri1, outmri2);
  // MRIwrite(outmri2, "/tmp/redone-outmri2.mgz") ;
  //

  printf("writing output to %s\n", outputfname) ;
  MRIwrite(outmri2, outputfname) ;

  MRIfree(&segmri) ;
  MRIfree(&outmri0);
  MRIfree(&outmri1);
  MRIfree(&outmri2);
  MRIfree(&outmri3);
  MRIfree(&outmri4);

  exit(0);

} /* end main() */
Exemple #30
0
/***-------------------------------------------------------****/
int main(int argc, char *argv[])
{
  int  nargs, index, ac, nvolumes;
  char **av ;
  MRI  *mri_or = NULL, *mri ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, vcid, "$Name:  $");
  if (nargs && argc - nargs == 1)
    exit (0);
  Progname = argv[0] ;
  argc -= nargs;
  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++)
  {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  nvolumes = argc-2 ;
  if (nvolumes <= 0)
    usage_exit() ;
  printf("processing %d input files\n", nvolumes) ;

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

  for (index = 0 ; index < nvolumes ; index++)
  {
    char *fname = argv[index+1] ;
    printf("processing input volume %d of %d: %s\n",
           index+1, nvolumes, fname) ;
    mri = MRIread(fname) ;
    if (index == 0){
      mri_or = MRIcopy(mri, NULL) ;
    // if nvolumes == 1 binarize the volume! LZ: MRIbinarize(MRI *mri_src, MRI *mri_dst, float threshold, float low_val,float hi_val)
      if (nvolumes == 1) {
	if(use_orig_value)
	  MRIorVal(mri, mri_or, mri_or, 0) ;
	else
	  MRIor(mri, mri_or, mri_or, 0) ;
      }
    } 
    else {
      if(use_orig_value)
	MRIorVal(mri, mri_or, mri_or, 0) ;
      else
	MRIor(mri, mri_or, mri_or, 0) ;
    }


    MRIfree(&mri) ;
  }

  printf("writing output to %s\n", argv[argc-1]) ;
  MRIwrite(mri_or, argv[argc-1]) ;
  exit(0);

} /* end main() */