示例#1
0
int
main(int argc, char *argv[]) {
  char         **av, *in_fname, *out_fname ;
  int          ac, nargs ;
  MRI_SURFACE  *mris ;
  float        alpha, beta, gamma ;

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

  in_fname = argv[1] ;
  if (sscanf(argv[2], "%f", &alpha) != 1)
    ErrorExit(ERROR_BADPARM, "%s: could not scan alpha from %s",
              Progname, argv[2]) ;
  if (sscanf(argv[3], "%f", &beta) != 1)
    ErrorExit(ERROR_BADPARM, "%s: could not scan beta from %s",
              Progname, argv[3]) ;
  if (sscanf(argv[4], "%f", &gamma) != 1)
    ErrorExit(ERROR_BADPARM, "%s: could not scan gamma from %s",
              Progname, argv[4]) ;
  out_fname = argv[5] ;

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

  alpha = RADIANS(alpha) ;
  beta = RADIANS(beta) ;
  gamma = RADIANS(gamma) ;
  MRIScenter(mris, mris) ;
  MRISrotate(mris, mris, alpha, beta, gamma) ;
  if (!mris)
    ErrorExit(ERROR_NOFILE, "%s: could not rotate surface", Progname) ;

  if (Gdiag & DIAG_SHOW)
    fprintf(stderr, "writing rotated surface to %s\n", out_fname) ;
  MRISwrite(mris, out_fname) ;

  exit(0) ;
  return(0) ;  /* for ansi */
}
示例#2
0
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 */
}
示例#3
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) ;
}
示例#4
0
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) ;
}
示例#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) ;
}
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) ;
}
示例#7
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) ;
}
示例#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() */
示例#9
0
int
main(int argc, char *argv[]) 
{
  MRI_SURFACE  *mris ;
  char         **av, *in_fname, *out_fname ;
  int          ac, nargs ;
  MRI          *mri_distance ;

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

  in_fname = argv[1] ;
  out_fname = argv[2] ;
  mris = MRISread(in_fname) ;
  if (mris == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not load surface %s", Progname, out_fname) ;

  mri_distance = MRIScomputeDistanceMap(mris, NULL, ref_vertex_no) ;

  MRIwrite(mri_distance, out_fname) ;
  MRISfree(&mris) ;

  exit(0) ;

  return(0) ;  /* for ansi */
}
示例#10
0
int
main(int argc, char *argv[]) {
  char         **av, *in_fname, *out_fname ;
  int          ac, nargs ;
  MRI_SURFACE  *mris ;
  float        radius, scale ;

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

  in_fname = argv[1] ;
  out_fname = argv[2] ;

  mris = MRISread(in_fname) ;
  if (!mris)
    ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
              Progname, in_fname) ;
  radius = MRISaverageRadius(mris) ;
  scale = DEFAULT_RADIUS / radius ;
  MRISscaleBrain(mris, mris, scale) ;
  MRISwrite(mris, out_fname) ;

  exit(0) ;
  return(0) ;  /* for ansi */
}
示例#11
0
int
main(int argc, char *argv[]) {
  char          **av, *out_fname, *in_fname ;
  int           ac, nargs ;
  MRI_SURFACE   *mris ;
  MRI           *mri_interior, *mri_template = NULL, *mri_buffer = NULL;

  char cmdline[CMD_LINE_LEN] ;

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

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

  in_fname = argv[1] ;
  out_fname = argv[2] ;

  fprintf(stderr, "reading surface from %s...\n", in_fname) ;
  mris = MRISread(in_fname) ;

  if (template)
示例#12
0
int
main(int argc, char *argv[]) {
  char   **av, fname[STRLEN] ;
  int    ac, nargs, i ;
  char   *in_fname, *out_fname ;
  int          msec, minutes, seconds ;
  struct timeb start ;

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

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

  TimerStart(&start) ;

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

  if (argc < 3)
    usage_exit(1) ;


  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  fprintf(stderr, "inverse operator application 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) ;
}
示例#14
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 */
}
示例#15
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 */
}
示例#16
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) ;
}
示例#17
0
int
main(int argc, char *argv[])
{
  char         **av, *in_fname,fname[STRLEN],hemi[10], path[STRLEN],
               name[STRLEN],*cp ;
  int          ac, nargs, nhandles ;
  MRI_SURFACE  *mris ;
  double       ici, fi, var ;

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

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

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

  if (argc < 2)
  {
    usage_exit() ;
  }

  in_fname = argv[1] ;

  FileNamePath(in_fname, path) ;
  FileNameOnly(in_fname, name) ;
  cp = strchr(name, '.') ;
  if (!cp)
    ErrorExit(ERROR_BADPARM, "%s: could not scan hemisphere from '%s'",
              Progname, fname) ;
  strncpy(hemi, cp-2, 2) ;
  hemi[2] = 0 ;

  if (patch_flag)  /* read the orig surface, then the patch file */
  {
    sprintf(fname, "%s/%s.orig", path, hemi) ;
    mris = MRISfastRead(fname) ;
    if (!mris)
      ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
                Progname, in_fname) ;
    if (Gdiag & DIAG_SHOW)
    {
      fprintf(stderr, "reading patch file %s...\n", in_fname) ;
    }
    if (MRISreadPatch(mris, in_fname) != NO_ERROR)
      ErrorExit(ERROR_NOFILE, "%s: could not read patch file %s",
                Progname, in_fname) ;

  }
  else     /* just read the surface normally */
  {
    mris = MRISread(in_fname) ;
    if (!mris)
      ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
                Progname, in_fname) ;
  }

  MRISsetNeighborhoodSize(mris, nbrs) ;

  if (nbhd_size > 0)
  {
    MRISsampleAtEachDistance(mris, nbhd_size, nbrs_per_distance) ;
  }
  if (max_mm > 0)
  {
    float ratio ;

    MRISstoreMetricProperties(mris) ;
    if (MRISreadCanonicalCoordinates(mris, "sphere") != NO_ERROR)
    {
      ErrorExit(ERROR_NOFILE,
                "%s: could not read canonical coordinates from ?h.sphere",
                Progname);
    }

    MRISsaveVertexPositions(mris, ORIGINAL_VERTICES) ;
    MRISrestoreVertexPositions(mris, CANONICAL_VERTICES) ;
    MRIScomputeMetricProperties(mris) ;
    ratio = mris->orig_area / M_PI * mris->radius * mris->radius * 4.0 ;
    ratio = mris->orig_area / mris->total_area ;
    MRISscaleBrain(mris, mris, sqrt(ratio)) ;
    MRISsaveVertexPositions(mris, CANONICAL_VERTICES) ;
    MRISrestoreVertexPositions(mris, ORIGINAL_VERTICES) ;
    MRIScomputeMetricProperties(mris) ;
    MRIScomputeNeighbors(mris, max_mm) ;
  }

  if (param_file)
  {
    MRI_SP *mrisp ;
    mrisp = MRISPread(param_file) ;
    if (normalize_param)
    {
      MRISnormalizeFromParameterization(mrisp, mris, param_no) ;
    }
    else
    {
      MRISfromParameterization(mrisp, mris, param_no) ;
    }
    MRISPfree(&mrisp) ;
    if (normalize)
    {
      MRISnormalizeCurvature(mris,which_norm) ;
    }
    sprintf(fname, "%s/%s%s.param", path,name,suffix) ;
    fprintf(stderr, "writing parameterized curvature to %s...", fname) ;
    MRISwriteCurvature(mris, fname) ;
    fprintf(stderr, "done.\n") ;
  }
  else
  {
    MRIScomputeSecondFundamentalFormThresholded(mris, cthresh) ;
    nhandles = nint(1.0 - mris->Ktotal / (4.0*M_PI)) ;
    fprintf(stderr, "total integrated curvature = %2.3f*4pi (%2.3f) --> "
            "%d handles\n", (float)(mris->Ktotal/(4.0f*M_PI)),
            (float)mris->Ktotal, nhandles) ;

#if 0
    fprintf(stderr, "0: k1 = %2.3f, k2 = %2.3f, H = %2.3f, K = %2.3f\n",
            mris->vertices[0].k1, mris->vertices[0].k2,
            mris->vertices[0].H, mris->vertices[0].K) ;
    fprintf(stderr, "0: vnum = %d, v2num = %d, total=%d, area=%2.3f\n",
            mris->vertices[0].vnum, mris->vertices[0].v2num,
            mris->vertices[0].vtotal,mris->vertices[0].area) ;
#endif
    MRIScomputeCurvatureIndices(mris, &ici, &fi);
    var = MRIStotalVariation(mris) ;
    fprintf(stderr,"ICI = %2.1f, FI = %2.1f, variation=%2.3f\n", ici, fi, var);

    if (diff_flag)
    {
      MRISuseCurvatureDifference(mris) ;
      MRISaverageCurvatures(mris, navgs) ;
      sprintf(fname, "%s/%s%s.diff", path,name,suffix) ;
      fprintf(stderr, "writing curvature difference to %s...", fname) ;
      MRISwriteCurvature(mris, fname) ;
      fprintf(stderr, "done.\n") ;
    }
    if (ratio_flag)
    {
      MRISuseCurvatureRatio(mris) ;
      MRISaverageCurvatures(mris, navgs) ;
      if (normalize)
      {
        MRISnormalizeCurvature(mris,which_norm) ;
      }
      sprintf(fname, "%s/%s%s.ratio", path,name,suffix) ;
      fprintf(stderr, "writing curvature ratio to %s...", fname) ;
      MRISwriteCurvature(mris, fname) ;
      fprintf(stderr, "done.\n") ;
    }
    if (contrast_flag)
    {
      MRISuseCurvatureContrast(mris) ;
      MRISaverageCurvatures(mris, navgs) ;
      if (normalize)
      {
        MRISnormalizeCurvature(mris,which_norm) ;
      }
      sprintf(fname, "%s/%s%s.contrast", path,name,suffix) ;
      fprintf(stderr, "writing curvature contrast to %s...", fname) ;
      MRISwriteCurvature(mris, fname) ;
      fprintf(stderr, "done.\n") ;
    }
    if (neg_flag)
    {
      int neg ;
      if (mris->patch)
      {
        mris->status = MRIS_PLANE ;
      }
      MRIScomputeMetricProperties(mris) ;
      neg = MRIScountNegativeTriangles(mris) ;
      MRISuseNegCurvature(mris) ;
      MRISaverageCurvatures(mris, navgs) ;
      sprintf(fname, "%s/%s%s.neg", path,name,suffix) ;
      fprintf(stderr, "writing negative vertex curvature to %s...", fname) ;
      MRISwriteCurvature(mris, fname) ;
      fprintf(stderr, "%d negative triangles\n", neg) ;
      fprintf(stderr, "done.\n") ;
      {
        int    vno, fno ;
        VERTEX *v ;
        FACE   *f ;
        for (vno = 0 ; vno < mris->nvertices ; vno++)
        {
          v = &mris->vertices[vno] ;
          if (v->ripflag)
          {
            continue ;
          }
          neg = 0 ;
          for (fno = 0 ; fno < v->num ; fno++)
          {
            f = &mris->faces[v->f[fno]] ;
            if (f->area < 0.0f)
            {
              neg = 1 ;
            }
          }
          if (neg)
          {
            fprintf(stdout, "%d\n", vno) ;
          }
        }
      }
    }

    if (max_flag)
    {
      MRISuseCurvatureMax(mris) ;
      MRISaverageCurvatures(mris, navgs) ;
      if (normalize)
      {
        MRISnormalizeCurvature(mris,which_norm) ;
      }
      sprintf(fname, "%s/%s%s.max", path,name,suffix) ;
      fprintf(stderr, "writing curvature maxima to %s...", fname) ;
      MRISwriteCurvature(mris, fname) ;
      fprintf(stderr, "done.\n") ;
    }

    if (min_flag)
    {
      MRISuseCurvatureMin(mris) ;
      MRISaverageCurvatures(mris, navgs) ;
      if (normalize)
      {
        MRISnormalizeCurvature(mris,which_norm) ;
      }
      sprintf(fname, "%s/%s%s.min", path,name,suffix) ;
      fprintf(stderr, "writing curvature minima to %s...", fname) ;
      MRISwriteCurvature(mris, fname) ;
      fprintf(stderr, "done.\n") ;
    }

    if (stretch_flag)
    {
      MRISreadOriginalProperties(mris, NULL) ;
      MRISuseCurvatureStretch(mris) ;
      MRISaverageCurvatures(mris, navgs) ;
      if (normalize)
      {
        MRISnormalizeCurvature(mris,which_norm) ;
      }
      sprintf(fname, "%s/%s%s.stretch", path,name,suffix) ;
      fprintf(stderr, "writing curvature stretch to %s...", fname) ;
      MRISwriteCurvature(mris, fname) ;
      fprintf(stderr, "done.\n") ;
    }

    if (write_flag)
    {
      MRISuseGaussianCurvature(mris) ;
      if (cthresh > 0)
      {
        MRIShistoThresholdCurvature(mris, cthresh) ;
      }
      MRISaverageCurvatures(mris, navgs) ;
      sprintf(fname, "%s/%s%s.K", path,name, suffix) ;
      fprintf(stderr, "writing Gaussian curvature to %s...", fname) ;
      if (normalize)
      {
        MRISnormalizeCurvature(mris,which_norm) ;
      }
      MRISwriteCurvature(mris, fname) ;
      MRISuseMeanCurvature(mris) ;
      if (cthresh > 0)
      {
        MRIShistoThresholdCurvature(mris, cthresh) ;
      }
      MRISaverageCurvatures(mris, navgs) ;
      if (normalize)
      {
        MRISnormalizeCurvature(mris,which_norm) ;
      }
      sprintf(fname, "%s/%s%s.H", path,name, suffix) ;
      fprintf(stderr, "done.\nwriting mean curvature to %s...", fname) ;
      MRISwriteCurvature(mris, fname) ;
      fprintf(stderr, "done.\n") ;
    }
  }
  exit(0) ;
  return(0) ;  /* for ansi */
}
int
main(int argc, char *argv[])
{
  char          **av, *output_fname ;
  int           ac, nargs, msec, mode=-1 ;
  LABEL         *area = NULL ;
  MRI_SURFACE   *mris ;
  struct timeb  then ;
  MRI           *mri_dist ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option 
    (argc, argv, 
     "$Id: mris_distance_transform.c,v 1.5 2013/04/12 20:59:17 fischl Exp $", 
     "$Name:  $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

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


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

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

  if (vol)
  {
/*
    mri_template = MRIread(argv[2]) ;
    if (!mri_template)
      ErrorExit(ERROR_NOFILE, "%s: could not read MRI volume from %s\n", Progname, argv[2]) ;
*/
  }
  else
  {
    area = LabelRead(NULL, argv[2]) ;
    if (area == NULL)
      ErrorExit(ERROR_NOFILE, "%s: could not read label %s",
		Progname, argv[2]) ;
    
    if (anterior_dist > 0)
      LabelCropAnterior(area, anterior_dist) ;
    if (posterior_dist > 0)
      LabelCropPosterior(area, posterior_dist) ;
  }
  
  if (stricmp(argv[3], "signed") == 0)
    mode = DTRANS_MODE_SIGNED ;
  else if (stricmp(argv[3], "unsigned") == 0)
    mode = DTRANS_MODE_UNSIGNED ;
  else if (stricmp(argv[3], "outside") == 0)
    mode = DTRANS_MODE_OUTSIDE ;
  else
  {
    print_usage() ;
    ErrorExit(ERROR_BADPARM, "unrecognized mode choice %s\n", argv[3]) ;
  }
  output_fname = argv[4] ;

  MRIScomputeMetricProperties(mris) ;
  if (vol)
  {
    mri_dist = MRIScomputeDistanceToSurface(mris, NULL, 0.25) ;
    MRIwrite(mri_dist, argv[4]) ;
  }
  else
  {
    MRIScomputeSecondFundamentalForm(mris) ;
    if (normalize > 0)
    {
      normalize = sqrt(mris->total_area) ;
      printf("normalizing surface distances by sqrt(%2.1f) = %2.1f\n", mris->total_area,normalize) ;
    }
    if (divide > 1)
    {
      int  i ;
      char fname[STRLEN], ext[STRLEN], base_name[STRLEN] ;
      LABEL *area_division ;
      
      FileNameExtension(output_fname, ext) ;
      FileNameRemoveExtension(output_fname, base_name) ;
      LabelMark(area, mris) ;
      MRIScopyMarksToAnnotation(mris) ;
      MRISsaveVertexPositions(mris, TMP_VERTICES) ;
      if (MRISreadVertexPositions(mris, divide_surf_name) != NO_ERROR)
	ErrorExit(ERROR_BADPARM, "%s: could not read vertex coords from %s", Progname, divide_surf_name) ;
      MRIScomputeSecondFundamentalForm(mris) ;
      MRISdivideAnnotationUnit(mris, 1, divide) ;
      MRISrestoreVertexPositions(mris, TMP_VERTICES) ;
      MRIScomputeSecondFundamentalForm(mris) ;
      
      
      // MRISdivideAnnotationUnit sets the marked to be in [0,divide-1], make it [1,divide]
      // make sure they are oriented along original a/p direction
#define MAX_UNITS 100    
      {
	double cx[MAX_UNITS], cy[MAX_UNITS], cz[MAX_UNITS], min_a ;
	int    index, num[MAX_UNITS], new_index[MAX_UNITS], j, min_i ;
	VERTEX *v ;
	
	memset(num, 0, sizeof(num[0])*divide) ;
	memset(cx, 0, sizeof(cx[0])*divide) ;
	memset(cy, 0, sizeof(cy[0])*divide) ;
	memset(cz, 0, sizeof(cz[0])*divide) ;
	for (i = 0 ; i < area->n_points ; i++)
	{
	  if (area->lv[i].vno < 0 || area->lv[i].deleted > 0)
	    continue ;
	  v = &mris->vertices[area->lv[i].vno] ;
	  v->marked++ ;
	  index = v->marked ;
	  cx[index] += v->x ;
	  cy[index] += v->y ;
	  cz[index] += v->z ;
	  num[index]++ ;
	}
	memset(new_index, 0, sizeof(new_index[0])*divide) ;
	for (i = 1 ; i <= divide ; i++)
	  cy[i] /= num[i] ;
	
	// order them from posterior to anterior
	for (j = 1 ; j <= divide ; j++)
	{
	  min_a = 1e10 ; min_i = 0 ;
	  for (i = 1 ; i <= divide ; i++)
	  {
	    if (cy[i] < min_a)
	    {
	      min_a = cy[i] ;
	      min_i = i ;
	    }
	  }
	  cy[min_i] = 1e10 ;  // make it biggest so it won't be considered again
	  new_index[j] = min_i ;
	}
	for (i = 0 ; i < area->n_points ; i++)
	{
	  if (area->lv[i].vno < 0 || area->lv[i].deleted > 0)
	    continue ;
	  v = &mris->vertices[area->lv[i].vno] ;
	  v->marked = new_index[v->marked] ;
	}
      }
      for (i = 1 ; i <= divide ; i++)
      {
	area_division = LabelFromMarkValue(mris, i) ;
	
	printf("performing distance transform on division %d with %d vertices\n", 
	       i, area_division->n_points) ;
	if (output_label)
	{
	  sprintf(fname, "%s%d.label", base_name, i) ;
	  printf("writing %dth subdivision to %s\n", i, fname) ;
	  LabelWrite(area_division, fname);
	}
	MRISdistanceTransform(mris, area_division, mode) ;
	sprintf(fname, "%s%d.%s", base_name, i, ext) ;
	if (normalize > 0)
	  MRISmulVal(mris, 1.0/normalize) ;
	MRISwriteValues(mris, fname) ;
      }
    }
    else
    {
      MRISdistanceTransform(mris, area, mode) ;
      if (normalize > 0)
	MRISmulVal(mris, 1.0/normalize) ;
      MRISwriteValues(mris, output_fname) ;
    }
  }

  msec = TimerStop(&then) ;
  fprintf(stderr,"distance transform took %2.1f minutes\n", (float)msec/(60*1000.0f));

  exit(0) ;
  return(0) ;  /* for ansi */
}
示例#19
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) ;
}
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 */
}
示例#21
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()  */
示例#22
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 */
}
示例#23
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() */
示例#24
0
int
main(int argc, char *argv[]) {
  char         **av, surf_fname[100], *template_fname, *out_fname, *surf_dir,
  *hemi, *sphere_name ;
  int          ac, nargs ;
  MRI_SURFACE  *mris ;
  MRI_SP       *mrisp, *mrisp_template ;

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

  surf_dir = argv[1] ;
  hemi = argv[2] ;
  sphere_name = argv[3] ;
  out_fname = template_fname = argv[4] ;
  if (argc > 5)
    out_fname = argv[5] ;

  sprintf(surf_fname, "%s/%s.%s", surf_dir, hemi, sphere_name) ;
  fprintf(stderr, "reading new surface %s...\n", surf_fname) ;
  mris = MRISread(surf_fname) ;
  if (!mris)
    ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
              Progname, surf_fname) ;
  MRISsaveVertexPositions(mris, ORIGINAL_VERTICES) ;

  if (!FileExists(template_fname))  /* first time - create it */
  {
    fprintf(stderr, "creating new parameterization...\n") ;
    mrisp_template = MRISPalloc(scale, PARAM_IMAGES);
  } else {
    fprintf(stderr, "reading template parameterization from %s...\n",
            template_fname) ;
    mrisp_template = MRISPread(template_fname) ;
    if (!mrisp_template)
      ErrorExit(ERROR_NOFILE, "%s: could not open template file %s",
                Progname, template_fname) ;
  }
  /*
    first read in inflated surface and use it to build the first template
    set.
    */
  sprintf(surf_fname, "%s/%s.%s", surf_dir, hemi, INFLATED_NAME) ;
  if (MRISreadVertexPositions(mris, surf_fname) != NO_ERROR)
    ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
              Progname, surf_fname) ;

  MRISsetNeighborhoodSize(mris, nbrs) ;
  MRIScomputeMetricProperties(mris) ;
  MRIScomputeSecondFundamentalForm(mris) ;
  MRISuseMeanCurvature(mris) ;
  MRISaverageCurvatures(mris, navgs) ;
  MRISrestoreVertexPositions(mris, ORIGINAL_VERTICES) ;
  MRISnormalizeCurvature(mris, which_norm) ;
  fprintf(stderr, "computing parameterization for surface %s...\n",surf_fname);
  mrisp = MRIStoParameterization(mris, NULL, scale, 0) ;
  MRISPcombine(mrisp, mrisp_template, 0) ;
  MRISPfree(&mrisp) ;

  /*
    now do the same thing with the smoothwm curvatures.
    */
  sprintf(surf_fname, "%s/%s.%s", surf_dir, hemi, SMOOTH_NAME) ;
  if (MRISreadVertexPositions(mris, surf_fname) != NO_ERROR)
    ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
              Progname, surf_fname) ;
  MRIScomputeMetricProperties(mris) ;
  if (curvature_fname[0])
    MRISreadCurvatureFile(mris, curvature_fname) ;
  else {
    MRIScomputeSecondFundamentalForm(mris) ;
    MRISuseMeanCurvature(mris) ;
  }
  MRISaverageCurvatures(mris, navgs) ;
  MRISrestoreVertexPositions(mris, ORIGINAL_VERTICES) ;
  if (curvature_fname[0])
    fprintf(stderr, "computing parameterization for surface %s (%s)...\n",
            surf_fname, curvature_fname);
  else
    fprintf(stderr, "computing parameterization for surface %s...\n",
            surf_fname);
  MRISnormalizeCurvature(mris, which_norm) ;
  mrisp = MRIStoParameterization(mris, NULL, scale, 0) ;
  MRISPcombine(mrisp, mrisp_template, 3) ;

  fprintf(stderr, "writing updated template to %s...\n", out_fname) ;
  MRISPwrite(mrisp_template, out_fname) ;

  MRISPfree(&mrisp) ;
  MRISPfree(&mrisp_template) ;
  MRISfree(&mris) ;
  exit(0) ;
  return(0) ;  /* for ansi */
}
示例#25
0
int
main(int argc, char *argv[]) {
  char         **av, in_surf_fname[STRLEN], *in_patch_fname, *out_patch_fname, hemi[STRLEN] ;
  int          ac, nargs;
  char         path[STRLEN], out_surf_fname[STRLEN], *cp ;
  int          msec, minutes, seconds ;
  struct timeb start ;
  MRI_SURFACE  *mris_in, *mris_out ;

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

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

  TimerStart(&start) ;

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

  if (argc < 3)
    usage_exit(1) ;


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

  FileNamePath(out_patch_fname, path) ;
  cp = strrchr(out_patch_fname, '/') ;
  if (!cp)
    cp = out_patch_fname ;
  cp = strchr(cp, '.') ;
  if (cp)
  {
    strncpy(hemi, cp-2, 2) ;
    hemi[2] = 0 ;
  }
  else
    strcpy(hemi, "lh") ;
  sprintf(out_surf_fname, "%s/%s.%s", path, hemi, orig_surf_name) ;

  mris_in = MRISread(in_surf_fname) ;
  mris_out = MRISread(out_surf_fname) ;
  MRISsaveVertexPositions(mris_in, CANONICAL_VERTICES) ;
  MRISsaveVertexPositions(mris_out, CANONICAL_VERTICES) ;
  if (MRISreadVertexPositions(mris_out, inf_surf_name)  != NO_ERROR)
    ErrorExit(ERROR_BADPARM, "%s: could not inflated surface %s",
              Progname, inf_surf_name) ;

  if (MRISreadPatch(mris_in, in_patch_fname) != NO_ERROR)
    ErrorExit(ERROR_BADPARM, "%s: could not read patch file %s",
              Progname, in_patch_fname) ;
  MRISmapCuts(mris_in, mris_out) ;
  if (dilate)
  {
    printf("dilating patch %d times\n", dilate) ;
    MRISdilateRipped(mris_out, dilate) ;
    printf("%d valid vertices (%2.1f %% of total)\n",
           MRISvalidVertices(mris_out), 100.0*MRISvalidVertices(mris_out)/mris_out->nvertices) ;
  }

  printf("writing output to %s\n", out_patch_fname) ;
  MRISwritePatch(mris_out, out_patch_fname) ;
  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  fprintf(stderr, "cut mapping took %d minutes"
          " and %d seconds.\n", minutes, seconds) ;
  exit(0) ;
  return(0) ;
}
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()  */
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) ;
}
/*----------------------------------------------------------------------
  Parameters:

  Description:
  ----------------------------------------------------------------------*/
int
main(int argc, char *argv[]) {
  char   **av, *subject_name, *cp, *hemi,
  *surf_name, *annot_name, fname[STRLEN], *name ;
  int    ac, nargs, msec, minutes, label, seconds, i ;
  double area, total_area ;
  struct timeb start ;
  MRIS   *mris ;
  FILE   *log_fp ;

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

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

  if (strlen(sdir) == 0) {
    cp = getenv("SUBJECTS_DIR") ;
    if (!cp)
      ErrorExit
      (ERROR_BADPARM,
       "%s: SUBJECTS_DIR not defined in env or cmd line",
       Progname) ;
    strcpy(sdir, cp) ;
  }
  sprintf(fname, "%s/%s/surf/%s.%s", sdir, subject_name, hemi, surf_name) ;
  mris = MRISread(fname) ;
  if (!mris)
    ErrorExit
    (ERROR_NOFILE,
     "%s: could not read surface from %s",
     Progname,fname) ;

  MRIScomputeMetricProperties(mris) ;
#if 0
  if (in_label >= 0)
    MRIreplaceValues(mri, mri, in_label, out_label) ;
#endif

  if (compute_pct)
    total_area = mris->total_area ;
  else
    total_area = 1 ;

  if (MRISreadAnnotation(mris, annot_name) != NO_ERROR)
    ErrorExit
    (ERROR_NOFILE,
     "%s: could not read annot file %s",
     Progname, annot_name) ;

  for (i = 5 ; i < argc ; i++) {
    label = atoi(argv[i]) ;
    name = annotation_to_name(index_to_annotation(label), NULL) ;
    printf("processing label %s (%d)...\n", name, label) ;

    area = MRISannotArea(mris, label) ;
    if (log_fname) {
      char fname[STRLEN] ;

      sprintf(fname, log_fname, label) ;
      printf("logging to %s...\n", fname) ;
      log_fp = fopen(fname, "a+") ;
      if (!log_fp)
        ErrorExit(ERROR_BADFILE, "%s: could not open %s for writing",
                  Progname, fname) ;
    } else
      log_fp = NULL ;

    if (compute_pct) {
      printf("%2.3f mm^2 in label %d (%s), "
             "%%%2.6f of total cortical area (%2.2f)\n",
             area, label, name,
             100.0*(float)area/(float)total_area,
             total_area) ;
      if (log_fp) {
        fprintf(log_fp,"%2.6f\n", 100.0*area/(float)total_area) ;
        fclose(log_fp) ;
      }
    } else {
      printf("%2.0f mm^2 in label %s (%d)\n", area, name, label) ;
      if (log_fp) {
        fprintf(log_fp,"%f\n", area) ;
        fclose(log_fp) ;
      }
    }
  }

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

  if (DIAG_VERBOSE_ON)
    printf("area calculation took %d minutes and %d seconds.\n",
           minutes, seconds) ;

  exit(0) ;
  return(0) ;
}
/***-------------------------------------------------------****/
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() */
int
main(int argc, char *argv[]) {
  char         **av, *avg_surf_name, *canon_surf_name, fname[STRLEN],
  *mdir, ico_fname[STRLEN], *hemi, *out_sname ;
  int          ac, nargs, i, vno, n ;
  VERTEX       *v ;
  MRI_SURFACE  *mris_ico ;
  MRI_SP       *mrisp_total ;
  LTA          *lta ;
  VOL_GEOM     vg;
  float        average_surface_area = 0.0 ;
  MATRIX *XFM=NULL;
  GCA_MORPH *gcam=NULL;

  memset((void *) &vg, 0, sizeof (VOL_GEOM));

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

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

  mdir = getenv("FREESURFER_HOME") ;
  if (!mdir)
    ErrorExit(ERROR_BADPARM, 
              "%s: no FREESURFER_HOME in environment.\n",Progname);
  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }
  if (sdir == NULL) {
    sdir =  getenv("SUBJECTS_DIR");
    if (!sdir)
      ErrorExit(ERROR_BADPARM, 
                "%s: no SUBJECTS_DIR in environment.\n",Progname);
  }
  if (sdirout == NULL) sdirout = sdir;
  if (argc < 6) usage_exit() ;

  hemi = argv[1] ;
  avg_surf_name = argv[2] ;
  canon_surf_name = argv[3] ;
  out_sname = argv[4] ;

  printf("---------------------------------------------------\n");
  printf("hemi            = %s\n",hemi);
  printf("avg_surf_name   = %s\n",avg_surf_name);
  printf("canon_surf_name = %s\n",canon_surf_name);
  printf("out_sname       = %s\n",out_sname);
  printf("xform           = %s\n",xform_name);
  printf("---------------------------------------------------\n");
  printf("\n\n");
  fflush(stdout);

#define SCALE 1
  mrisp_total = MRISPalloc(SCALE, 3) ;
  for (n = 0, i = 5 ; i < argc ; i++) {
    MRI *mri;
    MRI_SURFACE *mris;
    MRI_SP *mrisp;

    printf("\n---------------------------------------------------\n");
    printf("#@# processing subject %d/%d %s...\n", i-4,argc-5,argv[i]) ;
    fflush(stdout);

    // read sphere.reg
    sprintf(fname, "%s/%s/surf/%s.%s", sdir, argv[i], hemi, canon_surf_name) ;
    printf("  Reading %s\n",fname);
    fflush(stdout);
    mris = MRISread(fname) ;
    if (!mris) {
      ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
                Progname, fname) ;
      exit(1);
    }
    // get "pial" surface vertex into ->origx, origy, origz
    if (MRISreadOriginalProperties(mris, orig_name) != NO_ERROR)
      ErrorExit(ERROR_BADFILE,"%s: could not read orig file for %s.\n",
                Progname, argv[1]);
    // read transform
    if (0) {
      sprintf(fname, "%s/%s/mri/transforms/%s", sdir, argv[i], xform_name) ;
      lta = LTAreadEx(fname) ;
      if (!lta)
        ErrorExit(ERROR_BADPARM, 
                  "%s: could not read transform from %s", Progname, fname) ;
    }

    // read T1 volume
    sprintf(fname, "%s/%s/mri/T1.mgz", sdir, argv[i]) ;
    if (fio_FileExistsReadable(fname)) mri = MRIreadHeader(fname,MRI_MGH_FILE);
    else {
      sprintf(fname, "%s/%s/mri/T1", sdir, argv[i]) ;
      mri = MRIreadHeader(fname, MRI_UCHAR); // MRI_CORONAL_SLICE_DIRECTORY) ;
    }
    printf("  Read %s\n",fname);
    fflush(stdout);

    if (!mri)
      ErrorExit(ERROR_BADPARM, 
                "%s: could not read reference MRI volume from %s",
                Progname, fname) ;

    // save current vertex position into ->cx
    MRISsaveVertexPositions(mris, CANONICAL_VERTICES) ;
    // get the vertex position from ->origx, ... 
    // (get the "pial" vertex position)
    MRISrestoreVertexPositions(mris, ORIGINAL_VERTICES) ;
    MRIScomputeMetricProperties(mris) ;
    printf("  Surface area: %2.1f cm^2\n", mris->total_area/100) ;
    fflush(stdout);
    average_surface_area += mris->total_area ;

    // this means that we transform "pial" surface

    if (xform_name)
    {
      if (!strcmp(xform_name,"talairach.xfm")) {
        printf("  Applying linear transform\n");
        fflush(stdout);
        XFM = DevolveXFMWithSubjectsDir(argv[i], NULL, "talairach.xfm", sdir);
        if (XFM == NULL) exit(1);
        MRISmatrixMultiply(mris, XFM);
        MatrixFree(&XFM);
      } else if (!strcmp(xform_name,"talairach.m3z")) {
        printf("  Applying GCA Morph\n");
        fflush(stdout);
        sprintf(fname, "%s/%s/mri/transforms/talairach.m3z", sdir, argv[i]) ;
        gcam = GCAMreadAndInvert(fname);
        if (gcam == NULL) exit(1);
        GCAMmorphSurf(mris, gcam);
        GCAMfree(&gcam);
      } else {
        printf("ERROR: don't know what to do with %s\n",xform_name);
        exit(1);
      }
    }

    // save transformed position in ->orig 
    // (store "pial" vertices position in orig)
    MRIScomputeMetricProperties(mris) ;
    MRISsaveVertexPositions(mris, ORIGINAL_VERTICES) ;
    // get the vertex position from ->cx 
    // (note that this is not transformed)  sphere.reg vertices
    MRISrestoreVertexPositions(mris, CANONICAL_VERTICES) ;
    // mris contains sphere.reg in vertex and pial vertices in orig
    // map to a theta-phi space and accumulate values
    mrisp = MRIScoordsToParameterization(mris, NULL, SCALE, ORIGINAL_VERTICES) ;
    MRISPaccumulate(mrisp, mrisp_total, 0) ;
    MRISPaccumulate(mrisp, mrisp_total, 1) ;
    MRISPaccumulate(mrisp, mrisp_total, 2) ;
    MRISPfree(&mrisp) ;
    MRISfree(&mris) ;
    MRIfree(&mri) ;
    //LTAfree(&lta) ;
    fflush(stdout);
    n++ ;
  }
  printf("Finished loading all data\n");
  average_surface_area /= (float)n ;
  printf("Avg surf area = %g cm\n",average_surface_area/100.0);
  fflush(stdout);

  // mrisp_total lost info on the modified surface
  sprintf(ico_fname, "%s/lib/bem/ic%d.tri", mdir, ico_no) ;
  printf("Reading icosahedron from %s...\n", ico_fname) ;
  mris_ico = ICOread(ico_fname) ;
  if (!mris_ico)
    ErrorExit(ERROR_NOFILE, "%s: could not read icosahedron file %s\n",
              Progname,ico_fname) ;
  MRISscaleBrain(mris_ico, mris_ico,
                 DEFAULT_RADIUS/MRISaverageRadius(mris_ico)) ;
  // save current ico position to ->cx, cy, cz
  MRISsaveVertexPositions(mris_ico, CANONICAL_VERTICES) ;
  // using mrisp_total to calculate position into ->origx, origy, origz 
  // (orig is the "pial" vertices)
  MRIScoordsFromParameterization(mrisp_total, mris_ico, ORIGINAL_VERTICES) ;
  // copy geometry info
  memcpy((void *) &mris_ico->vg, (void *) &vg, sizeof (VOL_GEOM));

  if (Gdiag_no >= 0 && Gdiag_no < mris_ico->nvertices) {
    int n ;
    VERTEX *vn ;

    v = &mris_ico->vertices[Gdiag_no] ;
    printf( "v %d: x = (%2.2f, %2.2f, %2.2f)\n",
            Gdiag_no, v->origx, v->origy, v->origz) ;
    for (n = 0 ; n < v->vnum ; n++) {
      vn = &mris_ico->vertices[v->v[n]] ;
      printf( "v %d: x = (%2.2f, %2.2f, %2.2f)\n",
              v->v[n], vn->origx, vn->origy, vn->origz) ;
    }
  }
  // write *h.sphere.reg
  sprintf(fname, "%s/%s/surf/%s.%s", 
          sdirout, out_sname, hemi, canon_surf_name) ;
  if (Gdiag & DIAG_SHOW)
    printf("writing average canonical surface to %s\n", fname);
  MRISwrite(mris_ico, fname) ;

  // get "pial vertices" from orig
  MRISrestoreVertexPositions(mris_ico, ORIG_VERTICES);
  for (vno = 0 ; vno < mris_ico->nvertices ; vno++) {
    v = &mris_ico->vertices[vno] ;
    // n = number of subjects
    v->x /= (float)n ;
    v->y /= (float)n ;
    v->z /= (float)n ;
  }
  if (normalize_area) {
    MRIScomputeMetricProperties(mris_ico) ;
    printf("setting group surface area to be %2.1f cm^2 (scale=%2.2f)\n",
           average_surface_area/100.0,
           sqrt(average_surface_area/mris_ico->total_area)) ;

#if 0
    MRISscaleBrain(mris_ico, mris_ico,
                   sqrt(average_surface_area/mris_ico->total_area)) ;
#else
    mris_ico->group_avg_surface_area = average_surface_area ;
#endif
    MRIScomputeMetricProperties(mris_ico) ;
  }

  sprintf(fname, "%s/%s/surf/%s.%s", sdirout,out_sname, hemi, avg_surf_name) ;
  printf("writing average %s surface to %s\n", avg_surf_name, fname);
  MRISwrite(mris_ico,  fname) ;

  if (0) {
    char path[STRLEN] ;
    LTA  *lta ;

    FileNamePath(fname, path) ;
    lta = LTAalloc(1, NULL) ;
    // write to a different location
    sprintf(fname, "%s/../mri/transforms/%s", path,xform_name) ;
    LTAwriteEx(lta, fname) ;
    LTAfree(&lta) ;
  }

  MRISfree(&mris_ico) ;
  MRISPfree(&mrisp_total) ;

  printf("mris_make_average_surface done\n");

  exit(0) ;
  return(0) ;  /* for ansi */
}