예제 #1
0
int
MRISscaleUp(MRI_SURFACE *mris)
{
  int     vno, n, max_v, max_n ;
  VERTEX  *v ;
  float   ratio, max_ratio ;

  max_ratio = 0.0f ;
  max_v = max_n = 0 ;
  for (vno = 0 ; vno < mris->nvertices ; vno++)
  {
    v = &mris->vertices[vno] ;
    if (v->ripflag)
    {
      continue ;
    }
    if (vno == Gdiag_no)
    {
      DiagBreak() ;
    }
    for (n = 0 ; n < v->vnum ; n++)
    {
      if (FZERO(v->dist[n]))   /* would require infinite scaling */
      {
        continue ;
      }
      ratio = v->dist_orig[n] / v->dist[n] ;
      if (ratio > max_ratio)
      {
        max_v = vno ;
        max_n = n ;
        max_ratio = ratio ;
      }
    }
  }

  fprintf(stderr, "max @ (%d, %d), scaling brain by %2.3f\n",
          max_v, max_n, max_ratio) ;
#if 0
  MRISscaleBrain(mris, mris, max_ratio) ;
#else
  for (vno = 0 ; vno < mris->nvertices ; vno++)
  {
    v = &mris->vertices[vno] ;
    if (v->ripflag)
    {
      continue ;
    }
    if (vno == Gdiag_no)
    {
      DiagBreak() ;
    }
    for (n = 0 ; n < v->vnum ; n++)
    {
      v->dist_orig[n] /= max_ratio ;
    }
  }
#endif
  return(NO_ERROR) ;
}
예제 #2
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 */
}
예제 #3
0
static int
initialize_cluster_centers_with_ico(MRI_SURFACE *mris, MRI *mri_profiles, CLUSTER *ct, MRI_SURFACE *mris_ico) {
  int             i, j, vno, nsamples, vnos[MAX_CLUSTERS], k ;
  double          r1, r2, res ;
  float           fmin ;
  MRIS_HASH_TABLE *mht ;
  VERTEX          *vico ;

  k = mris_ico->nvertices ;
  MRISstoreRipFlags(mris) ;
  MRISunrip(mris) ;
  r1 = MRISaverageRadius(mris) ;
  r2 = MRISaverageRadius(mris_ico) ;
  MRISscaleBrain(mris_ico,mris_ico, r1/r2);

  res = sqrt(mris->total_area/mris->nvertices) ;
  mht = MHTfillVertexTableRes(mris, NULL, CURRENT_VERTICES, 2*res) ;
  nsamples = mri_profiles->nframes ;
  for (i = 0 ; i < mris_ico->nvertices ; i++) {
    vico = &mris_ico->vertices[i] ;
    vno = MRISfindClosestVertex(mris, vico->x, vico->y, vico->z, &fmin) ;
    if (vno < 0)
      continue ;
    vnos[i] = vno ;
    for (j = 0 ; j < nsamples ; j++)
      VECTOR_ELT(ct[i].v_mean, j+1) = MRIgetVoxVal(mri_profiles, vno, 0, 0, j) ;
  }
  mris->ct = CTABalloc(k) ;
  for (i = 0 ; i < k ; i++) {
    mris->vertices[vnos[i]].curv = i ;
    ct[i].npoints++ ;
    ct[i].vno = vnos[i] ;
    CTABannotationAtIndex(mris->ct, i, &mris->vertices[vnos[i]].annotation) ;
  }
  MRISrestoreRipFlags(mris) ;
  return(NO_ERROR) ;
}
예제 #4
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 */
}
예제 #5
0
int
main(int argc, char *argv[])
{
  char         **av, *in_surf_fname, *out_fname, fname[STRLEN], *cp ;
  int          ac, nargs, msec, err ;
  MRI_SURFACE  *mris ;
  struct timeb then ;
  float        max_dim ;

  char cmdline[CMD_LINE_LEN] ;

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

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

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

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

  memset(&parms, 0, sizeof(parms)) ;
  parms.dt = .05 ;
  parms.projection = PROJECT_ELLIPSOID ;
  parms.tol = .5 /*1e-1*/ ;
  parms.n_averages = 1024 ;
  parms.min_averages = 0 ;
  parms.l_angle = 0.0 /* L_ANGLE */ ;
  parms.l_area = 0.0 /* L_AREA */ ;
  parms.l_neg = 0.0 ;
  parms.l_dist = 1.0 ;
  parms.l_spring = 0.0 ;
  parms.l_area = 1.0 ;
  parms.l_boundary = 0.0 ;
  parms.l_curv = 0.0 ;
  parms.niterations = 25 ;
  parms.write_iterations = 1000 ;
  parms.a = parms.b = parms.c = 0.0f ;  /* ellipsoid parameters */
  parms.dt_increase = 1.01 /* DT_INCREASE */;
  parms.dt_decrease = 0.99 /* DT_DECREASE*/ ;
  parms.error_ratio = 1.03 /*ERROR_RATIO */;
  parms.integration_type = INTEGRATE_LINE_MINIMIZE ;
  parms.momentum = 0.9 ;
  parms.desired_rms_height = -1.0 ;
  parms.base_name[0] = 0 ;
  parms.Hdesired = 0.0 ;   /* a flat surface */
  parms.nbhd_size = 7 ;
  parms.max_nbrs = 8 ;

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

  parms.scale = scale ;

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

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

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

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

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

  MRISaddCommandLine(mris, cmdline) ;

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

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

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

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

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

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

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

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

  msec = TimerStop(&then) ;
  fprintf(stderr, "spherical transformation took %2.2f hours\n",
          (float)msec/(1000.0f*60.0f*60.0f));
  exit(0) ;
  return(0) ;  /* for ansi */
}
int
main(int argc, char *argv[]) {
  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 */
}
예제 #7
0
int
main(int argc, char *argv[]) {
  int           nargs, msec, order, i, number, vno, nnum, m, k, b1, b2, cno, flag=0, fno;
  struct timeb  then ;
  MRIS          *mris_in, *mris_out, *mris_high;
  MRI_SP        *mrisp ;
  VERTEX        *vm_out, *vm_high, *v;
  float         s_jkm, area;

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

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

  if (argc < 4)
    ErrorExit(ERROR_BADPARM,
              "usage: %s <input surface> <orig surface> <finest order> <output surface>", Progname);

  TimerStart(&then) ;

  order = atoi (argv[3]);
  fprintf(stdout, "Set %s as the finest scale level\n", argv[3]);
  if (order > 7)
    ErrorExit(ERROR_BADPARM, "the highest order is 7\n");

  /*Spherical Wavelet Analysis*/

  if (ANALYSIS&&!CURV) {
    mris_in = MRISread(argv[1]) ;
    if (!mris_in)
      ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
                Progname, argv[1]) ;
    fprintf(stdout, "Reading input spherical surface from %s\n", argv[1]);
    MRISreadOriginalProperties(mris_in, argv[2]) ;
    fprintf(stdout, "Reading original surface from %s orig area is %f\n", argv[2],mris_in->orig_area);

    mris_out = ReadIcoByOrder(order, 100);
    for (m = 0; m<mris_out->nvertices; m++)
      mris_out->vertices[m].nsize=1;
    mrisp = MRISPalloc(1, 3);
#if 1
    MRIScoordsToParameterization(mris_in, mrisp, 1, ORIGINAL_VERTICES) ;
    MRISPblur(mrisp, mrisp, 1, 0);
    MRISPblur(mrisp, mrisp, 1, 1);
    MRISPblur(mrisp, mrisp, 1, 2);
    MRIScoordsFromParameterization(mrisp, mris_out) ;
#else
    MRISreadOriginalProperties(mris_out, argv[2]) ;
#endif
#if 1 /*just to test if the parameterization is correct */
    MRISsaveVertexPositions(mris_out, TMP_VERTICES) ;
    MRISrestoreVertexPositions(mris_out, ORIGINAL_VERTICES) ;
    MRISupdateSurface(mris_out);
    fprintf(stderr, "original area becomes %f\n", mris_out->total_area);
    center_brain(mris_out, mris_out);
    MRISscaleBrain(mris_out, mris_out, sqrt(100000.0f/mris_out->total_area)) ;
    MRISupdateSurface(mris_out);
    for (fno=0; fno<mris_out->nfaces; fno++)
      area += mris_out->faces[fno].area;
    fprintf(stderr, "original area becomes %f\n", area);
    //MRISwrite(mris_out, "/space/xrt/1/users/btquinn/buckner_paper/010223_61223/surf/lh.sampled") ;
    MRISsaveVertexPositions(mris_out, ORIGINAL_VERTICES) ;
    MRISrestoreVertexPositions(mris_out, TMP_VERTICES) ;
#endif

    /* Initialize Ij,k*/
    for (vno = 0 ; vno<mris_out->nvertices; vno++) {
      vm_out = &mris_out->vertices[vno];
      vm_out->val = 1;
    }

    /*Iteratively compute Ij,k*/
    for (i=order;i>0;i--) {
      mris_high = ReadIcoByOrder(i, 100); //higher order surface
      for (m = 0; m<mris_high->nvertices; m++)
        mris_high->vertices[m].nsize=1;
      MRISsetNeighborhoodSize(mris_high, 3) ;
      number = IcoNVtxsFromOrder(i-1); //the start of m vertices
      for (m = number; m<mris_high->nvertices; m++) {
        vm_out = &mris_out->vertices[m];
        vm_high = &mris_high->vertices[m];
        flag=0;
        for (nnum=0; nnum<vm_high->vnum; nnum++)
          if ( vm_high->v[nnum]<number ) //A(j,m)
          {
            k = vm_high->v[nnum];
            v = &mris_out->vertices[k];
            v->val += 0.5*vm_out->val ;
          }
        for (; nnum<vm_high->v2num; nnum++)
          if ( vm_high->v[nnum]<number ) //B(j,m)
          {
            k = vm_high->v[nnum];
            if (flag==0) b1=k;
            else b2=k;
            flag++;
            v = &mris_out->vertices[k];
            v->val += 0.125*vm_out->val ;
          }
        for (; nnum<vm_high->v3num; nnum++)
          if ( vm_high->v[nnum]<number ) //C(j,m)
          {
            k = vm_high->v[nnum];
            flag=0; //C has to be a second-order neighbor of B
            for (cno=mris_high->vertices[b1].vnum; cno<mris_high->vertices[b1].v2num;cno++)
              if (mris_high->vertices[b1].v[cno]==k) flag=1;
            for (cno=mris_high->vertices[b2].vnum; cno<mris_high->vertices[b2].v2num;cno++)
              if (mris_high->vertices[b2].v[cno]==k) flag=1;
            if (flag) {
              v = &mris_out->vertices[k];
              v->val -= 0.0625*vm_out->val ;
            }
          }
      }
    }


    /*Analysis Stage I:*/
    for (i=order;i>0;i--) {
      mris_high = ReadIcoByOrder(i, 100); //higher order surface
      for (m = 0; m<mris_high->nvertices; m++)
        mris_high->vertices[m].nsize=1;
      MRISsetNeighborhoodSize(mris_high, 3) ;

      number = IcoNVtxsFromOrder(i-1); //the start of m vertices
      /* compute Yj,m for each m vertices */
      for (m = number; m<mris_high->nvertices; m++) {
        vm_out = &mris_out->vertices[m];
        vm_high = &mris_high->vertices[m];
        flag=0;
        for (nnum=0; nnum<vm_high->vnum; nnum++)  //first order neighborhood
          if ( vm_high->v[nnum]<number ) //neighbor A(j,m)
          {
            k = vm_high->v[nnum] ;
            v = &mris_out->vertices[k];
            vm_out->origx -= 0.5*v->origx;
            vm_out->origy -= 0.5*v->origy;
            vm_out->origz -= 0.5*v->origz;
          }
        for (; nnum<vm_high->v2num; nnum++) //second order neighborhood
          if ( vm_high->v[nnum]<number ) //neighbor B(j,m)
          {
            k = vm_high->v[nnum] ;
            if (flag==0) b1=k;
            else b2=k;
            flag++;
            v = &mris_out->vertices[k];
            vm_out->origx -= 0.125*v->origx;
            vm_out->origy -= 0.125*v->origy;
            vm_out->origz -= 0.125*v->origz;
          }
        for (; nnum<vm_high->v3num; nnum++)
          if ( vm_high->v[nnum]<number ) //neighbor C(j,m)
          {
            k = vm_high->v[nnum] ;
            flag=0; //C has to be a second-order neighbor of B
            for (cno=mris_high->vertices[b1].vnum; cno<mris_high->vertices[b1].v2num;cno++)
              if (mris_high->vertices[b1].v[cno]==k) flag=1;
            for (cno=mris_high->vertices[b2].vnum; cno<mris_high->vertices[b2].v2num;cno++)
              if (mris_high->vertices[b2].v[cno]==k) flag=1;
            if (flag) {
              v = &mris_out->vertices[k];
              vm_out->origx += 0.0625*v->origx;
              vm_out->origy += 0.0625*v->origy;
              vm_out->origz += 0.0625*v->origz;
            }
          }
      }


      /*Analysis Stage II: */
      /*Compute Lamda(j,k) using the Yita(j,m)*/
      for (m = number; m<mris_high->nvertices; m++) {
        vm_out = &mris_out->vertices[m];
        vm_high = &mris_high->vertices[m];
        for (nnum=0; nnum<vm_high->vnum; nnum++)
          if ( vm_high->v[nnum]<number ) //A(j,m)
          {
            k = vm_high->v[nnum];
            v = &mris_out->vertices[k];
            s_jkm = vm_out->val/2/v->val;
            v->origx += s_jkm*vm_out->origx;
            v->origy += s_jkm*vm_out->origy;
            v->origz += s_jkm*vm_out->origz;
          }

      }

    }

    MRISsaveVertexPositions(mris_out, TMP_VERTICES) ;
    MRISrestoreVertexPositions(mris_out, ORIGINAL_VERTICES) ;
#if 0
    for (m=0;m<mris_out->nvertices;m++)
      if (mris_out->vertices[m].z>6)
        fprintf(stdout, "%d %f %f %f\n", m,mris_out->vertices[m].x, mris_out->vertices[m].y, mris_out->vertices[m].z);
    //mris_high = ReadIcoByOrder(0, 100);
    //for (m=0;m<mris_high->nvertices;m++)
    //{mris_high->vertices[m].x=mris_out->vertices[m].x;
    //mris_high->vertices[m].y=mris_out->vertices[m].y;
    //mris_high->vertices[m].z=mris_out->vertices[m].z;
    //}
    //MRISwrite(mris_high, "/space/xrt/1/users/btquinn/buckner_paper/010223_61223/surf/lh.sampled") ;
#endif
    fprintf(stdout, "Writing wavelets coefficient of original surface to %s\n", argv[4]);
    MRISwrite(mris_out,argv[4] ) ;
    MRISrestoreVertexPositions(mris_out, TMP_VERTICES) ;
    MRISPfree(&mrisp) ;
    MRISfree(&mris_in) ;
    /*End of Analysis*/
  } else if (ANALYSIS&&CURV) {
    mris_in = MRISread(argv[1]) ;
    if (!mris_in)
      ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
                Progname, argv[1]) ;
    fprintf(stdout, "Reading input spherical surface from %s\n", argv[1]);

    MRISreadCurvatureFile(mris_in, argv[2]) ;
    fprintf(stdout, "Reading input from %s\n", argv[2]);

    mris_out = ReadIcoByOrder(order, 100);
    for (m = 0; m<mris_out->nvertices; m++)
      mris_out->vertices[m].nsize=1;
    //mrisp = MRISPalloc(1, 3);
    mrisp = MRIStoParameterization(mris_in, NULL, 1, 0) ;
    //MRISPblur(mrisp, mrisp, 1, 0);
    MRISfromParameterization(mrisp, mris_out, 0) ;
    //MRISwriteCurvature(mris_out,"/space/xrt/1/users/btquinn/buckner_paper/010223_61223/surf/lh.thickness.sampled");
    /* Initialize Ij,k*/
    for (vno = 0 ; vno<mris_out->nvertices; vno++) {
      vm_out = &mris_out->vertices[vno];
      vm_out->val = 1;
    }

    /*Iteratively compute Ij,k*/
    for (i=order;i>0;i--) {
      mris_high = ReadIcoByOrder(i, 100); //higher order surface
      for (m = 0; m<mris_high->nvertices; m++)
        mris_high->vertices[m].nsize=1;
      MRISsetNeighborhoodSize(mris_high, 3) ;
      number = IcoNVtxsFromOrder(i-1); //the start of m vertices
      for (m = number; m<mris_high->nvertices; m++) {
        vm_out = &mris_out->vertices[m];
        vm_high = &mris_high->vertices[m];
        flag=0;
        for (nnum=0; nnum<vm_high->vnum; nnum++)
          if ( vm_high->v[nnum]<number ) //A(j,m)
          {
            k = vm_high->v[nnum];
            v = &mris_out->vertices[k];
            v->val += 0.5*vm_out->val ;
          }
        for (; nnum<vm_high->v2num; nnum++)
          if ( vm_high->v[nnum]<number ) //B(j,m)
          {
            k = vm_high->v[nnum];
            if (flag==0) b1=k;
            else b2=k;
            flag++;
            v = &mris_out->vertices[k];
            v->val += 0.125*vm_out->val ;
          }
        for (; nnum<vm_high->v3num; nnum++)
          if ( vm_high->v[nnum]<number ) //C(j,m)
          {
            k = vm_high->v[nnum];
            flag=0; //C has to be a second-order neighbor of B
            for (cno=mris_high->vertices[b1].vnum; cno<mris_high->vertices[b1].v2num;cno++)
              if (mris_high->vertices[b1].v[cno]==k) flag=1;
            for (cno=mris_high->vertices[b2].vnum; cno<mris_high->vertices[b2].v2num;cno++)
              if (mris_high->vertices[b2].v[cno]==k) flag=1;
            if (flag) {
              v = &mris_out->vertices[k];
              v->val -= 0.0625*vm_out->val ;
            }
          }
      }
    }


    /*Analysis Stage I:*/
    for (i=order;i>0;i--) {
      mris_high = ReadIcoByOrder(i, 100); //higher order surface
      for (m = 0; m<mris_high->nvertices; m++)
        mris_high->vertices[m].nsize=1;
      MRISsetNeighborhoodSize(mris_high, 3) ;

      number = IcoNVtxsFromOrder(i-1); //the start of m vertices
      /* compute Yj,m for each m vertices */
      for (m = number; m<mris_high->nvertices; m++) {
        vm_out = &mris_out->vertices[m];
        vm_high = &mris_high->vertices[m];
        flag=0;
        for (nnum=0; nnum<vm_high->vnum; nnum++)  //first order neighborhood
          if ( vm_high->v[nnum]<number ) //neighbor A(j,m)
          {
            k = vm_high->v[nnum] ;
            v = &mris_out->vertices[k];
            vm_out->curv -= 0.5*v->curv;
          }
        for (; nnum<vm_high->v2num; nnum++) //second order neighborhood
          if ( vm_high->v[nnum]<number ) //neighbor B(j,m)
          {
            k = vm_high->v[nnum] ;
            if (flag==0) b1=k;
            else b2=k;
            flag++;
            v = &mris_out->vertices[k];
            vm_out->curv -= 0.125*v->curv;
          }
        for (; nnum<vm_high->v3num; nnum++)
          if ( vm_high->v[nnum]<number ) //neighbor C(j,m)
          {
            k = vm_high->v[nnum] ;
            flag=0; //C has to be a second-order neighbor of B
            for (cno=mris_high->vertices[b1].vnum; cno<mris_high->vertices[b1].v2num;cno++)
              if (mris_high->vertices[b1].v[cno]==k) flag=1;
            for (cno=mris_high->vertices[b2].vnum; cno<mris_high->vertices[b2].v2num;cno++)
              if (mris_high->vertices[b2].v[cno]==k) flag=1;
            if (flag) {
              v = &mris_out->vertices[k];
              vm_out->curv += 0.0625*v->curv;
            }
          }
      }


      /*Analysis Stage II: */
      /*Compute Lamda(j,k) using the Yita(j,m)*/
      for (m = number; m<mris_high->nvertices; m++) {
        vm_out = &mris_out->vertices[m];
        vm_high = &mris_high->vertices[m];
        for (nnum=0; nnum<vm_high->vnum; nnum++)
          if ( vm_high->v[nnum]<number ) //A(j,m)
          {
            k = vm_high->v[nnum];
            v = &mris_out->vertices[k];
            s_jkm = vm_out->val/2/v->val;
            v->curv += s_jkm*vm_out->curv;
          }

      }
    }

    fprintf(stdout, "Writing wavelets coefficient of original surface to %s\n", argv[4]);
    MRISwriteCurvature(mris_out,argv[4] ) ;
    MRISPfree(&mrisp) ;
    MRISfree(&mris_in) ;
    /*End of Analysis*/
  } else if (SYNTHESIS) /*Spherical Wavelet Synthesis*/
  {
    mris_out = ReadIcoByOrder(order, 100); //higher order surface
    fprintf(stdout, "Creating a %d order spherical surface\n", order);
    MRISreadOriginalProperties(mris_out, argv[1]) ;
    fprintf(stdout, "Reading wavelet coefficients from %s\n", argv[1]);
    for (m = 0; m<mris_out->nvertices; m++)
      mris_out->vertices[m].nsize=1;
    MRISsetNeighborhoodSize(mris_out, 3) ;

    if (COMPARE) {
      mris_in = MRISread(fname);
      for (i=1; i<IcoNVtxsFromOrder(order-1); i++) {
        if (mris_out->vertices[i].origx==0)
          area =  fabs(mris_out->vertices[i].origx-mris_in->vertices[i].x);
        else area = fabs((mris_out->vertices[i].origx-mris_in->vertices[i].x)/mris_out->vertices[i].origx);
        if ( area>5 ) {
          mris_out->vertices[i].origx = mris_in->vertices[i].x ;
          fprintf(stdout, "%d %f\n", i, area);
        }
        if (mris_out->vertices[i].origy==0)
          area =  fabs(mris_out->vertices[i].origy-mris_in->vertices[i].y);
        else area = fabs((mris_out->vertices[i].origy-mris_in->vertices[i].y)/mris_out->vertices[i].origy);
        if ( area>5 ) {
          mris_out->vertices[i].origy = mris_in->vertices[i].y ;
          fprintf(stdout, "%d %f\n", i, area);
        }
        if (mris_out->vertices[i].origz==0)
          area =  fabs(mris_out->vertices[i].origz-mris_in->vertices[i].z);
        else area = fabs((mris_out->vertices[i].origz-mris_in->vertices[i].z)/mris_out->vertices[i].origz);
        if ( area>5 ) {
          mris_out->vertices[i].origz = mris_in->vertices[i].z ;
          fprintf(stdout, "%d %f\n", i, area);
        }
      }
      MRISfree(&mris_in);
    }

    fprintf(stdout, "Recover the surface using %s order coefficients\n",argv[2]);
    number = IcoNVtxsFromOrder(atoi(argv[2]));
    for (m = number; m<mris_out->nvertices; m++) {
      mris_out->vertices[m].origx = 0;
      mris_out->vertices[m].origy = 0;
      mris_out->vertices[m].origz = 0;
    }

    /*Initialize Ij,k*/
    for (vno = 0; vno<mris_out->nvertices; vno++) {
      vm_out = &mris_out->vertices[vno];
      vm_out->val = 1;
    }

    /*Iteratively compute Ij,k*/
    for (i=order;i>0;i--) {
      mris_high = ReadIcoByOrder(i, 100); //higher order surface
      for (m = 0; m<mris_high->nvertices; m++)
        mris_high->vertices[m].nsize=1;
      MRISsetNeighborhoodSize(mris_high, 3) ;
      number = IcoNVtxsFromOrder(i-1); //the start of m vertices
      for (m = number; m<mris_high->nvertices; m++) {
        vm_out = &mris_out->vertices[m];
        vm_high = &mris_high->vertices[m];
        flag=0;
        for (nnum=0; nnum<vm_high->vnum; nnum++)
          if ( vm_high->v[nnum]<number ) //A(j,m)
          {
            k = vm_high->v[nnum];
            v = &mris_out->vertices[k];
            v->val += 0.5*vm_out->val ;
          }
        for (; nnum<vm_high->v2num; nnum++)
          if ( vm_high->v[nnum]<number ) //B(j,m)
          {
            k = vm_high->v[nnum];
            if (flag==0) b1=k;
            else b2=k;
            flag++;
            v = &mris_out->vertices[k];
            v->val += 0.125*vm_out->val ;
          }
        for (; nnum<vm_high->v3num; nnum++)
          if ( vm_high->v[nnum]<number ) //C(j,m)
          {
            k = vm_high->v[nnum];
            flag=0; //C has to be a second-order neighbor of B
            for (cno=mris_high->vertices[b1].vnum; cno<mris_high->vertices[b1].v2num;cno++)
              if (mris_high->vertices[b1].v[cno]==k) flag=1;
            for (cno=mris_high->vertices[b2].vnum; cno<mris_high->vertices[b2].v2num;cno++)
              if (mris_high->vertices[b2].v[cno]==k) flag=1;
            if (flag) {
              v = &mris_out->vertices[k];
              v->val -= 0.0625*vm_out->val ;
            }
          }
      }
    }


    for (i=1;i<=order;i++) {
      mris_high = ReadIcoByOrder(i, 100); //higher order surface
      for (m = 0; m<mris_high->nvertices; m++)
        mris_high->vertices[m].nsize=1;
      MRISsetNeighborhoodSize(mris_high, 3) ;
      number = IcoNVtxsFromOrder(i-1); //the start of m vertices

      /* Synthesis Stage I */
      /* Compute Lamda(j+1,k) using the Yita(j,m) */
      for (m = number; m<mris_high->nvertices; m++) {
        vm_out = &mris_out->vertices[m];
        vm_high = &mris_high->vertices[m];
        for (nnum=0; nnum<vm_high->vnum; nnum++)
          if ( vm_high->v[nnum]<number ) //A(j,m)
          {
            k = vm_high->v[nnum];
            v = &mris_out->vertices[k];
            s_jkm = vm_out->val/2/v->val;
            v->origx -= s_jkm*vm_out->origx;
            v->origy -= s_jkm*vm_out->origy;
            v->origz -= s_jkm*vm_out->origz;
          }
      }

      /* compute Lamda(j+1,m) for each m vertices */
      for (m = number; m<mris_high->nvertices; m++) {
        vm_out = &mris_out->vertices[m];
        vm_high = &mris_high->vertices[m];
        flag=0;
        for (nnum=0; nnum<vm_high->vnum; nnum++)  //first order neighborhood
          if ( vm_high->v[nnum]<number ) //neighbor A(j,m)
          {
            k = vm_high->v[nnum] ;
            v = &mris_out->vertices[k];
            vm_out->origx += 0.5*v->origx;
            vm_out->origy += 0.5*v->origy;
            vm_out->origz += 0.5*v->origz;
          }
        for (; nnum<vm_high->v2num; nnum++) //second order neighborhood
          if ( vm_high->v[nnum]<number ) //neighbor B(j,m)
          {
            k = vm_high->v[nnum] ;
            if (flag==0) b1=k;
            else b2=k;
            flag++;
            v = &mris_out->vertices[k];
            vm_out->origx += 0.125*v->origx;
            vm_out->origy += 0.125*v->origy;
            vm_out->origz += 0.125*v->origz;
          }
        for (; nnum<vm_high->v3num; nnum++) //third order neighborhood
          if ( vm_high->v[nnum]<number ) //neighbor C(j,m)
          {
            k = vm_high->v[nnum] ;
            flag=0; //C has to be a second-order neighbor of B
            for (cno=mris_high->vertices[b1].vnum; cno<mris_high->vertices[b1].v2num;cno++)
              if (mris_high->vertices[b1].v[cno]==k) flag=1;
            for (cno=mris_high->vertices[b2].vnum; cno<mris_high->vertices[b2].v2num;cno++)
              if (mris_high->vertices[b2].v[cno]==k) flag=1;
            if (flag) {
              v = &mris_out->vertices[k];
              vm_out->origx -= 0.0625*v->origx;
              vm_out->origy -= 0.0625*v->origy;
              vm_out->origz -= 0.0625*v->origz;
            }
          }
      }
    }

    MRISsaveVertexPositions(mris_out, TMP_VERTICES) ;
    MRISrestoreVertexPositions(mris_out, ORIGINAL_VERTICES) ;
    fprintf(stdout, "Writing recovered surface to %s\n", argv[4]);
    MRISwrite(mris_out, argv[4]) ;
#if 0
    mris_high = ReadIcoByOrder(4, 100);
    for (m=0;m<mris_high->nvertices;m++) {
      mris_high->vertices[m].x=mris_out->vertices[m].x;
      mris_high->vertices[m].y=mris_out->vertices[m].y;
      mris_high->vertices[m].z=mris_out->vertices[m].z;
    }
    MRISwrite(mris_high, "/space/xrt/1/users/btquinn/buckner_paper/010223_61223/surf/lh.wavelet.recon") ;
#endif
    MRISrestoreVertexPositions(mris_out, TMP_VERTICES) ;
    /*End of Synthesis*/
  }

  MRISfree(&mris_out);
  MRISfree(&mris_high) ;
  msec = TimerStop(&then) ;
  fprintf(stdout, "spherical wavelet took %2.1f minutes\n", (float)msec/(1000.0f*60.0f));
  exit(0) ;
  return(0) ;
}
예제 #8
0
int
main(int argc, char *argv[])
{
  char         **av, in_surf_fname[STRLEN], *in_patch_fname, *out_patch_fname,
  fname[STRLEN], path[STRLEN], *cp, hemi[10] ;
  int          ac, nargs ;
  MRI_SURFACE  *mris ;
  MRI          *mri_vertices ;

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

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

  if (argc < 3)
    print_help() ;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  exit(0) ;
  return(0) ;  /* for ansi */
}
예제 #9
0
static int
MRISrepositionToInnerSkull(MRI_SURFACE *mris, MRI *mri_smooth, INTEGRATION_PARMS *parms) {
  MRI   *mri_dist, *mri_bin, *mri_kernel, *mri_bin_smooth, *mri_dist_smooth ;
  float l_spring, sigma ;
  int   i, ic_order, avgs ;

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

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

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

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

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

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


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

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

  MRIfree(&mri_bin) ;
  MRIfree(&mri_dist) ;
  return(NO_ERROR) ;
}