static int
mrisFindMiddleOfGray(MRI_SURFACE *mris) {
  int     vno ;
  VERTEX  *v ;
  float   nx, ny, nz, thickness ;

  MRISaverageCurvatures(mris, 3) ;
  MRISsaveVertexPositions(mris, TMP_VERTICES) ;
  MRISrestoreVertexPositions(mris, ORIGINAL_VERTICES) ;
  MRIScomputeMetricProperties(mris);  /* compute orig surface normals */
  for (vno = 0 ; vno < mris->nvertices ; vno++) {
    v = &mris->vertices[vno] ;
    if (v->ripflag)
      continue ;
    nx = v->nx ;
    ny = v->ny ;
    nz = v->nz ;
    thickness = 0.5 * v->curv ;
    v->origx = v->origx + thickness * nx ;
    v->origy = v->origy + thickness * ny ;
    v->origz = v->origz + thickness * nz ;
  }
  MRISrestoreVertexPositions(mris, TMP_VERTICES) ;
  MRIScomputeMetricProperties(mris);
  return(NO_ERROR) ;
}
Exemplo n.º 2
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) ;
}
Exemplo n.º 3
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) ;
}
Exemplo n.º 4
0
int
main(int argc, char *argv[])
{
  char         **av, surf_fname[STRLEN], *template_fname, *hemi, *sphere_name,
  *cp, *subject, fname[STRLEN] ;
  int          ac, nargs, ino, sno, nbad = 0, failed, n,nfields;
  VERTEX *v;
  VALS_VP *vp;
  MRI_SURFACE  *mris ;
  MRI_SP       *mrisp, /* *mrisp_aligned,*/ *mrisp_template ;
  INTEGRATION_PARMS parms ;

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

  memset(&parms, 0, sizeof(parms)) ;
  Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;
  /* setting default values for vectorial registration */
  setParms(&parms);

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

  if (argc < 5) usage_exit() ;

  /* multiframe registration */
  if (multiframes) parms.flags |= IP_USE_MULTIFRAMES;

  if (!strlen(subjects_dir))  /* not specified on command line*/
  {
    cp = getenv("SUBJECTS_DIR") ;
    if (!cp)
      ErrorExit(ERROR_BADPARM,
                "%s: SUBJECTS_DIR not defined in environment.\n",
                Progname) ;
    strcpy(subjects_dir, cp) ;
  }
  hemi = argv[1] ;
  sphere_name = argv[2] ;
  template_fname = argv[argc-1] ;
  if (1 || !FileExists(template_fname))  /* first time - create it */
  {
    fprintf(stderr, "creating new parameterization...\n") ;
    if (multiframes)
    {
      mrisp_template = MRISPalloc(scale, atlas_size * IMAGES_PER_SURFACE );
      /*    if (no_rot)  /\* don't do rigid alignment *\/ */
      /*     mrisp_aligned = NULL ; */
      /*    else */
      /*     mrisp_aligned = MRISPalloc(scale, PARAM_FRAMES);  */
    }
    else
    {
      mrisp_template = MRISPalloc(scale, PARAM_IMAGES);
      /*    if (no_rot)  /\* don't do rigid alignment *\/ */
      /*     mrisp_aligned = NULL ; */
      /*    else */
      /*     mrisp_aligned = MRISPalloc(scale, PARAM_IMAGES);  */
    }

  }
  else
  {
    fprintf(stderr, "reading template parameterization from %s...\n",
            template_fname) ;
    /* mrisp_aligned = NULL ; */
    mrisp_template = MRISPread(template_fname) ;
    if (!mrisp_template)
      ErrorExit(ERROR_NOFILE, "%s: could not open template file %s",
                Progname, template_fname) ;
  }

  argv += 3 ;
  argc -= 3 ;
  for (ino = 0 ; ino < argc-1 ; ino++)
  {
    failed = 0 ;
    subject = argv[ino] ;
    fprintf(stderr, "\nprocessing subject %s (%d of %d)\n", subject,
            ino+1, argc-1) ;
    sprintf(surf_fname, "%s/%s/surf/%s.%s",
            subjects_dir, subject, hemi, sphere_name) ;
    fprintf(stderr, "reading spherical surface %s...\n", surf_fname) ;
    mris = MRISread(surf_fname) ;
    if (!mris)
    {
      nbad++ ;
      ErrorPrintf(ERROR_NOFILE, "%s: could not read surface file %s",
                  Progname, surf_fname) ;
      exit(1) ;
    }
    if (annot_name)
    {
      if (MRISreadAnnotation(mris, annot_name) != NO_ERROR)
        ErrorExit(ERROR_BADPARM,
                  "%s: could not read annot file %s",
                  Progname, annot_name) ;
      MRISripMedialWall(mris) ;
    }

    MRISsaveVertexPositions(mris, CANONICAL_VERTICES) ;
    MRIScomputeMetricProperties(mris) ;
    MRISstoreMetricProperties(mris) ;

    if (Gdiag & DIAG_WRITE)
    {
      char *cp1 ;

      FileNameOnly(template_fname, fname) ;
      cp = strchr(fname, '.') ;
      if (cp)
      {
        cp1 = strrchr(fname, '.') ;
        if (cp1 && cp1 != cp)
          strncpy(parms.base_name, cp+1, cp1-cp-1) ;
        else
          strcpy(parms.base_name, cp+1) ;
      }
      else
        strcpy(parms.base_name, "template") ;
      sprintf(fname, "%s.%s.out", hemi, parms.base_name);
      parms.fp = fopen(fname, "w") ;
      printf("writing output to '%s'\n", fname) ;
    }

    /* multiframe registration */
    if (multiframes)
    {
      nfields=parms.nfields;

      for ( n = 0; n < mris->nvertices ; n++) /* allocate the VALS_VP
                                                                 structure */
      {
        v=&mris->vertices[n];
        vp=calloc(1,sizeof(VALS_VP));
        vp->nvals=nfields;
        vp->orig_vals=(float*)malloc(nfields*sizeof(float)); /* before
                                                                blurring */
        vp->vals=(float*)malloc(nfields*sizeof(float));     /* values used by
                                                               MRISintegrate */
        v->vp=(void*)vp;
      }

      /* load the different fields */
      for (n = 0 ; n < parms.nfields ; n++)
      {
        if (parms.fields[n].name != NULL)
        {
          sprintf(surf_fname, "%s/%s/%s/%s.%s", subjects_dir,
                  subject, overlay_dir, hemi, parms.fields[n].name) ;
          printf("reading overlay file %s...\n", surf_fname) ;
          if (MRISreadValues(mris, surf_fname) != NO_ERROR)
            ErrorExit(ERROR_BADPARM, "%s: could not read overlay file %s",
                      Progname, surf_fname) ;
          MRIScopyValuesToCurvature(mris) ;
        }
        else if (ReturnFieldName(parms.fields[n].field))
        {
          /* read in precomputed curvature file */
          sprintf(surf_fname, "%s/%s/surf/%s.%s", subjects_dir,
                  subject, hemi, ReturnFieldName(parms.fields[n].field)) ;
          // fprintf(stderr,"\nreading field %d from %s(type=%d,frame=%d)\n",parms.fields[n].field,surf_fname,parms.fields[n].type,parms.fields[n].frame);
          if (MRISreadCurvatureFile(mris, surf_fname) != NO_ERROR)
          {
            fprintf(stderr,"\n\nXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n");
            fprintf(stderr, "%s: could not read curvature file '%s'\n",
                    Progname, surf_fname) ;
            failed = 1;
            break;
          }
        }
        else
        {                       /* compute curvature of surface */
          sprintf(surf_fname, "%s/%s/surf/%s.%s", subjects_dir,
                  subject, hemi, surface_names[parms.fields[n].field]) ;
          /*if(parms.fields[n].field==0)
           sprintf(fname, "inflated") ;
           else
           sprintf(fname, "smoothwm") ;*/
          //fprintf(stderr,"\ngenerating field %d(type=%d,frame=%d) (from %s)\n",parms.fields[n].field,parms.fields[n].type,parms.fields[n].frame,surf_fname);
          //     MRISsaveVertexPositions(mris, TMP_VERTICES) ;
          if (MRISreadVertexPositions(mris, surf_fname) != NO_ERROR)
          {
            fprintf(stderr,"\n\nXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n");
            ErrorPrintf(ERROR_NOFILE, "%s: could not read surface file %s",
                        Progname, surf_fname) ;
            fprintf(stderr,"setting up correlation coefficient to zero\n");
            parms.fields[n].l_corr=parms.fields[n].l_pcorr=0.0;
            failed=1;
            break;
          }

          if (nbrs > 1) MRISsetNeighborhoodSize(mris, nbrs) ;
          MRIScomputeMetricProperties(mris) ;
          MRIScomputeSecondFundamentalForm(mris) ;
          MRISuseMeanCurvature(mris) ;
          MRISaverageCurvatures(mris, navgs) ;
          MRISrestoreVertexPositions(mris, CANONICAL_VERTICES) ;
        }
        /*    if(parms.fields[n].field!=SULC_CORR_FRAME)*/
        MRISnormalizeField(mris,parms.fields[n].type,
                           parms.fields[n].which_norm); /* normalize values */
        MRISsetCurvaturesToOrigValues(mris,n);
        MRISsetCurvaturesToValues(mris,n);
      }

      if (failed)
      {
        fprintf(stderr,"\n\nXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n");
        fprintf(stderr,"Subject %s Failed",subject);
        fprintf(stderr,"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n\n");
        /* free cal structure*/
        for ( n = 0; n < mris->nvertices ; n++)
        {
          v=&mris->vertices[n];
          vp=(VALS_VP*)v->vp;
          free(vp->orig_vals);
          free(vp->vals);
          free(vp);
          v->vp=NULL;
        }
        /* free surface */
        MRISfree(&mris);
        /* go onto the next subject */
        continue;
      }
    }

    if (multiframes && (!no_rot))
    { /* rigid body alignment */
      parms.frame_no = 3 ;  /* don't use single field correlation functions */
      parms.l_corr = parms.l_pcorr = 0.0f ;

      parms.mrisp = MRIStoParameterization(mris, NULL, scale, 0) ;
      parms.mrisp_template = mrisp_template ;

      MRISrigidBodyAlignVectorGlobal(mris, &parms, 1.0, 64.0, 8) ;
      if (Gdiag & DIAG_WRITE) MRISwrite(mris, "sphere.rot.global") ;
      MRISrigidBodyAlignVectorLocal(mris, &parms) ;
      if (Gdiag & DIAG_WRITE) MRISwrite(mris, "sphere.rot.local") ;
      MRISPfree(&parms.mrisp) ;
      MRISsaveVertexPositions(mris, CANONICAL_VERTICES) ;
    };
    if ((!multiframes) && (!no_rot) && ino > 0)
    { /* rigid body alignment */
      sprintf(surf_fname, "%s/%s/surf/%s.%s",
              subjects_dir, subject, hemi, "sulc") ;
      if (MRISreadCurvatureFile(mris, surf_fname) != NO_ERROR)
      {
        ErrorPrintf(Gerror, "%s: could not read curvature file '%s'\n",
                    Progname, surf_fname) ;
        nbad++ ;
        MRISfree(&mris) ;
        continue ;
      }
      parms.frame_no = 3 ; /* use sulc for rigid registration */
      parms.mrisp = MRIStoParameterization(mris, NULL, scale, 0) ;
      parms.mrisp_template = mrisp_template ;
      parms.l_corr = 1.0f ;

      MRISrigidBodyAlignGlobal(mris, &parms, 1.0, 64.0, 8) ;
      if (Gdiag & DIAG_WRITE)
        MRISwrite(mris, "sphere.rot.global") ;
      MRISrigidBodyAlignLocal(mris, &parms) ;
      if (Gdiag & DIAG_WRITE)
        MRISwrite(mris, "sphere.rot.local") ;
      MRISPfree(&parms.mrisp) ;
      MRISsaveVertexPositions(mris, CANONICAL_VERTICES) ;
    }

    if (multiframes)
    {
      for (n = 0; n < parms.nfields ; n++)
      {
        MRISsetOrigValuesToCurvatures(mris,n);
        MRISaverageCurvatures(mris, parms.fields[n].navgs) ;
        mrisp = MRIStoParameterization(mris, NULL, scale, 0) ;
        MRISPcombine(mrisp,
                     mrisp_template,
                     parms.fields[n].frame * IMAGES_PER_SURFACE) ;
        MRISPfree(&mrisp) ;
      }
      /* free the VALS_VP structure */
      for ( n = 0; n < mris->nvertices ; n++)
      {
        v=&mris->vertices[n];
        vp=(VALS_VP*)v->vp;
        free(vp->orig_vals);
        free(vp->vals);
        free(vp);
        v->vp=NULL;
      }
      MRISfree(&mris) ;
    }
    else
    {
      for (sno = 0; sno < SURFACES ; sno++)
      {
        if (curvature_names[sno])  /* read in precomputed curvature file */
        {
          sprintf(surf_fname, "%s/%s/surf/%s.%s",
                  subjects_dir, subject, hemi, curvature_names[sno]) ;
          if (MRISreadCurvatureFile(mris, surf_fname) != NO_ERROR)
          {
            nbad++ ;
            ErrorPrintf(Gerror, "%s: could not read curvature file '%s'\n",
                        Progname, surf_fname) ;
            failed = 1 ;
            break ;
          }
          /* the two next lines were not in the original code */
          MRISaverageCurvatures(mris, navgs) ;
          MRISnormalizeCurvature(mris, which_norm) ;
        } else                       /* compute curvature of surface */
        {
          sprintf(surf_fname, "%s/%s/surf/%s.%s",
                  subjects_dir, subject, hemi, surface_names[sno]) ;
          if (MRISreadVertexPositions(mris, surf_fname) != NO_ERROR)
          {
            ErrorPrintf(ERROR_NOFILE, "%s: could not read surface file %s",
                        Progname, surf_fname) ;
            nbad++ ;
            failed = 1 ;
            break ;
          }

          if (nbrs > 1)
            MRISsetNeighborhoodSize(mris, nbrs) ;
          MRIScomputeMetricProperties(mris) ;
          MRIScomputeSecondFundamentalForm(mris) ;
          MRISuseMeanCurvature(mris) ;
          MRISaverageCurvatures(mris, navgs) ;
          MRISrestoreVertexPositions(mris, CANONICAL_VERTICES) ;
          MRISnormalizeCurvature(mris, which_norm) ;
        }
        fprintf(stderr, "computing parameterization for surface %s...\n",
                surf_fname);
        if (failed)
        {
          continue ;
          MRISfree(&mris) ;
        }
        mrisp = MRIStoParameterization(mris, NULL, scale, 0) ;
        MRISPcombine(mrisp, mrisp_template, sno*3) ;
        MRISPfree(&mrisp) ;
      }
      MRISfree(&mris) ;
    }
  }

#if 0
  if (mrisp_aligned)  /* new parameterization - use rigid alignment */
  {
    MRI_SP *mrisp_tmp ;

    if (Gdiag & DIAG_WRITE)
    {
      char *cp1 ;

      FileNameOnly(template_fname, fname) ;
      cp = strchr(fname, '.') ;
      if (cp)
      {
        cp1 = strrchr(fname, '.') ;
        if (cp1 && cp1 != cp)
          strncpy(parms.base_name, cp+1, cp1-cp-1) ;
        else
          strcpy(parms.base_name, cp+1) ;
      }
      else
        strcpy(parms.base_name, "template") ;
      sprintf(fname, "%s.%s.out", hemi, parms.base_name);
      parms.fp = fopen(fname, "w") ;
      printf("writing output to '%s'\n", fname) ;
    }
    for (ino = 0 ; ino < argc-1 ; ino++)
    {
      subject = argv[ino] ;
      if (Gdiag & DIAG_WRITE)
        fprintf(parms.fp, "processing subject %s\n", subject) ;
      fprintf(stderr, "processing subject %s\n", subject) ;
      sprintf(surf_fname, "%s/%s/surf/%s.%s",
              subjects_dir, subject, hemi, sphere_name) ;
      fprintf(stderr, "reading spherical surface %s...\n", surf_fname) ;
      mris = MRISread(surf_fname) ;
      if (!mris)
        ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
                  Progname, surf_fname) ;
      MRIScomputeMetricProperties(mris) ;
      MRISstoreMetricProperties(mris) ;
      MRISsaveVertexPositions(mris, ORIGINAL_VERTICES) ;
      sprintf(surf_fname, "%s/%s/surf/%s.%s",
              subjects_dir, subject, hemi, "sulc") ;
      if (MRISreadCurvatureFile(mris, surf_fname) != NO_ERROR)
        ErrorExit(Gerror, "%s: could not read curvature file '%s'\n",
                  Progname, surf_fname) ;
      parms.frame_no = 3 ;
      parms.mrisp = MRIStoParameterization(mris, NULL, scale, 0) ;
      parms.mrisp_template = mrisp_template ;
      parms.l_corr = 1.0f ;

      MRISrigidBodyAlignGlobal(mris, &parms, 1.0, 32.0, 8) ;
      if (Gdiag & DIAG_WRITE)
        MRISwrite(mris, "sphere.rot.global") ;
      MRISrigidBodyAlignLocal(mris, &parms) ;
      if (Gdiag & DIAG_WRITE)
        MRISwrite(mris, "sphere.rot.local") ;
      MRISPfree(&parms.mrisp) ;

#if 0
      /* write out rotated surface */
      sprintf(surf_fname, "%s.rot", mris->fname) ;
      fprintf(stderr, "writing out rigidly aligned surface to '%s'\n",
              surf_fname) ;
      MRISwrite(mris, surf_fname) ;
#endif

      /* now generate new parameterization using the optimal alignment */
      for (sno = 0; sno < SURFACES ; sno++)
      {
        if (curvature_names[sno])  /* read in precomputed curvature file */
        {
          sprintf(surf_fname, "%s/%s/surf/%s.%s",
                  subjects_dir, subject, hemi, curvature_names[sno]) ;
          if (MRISreadCurvatureFile(mris, surf_fname) != NO_ERROR)
            ErrorExit(Gerror, "%s: could not read curvature file '%s'\n",
                      Progname, surf_fname) ;
        } else                       /* compute curvature of surface */
        {
          sprintf(surf_fname, "%s/%s/surf/%s.%s",
                  subjects_dir, subject, hemi, surface_names[sno]) ;
          if (MRISreadVertexPositions(mris, surf_fname) != NO_ERROR)
            ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
                      Progname, surf_fname) ;

          if (nbrs > 1)
            MRISsetNeighborhoodSize(mris, nbrs) ;
          MRIScomputeMetricProperties(mris) ;
          MRIScomputeSecondFundamentalForm(mris) ;
          MRISuseMeanCurvature(mris) ;
          MRISaverageCurvatures(mris, navgs) ;
          MRISrestoreVertexPositions(mris, ORIGINAL_VERTICES) ;
          MRISnormalizeCurvature(mris) ;
        }
        fprintf(stderr, "computing parameterization for surface %s...\n",
                surf_fname);
        mrisp = MRIStoParameterization(mris, NULL, scale, 0) ;
        MRISPcombine(mrisp, mrisp_aligned, sno*3) ;
        MRISPfree(&mrisp) ;
      }
      MRISfree(&mris) ;
    }

    if (Gdiag & DIAG_WRITE)
      fclose(parms.fp) ;

    mrisp_tmp = mrisp_aligned ;
    mrisp_aligned = mrisp_template ;
    mrisp_template = mrisp_tmp ;
    MRISPfree(&mrisp_aligned) ;
  }
#endif
  fprintf(stderr,
          "writing updated template with %d subjects to %s...\n",
          argc-1-nbad, template_fname) ;
  MRISPwrite(mrisp_template, template_fname) ;
  MRISPfree(&mrisp_template) ;
  exit(0) ;
  return(0) ;  /* for ansi */
}
Exemplo n.º 5
0
int
main(int argc, char *argv[]) {
  char         *cp, **av, *in_fname, fname[100], path[100],
  name[100], hemi[100] ;
  int          ac, nargs ;

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

  in_fname = argv[1] ;
#if 0
  out_fname = argv[2] ;
  cp = strrchr(out_fname, '.') ;
#endif

  if (patch_flag)   /* read in orig surface before reading in patch */
  {
    FileNamePath(in_fname, path) ;
    FileNameOnly(in_fname, name) ;
    cp = strchr(name, '.') ;
    if (cp) {
      strncpy(hemi, cp-2, 2) ;
      hemi[2] = 0 ;
    } else
      strcpy(hemi, "lh") ;
    sprintf(fname, "%s/%s.smoothwm", path, hemi) ;
    mris = MRISread(fname) ;
    if (!mris)
      ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
                Progname, fname) ;
    FileNameOnly(in_fname, name) ;
    MRISstoreMetricProperties(mris) ;
    MRISsaveVertexPositions(mris, ORIGINAL_VERTICES) ;
    if (MRISreadPatch(mris, name) != NO_ERROR)
      ErrorExit(ERROR_NOFILE, "%s: could not read patch file %s",
                Progname, name) ;
  } else {
    mris = MRISread(in_fname) ;
    if (!mris)
      ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
                Progname, in_fname) ;

    MRISreadOriginalProperties(mris, "smoothwm") ;
  }

  MRISsaveVertexPositions(mris, TMP_VERTICES) ;
  MRISrestoreVertexPositions(mris, ORIGINAL_VERTICES) ;
  MRISsampleAtEachDistance(mris, nbhd_size, max_nbrs) ;
  MRIScomputeMetricProperties(mris) ;
  MRISstoreMetricProperties(mris) ;

  MRISrestoreVertexPositions(mris, TMP_VERTICES) ;
  MRIScomputeMetricProperties(mris) ;

  MRIScomputeDistanceErrors(mris, nbhd_size, max_nbrs) ;
#if 0
  if (write_flag) {
    MRISareaErrors(mris) ;
    MRISangleErrors(mris) ;
  }

  if (area_flag) {
    sprintf(fname, "%s.area_error", in_fname) ;
    printf("writing area errors to %s\n", fname) ;
    MRISwriteAreaError(mris, fname) ;
    sprintf(fname, "%s.angle_error", in_fname) ;
    printf("writing angle errors to %s\n", fname) ;
    MRISwriteAngleError(mris, fname) ;
  }
#else
  sprintf(fname, "%s.distance_error", in_fname) ;
  fprintf(stderr, "writing errors to %s\n", fname) ;
  MRISwriteValues(mris, fname) ;
#endif

  MRISfree(&mris) ;

  exit(0) ;
  return(0) ;  /* for ansi */
}
Exemplo n.º 6
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 */
}
Exemplo n.º 8
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 */
}
Exemplo n.º 9
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 */
}
Exemplo n.º 10
0
int
MRISpositionOptimalSphere(MRI_SURFACE *mris, MRI *mri_inner, float sample_dist) {
  double  r, rmin, rmax, min_sse, min_r, min_x0, min_y0, min_z0, x0, y0, z0, sse,
  xmin, xmax, ymin, ymax, zmin, zmax, delta_r, delta_x, delta_y, delta_z ;
  int     scale ;

  MRISsaveVertexPositions(mris, ORIGINAL_VERTICES) ;
  MRIScomputeMetricProperties(mris) ;
  rmin = mris->radius*.5 ;
  rmax = mris->radius*1.5 ;
  min_x0 = mris->xctr ;
  min_y0 = mris->yctr ;
  min_z0 = mris->zctr ;
  min_r = mris->radius ;

  MRISrestoreVertexPositions(mris, ORIGINAL_VERTICES) ;
  MRISprojectOntoTranslatedSphere(mris, mris, min_r, min_x0, min_y0, min_z0) ;
  min_sse = compute_surface_sse(mris, mri_inner, sample_dist) ;
  delta_r = DELTA_R ;
  for (r = rmin ; r <= rmax ; r += delta_r) {
    MRISrestoreVertexPositions(mris, ORIGINAL_VERTICES) ;
    MRISprojectOntoTranslatedSphere(mris, mris, r, min_x0, min_y0, min_z0) ;
    sse = compute_surface_sse(mris, mri_inner, sample_dist) ;
    if (sse < min_sse) {
      min_sse = sse ;
      min_r = r ;
      printf("new min sse %2.0f, found at r=%2.1f mm, c = (%2.1f, %2.1f, %2.1f)\n",
             min_sse, min_r, min_x0, min_y0, min_z0) ;
    }
  }
  MRISrestoreVertexPositions(mris, ORIGINAL_VERTICES) ;
  MRISprojectOntoTranslatedSphere(mris, mris, min_r, min_x0, min_y0, min_z0) ;
  MRISwrite(mris, "lh.minr") ;
  for (scale = 8 ; scale >= 1 ; scale /=2) {
    printf("scale = %d\n", scale) ;
    xmin = min_x0-scale ;
    xmax = min_x0+scale ;
    ymin = min_y0-scale ;
    ymax = min_y0+scale ;
    zmin = min_z0-scale ;
    zmax = min_z0+scale ;
    rmin = min_r*(1.0-scale/128.0) ;
    rmax = min_r*(1.0+scale/128.0) ;
    delta_x = mri_inner->xsize*scale/16 ;
    delta_y = mri_inner->ysize*scale/16 ;
    delta_z = mri_inner->zsize*scale/16 ;
    delta_r = DELTA_R*scale ;
    if (delta_x > (xmax-xmin)/3)
      delta_x = (xmax-xmin)/3 ;
    if (delta_y > (ymax-ymin)/3)
      delta_y = (ymax-ymin)/3 ;
    if (delta_z > (zmax-zmin)/3)
      delta_z = (zmax-zmin)/3 ;
    if (delta_r > (rmax-rmin)/3)
      delta_r = (rmax-rmin)/3 ;

    for (x0 = xmin ; x0 <= xmax ; x0 += delta_x) {
      for (y0 = ymin ; y0 <= ymax ; y0 += delta_y) {
        for (z0 = zmin ; z0 <= zmax ; z0 += delta_z) {
          for (r = rmin ; r <= rmax ; r += delta_r) {
            MRISrestoreVertexPositions(mris, ORIGINAL_VERTICES) ;
            MRISprojectOntoTranslatedSphere(mris, mris, r, x0, y0, z0) ;
            sse = compute_surface_sse(mris, mri_inner, sample_dist) ;
            if (sse < min_sse) {
              min_sse = sse ;
              min_r = r ;
              min_x0 = x0 ;
              min_y0 = y0 ;
              min_z0 = z0 ;
              printf("new min sse %2.0f, found at r=%2.1f mm, c = (%2.1f, %2.1f, %2.1f)\n",
                     min_sse, min_r, min_x0, min_y0, min_z0) ;
            }
          }
        }
      }
    }
    {
      char fname[STRLEN] ;
      MRISrestoreVertexPositions(mris, ORIGINAL_VERTICES) ;
      MRISprojectOntoTranslatedSphere(mris, mris, min_r, min_x0, min_y0, min_z0) ;
      sprintf(fname, "lh.min_scale%d", scale) ;
      MRISwrite(mris, fname) ;
    }
  }

  MRISrestoreVertexPositions(mris, ORIGINAL_VERTICES) ;
  MRISprojectOntoTranslatedSphere(mris, mris, min_r, min_x0, min_y0, min_z0) ;
  return(NO_ERROR) ;
}
Exemplo n.º 11
0
static int
initialize_surface_position(MRI_SURFACE *mris, MRI *mri_masked, int outside, INTEGRATION_PARMS *parms) {
  MRI    *mri_dilated ;
  int    x, y, z, vno ;
  double x0, y0, z0, radius = 0, dist, num ;
  Real   xs, ys, zs ;
  VERTEX *v ;

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

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

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

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

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


    MRIfree(&mri_dilated) ;
    MRISprojectOntoSphere(mris, mris, radius*1.25) ;
    for (vno = 0 ; vno < mris->nvertices ; vno++) {
      v = &mris->vertices[vno] ;
      v->x += x0 ;
      v->y += y0 ;
      v->z += z0 ;
    }
    MRIScomputeMetricProperties(mris) ;
  }
  parms->target_radius = radius ;
  MRISsaveVertexPositions(mris, ORIGINAL_VERTICES) ;
  return(NO_ERROR) ;
}
Exemplo n.º 12
0
int
main(int argc, char *argv[])
{
  char               **av, *in_fname, *out_fname, fname[STRLEN], path[STRLEN] ;
  int                ac, nargs, start_t, pass ;
  MRI_SURFACE        *mris ;

  char cmdline[CMD_LINE_LEN] ;

  make_cmd_version_string
  (argc, argv,
   "$Id: mris_smooth.c,v 1.28 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_smooth.c,v 1.28 2011/03/02 00:04:34 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)
  {
    print_help() ;
  }

  in_fname = argv[1] ;
  out_fname = argv[2] ;
  FileNamePath(out_fname, path) ;

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

  MRISaddCommandLine(mris, cmdline) ;
  MRISremoveTriangleLinks(mris) ;
  fprintf(stderr, "smoothing surface tessellation for %d iterations...\n",
          niterations);

  MRIScomputeMetricProperties(mris) ;
  MRISstoreMetricProperties(mris) ;
  MRISsetNeighborhoodSize(mris, nbrs) ;
#define DT 0.5
  if (gaussian_norm > 0)
  {
    int i, done, start_avgs = gaussian_avgs, j ;

    done = 0;
    start_t = 0 ;
    pass = 0 ;
    do
    {
      for (i = start_t ; i < niterations+start_t ; i++)
      {
        MRIScomputeMetricProperties(mris) ;
        MRISsaveVertexPositions(mris, TMP_VERTICES) ;
        for (j = 0 ; j < 5 ; j++)
        {
          MRISaverageVertexPositions(mris, 2) ; // turn flat spikes into tubular ones
          MRIScomputeMetricProperties(mris) ;
          MRIScomputeSecondFundamentalForm(mris) ;
          MRIShistoThresholdGaussianCurvatureToMarked(mris, (float)(mris->nvertices-20)/mris->nvertices) ;
        }
        MRISrestoreVertexPositions(mris, TMP_VERTICES) ;
        MRIScomputeMetricProperties(mris) ;
        MRISsmoothSurfaceNormals(mris, gaussian_avgs) ;
        MRISclearMarks(mris) ;
        MRISthresholdGaussianCurvatureToMarked(mris, 10, 50);
        MRIScomputeSecondFundamentalForm(mris) ;
        MRIShistoThresholdGaussianCurvatureToMarked(mris, (float)(mris->nvertices-20)/mris->nvertices) ;
        MRISthresholdGaussianCurvatureToMarked(mris, 10, 50);
        if ((write_iterations > 0) && ((i % write_iterations) == 0))
        {
          char fname[STRLEN] ;

          sprintf(fname, "%s%04d", out_fname, i) ;
          printf("writing snapshot to %s...\n", fname) ;
          MRISwrite(mris, fname) ;
          if (Gdiag & DIAG_WRITE)
          {
            MRISuseGaussianCurvature(mris) ;
            sprintf(fname, "%s_K%04d", out_fname, i) ;
            printf("writing curvature to %s...\n", fname) ;
            MRISwriteCurvature(mris, fname) ;
            sprintf(fname, "%s_marked%04d", out_fname, i) ;
            printf("writing marks to %s...\n", fname) ;
            MRISwriteMarked(mris, fname) ;
          }
        }
        for (j = 0 ; j <= 5*nint(1/DT) ; j++)
        {
          MRISmarkedSpringTerm(mris, l_spring) ;
          MRISaverageGradients(mris, gaussian_avgs) ;
          MRISmomentumTimeStep(mris, momentum, DT, 1, gaussian_avgs) ;
          MRISclearGradient(mris) ;
          MRIScomputeMetricProperties(mris) ;
          MRISsmoothSurfaceNormals(mris, gaussian_avgs) ;
          {
            int vno ;
            VERTEX *v ;

            for (vno = 0 ; vno < mris->nvertices ; vno++)
            {
              v = &mris->vertices[vno] ;
              if (v->marked > 0)
              {
                v->K = 1.0/(v->marked) ;
              }
              else
              {
                v->K = 0 ;
              }
            }
          }
        }
      }
      MRISclearGradient(mris) ;
      if (gaussian_avgs == 2)
      {
        if (pass++ > 4)
        {
          done = 1 ;
        }
        else
        {
          int num = count_big_curvatures(mris, 2) ;
          printf("------------------------------------------------------\n") ;
          printf("------------------------------------------------------\n") ;
          printf("------------------ pass %d (num=%d) ------------------\n",
                 pass, num) ;
          printf("------------------------------------------------------\n") ;
          printf("------------------------------------------------------\n") ;
          gaussian_avgs = start_avgs ;
        }
      }
      else
      {
        gaussian_avgs /= 2 ;
        if (done ==0)
        {
          printf("----------------- setting avgs to %d -----------------\n", gaussian_avgs) ;
        }
      }
      start_t = i ;
    }
    while (!done) ;

#if 0
    // more smoothing with principal curvatures
    gaussian_avgs = start_avgs ;
    printf("--------------------------------------------------------------------------\n") ;
    printf("--------------------------------------------------------------------------\n") ;
    printf("---------------------- starting threshold smoothing ----------------------\n") ;
    printf("--------------------------------------------------------------------------\n") ;
    printf("--------------------------------------------------------------------------\n") ;
    do
    {
      for (i = start_t ; i < niterations+start_t ; i++)
      {
        MRIScomputeMetricProperties(mris) ;
        MRIScomputeSecondFundamentalForm(mris) ;
        MRISsmoothSurfaceNormals(mris, 16) ;
#define KTHRESH 1.5  // everything with kmin less than this will not move
        MRISthresholdPrincipalCurvatures(mris, KTHRESH) ;
        MRISspringTermWithGaussianCurvature(mris, gaussian_norm, l_spring) ;
        MRISaverageGradients(mris, gaussian_avgs) ;
        MRISmomentumTimeStep(mris, 0, 0.1, 1, gaussian_avgs) ;
        MRISclearGradient(mris) ;
        if ((write_iterations > 0) && (((i+1) % write_iterations) == 0))
        {
          char fname[STRLEN] ;

          sprintf(fname, "%s%04d", out_fname, i+1) ;
          printf("writing snapshot to %s...\n", fname) ;
          MRISwrite(mris, fname) ;
          if (Gdiag & DIAG_WRITE/* && DIAG_VERBOSE_ON*/)
          {
            MRISuseGaussianCurvature(mris) ;
            sprintf(fname, "%s_K%04d", out_fname, i+1) ;
            printf("writing curvature to %s...\n", fname) ;
            MRISwriteCurvature(mris, fname) ;
          }
        }
      }
      MRISclearGradient(mris) ;
      done = (gaussian_avgs == 2) ;
      gaussian_avgs /= 2 ;
      if (done ==0)
      {
        printf("---------------------- setting avgs to %d ----------------------\n", gaussian_avgs) ;
      }
      start_t = i ;
    }
    while (!done) ;
#endif
  }
  else
  {
    MRISaverageVertexPositions(mris, niterations) ;
  }

  fprintf(stderr, "smoothing complete - recomputing first and second "
          "fundamental forms...\n") ;
  MRIScomputeMetricProperties(mris) ;

  if (rescale)
  {
    MRISscaleBrainArea(mris) ;
  }
  MRIScomputeSecondFundamentalForm(mris) ;
  MRISuseMeanCurvature(mris) ;
  MRISaverageCurvatures(mris, navgs) ;
  if (normalize_flag)
  {
    MRISnormalizeCurvature(mris, which_norm) ;
  }
  sprintf(fname, "%s.%s", mris->hemisphere == LEFT_HEMISPHERE?"lh":"rh",
          curvature_fname);
  if (no_write == 0)
  {
    fprintf(stderr, "writing smoothed curvature to %s/%s\n", path,fname) ;
    MRISwriteCurvature(mris, fname) ;
    sprintf(fname, "%s.%s", mris->hemisphere == LEFT_HEMISPHERE?"lh":"rh",
            area_fname);
    fprintf(stderr, "writing smoothed area to %s/%s\n", path, fname) ;
    MRISwriteArea(mris, fname) ;
  }

  if (Gdiag & DIAG_SHOW)
  {
    fprintf(stderr, "writing smoothed surface to %s\n", out_fname) ;
  }
  MRISwrite(mris, out_fname) ;
  exit(0) ;
  return(0) ;  /* for ansi */
}
Exemplo n.º 13
0
int
main(int argc, char *argv[]) {
  MRI_SURFACE  *mris ;
  char         **av, *in_label_fname, *out_label_fname, *surf_fname, ext[STRLEN] ; ;
  int          ac, nargs ;
  LABEL        *label, *label_out ;

  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_label_fname = argv[1] ;
  surf_fname = argv[2] ;
  out_label_fname = argv[3] ;

  printf("reading label from %s...\n", in_label_fname) ;
  if (!strcmp(FileNameExtension(in_label_fname, ext), "mgz"))
  {
    MRI *mri = MRIread(in_label_fname) ;
    printf("creating label from volumetric inputs with voxval = %d\n", voxval) ;
    if (mri == NULL)
      ErrorExit(ERROR_NOFILE, "%s: could not read input volume from %s", Progname, in_label_fname);
    label = LabelfromASeg(mri, voxval) ;
    MRIfree(&mri) ;
  }
  else
  {
    label = LabelRead(NULL, in_label_fname) ;
    if (!label)
      ErrorExit(ERROR_NOFILE, "%s: could not read label file %s", Progname, in_label_fname) ;
  }
  printf("reading surface from %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 0
  LabelFillUnassignedVertices(mris, label) ;
#else
  label_out = LabelFillHoles(label, mris, ORIGINAL_VERTICES) ;
#endif
  printf("writing sampled label to %s...\n", out_label_fname) ;
  LabelWrite(label_out, out_label_fname) ;
  MRISfree(&mris) ;
  LabelFree(&label) ;

  exit(0) ;
  return(0) ;  /* for ansi */
}
int
main(int argc, char *argv[])
{
  char          **av, *hemi, fname[STRLEN],
                *in_aseg_name, *out_aseg_name, *surf_dir ;
  int           ac, nargs, h ;
  MRI_SURFACE   *mris ;
  MRI           *mri_aseg ;

  char cmdline[CMD_LINE_LEN] ;
  make_cmd_version_string
  (argc, argv,
   "$Id: mri_relabel_hypointensities.c,v 1.13 2015/05/15 18:44:10 nicks Exp $",
   "$Name:  $", cmdline);

  /* rkt: check for and handle version tag */
  nargs = handle_version_option
          (argc, argv,
           "$Id: mri_relabel_hypointensities.c,v 1.13 2015/05/15 18:44:10 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_aseg_name = argv[1] ;
  surf_dir = argv[2] ;
  out_aseg_name = argv[3] ;

  mri_aseg = MRIread(in_aseg_name) ;
  if (!mri_aseg) {
    ErrorExit(ERROR_NOFILE,
              "%s: could not read input segmentation %s",
              Progname, in_aseg_name) ;
  }

  for (h = 0 ; h <= 1 ; h++) {
    if (h == 0) {
      hemi = "lh" ;
    } else {
      hemi = "rh" ;
    }
    sprintf(fname, "%s/%s.%s", surf_dir, 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) ;

    printf("relabeling %s hypointensities...\n", hemi) ;
    relabel_hypointensities(mri_aseg, mris, h) ;
    MRISfree(&mris) ;
  }
  relabel_hypointensities_neighboring_gray(mri_aseg) ;

  MRIwrite(mri_aseg, out_aseg_name) ;
  exit(0) ;
  return(0) ;  /* for ansi */
}
Exemplo n.º 15
0
int
main(int argc, char *argv[])
{
  char        **av, *out_name ;
  int          ac, nargs ;
  int          msec, minutes, seconds ;
  struct timeb start ;
  MRI_SURFACE  *mris ;
  GCA_MORPH    *gcam ;
  MRI          *mri = NULL ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mris_interpolate_warp.c,v 1.5 2011/10/07 12:07:26 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 < 3)
  {
    usage_exit(1) ;
  }


  /*
    note that a "forward" morph means a retraction, so we reverse the order of the argvs here.
    This means that for every voxel in the inflated image we have a vector that points to where in
    the original image it came from, and *NOT* the reverse.
  */
  mris = MRISread(argv[2]) ;
  if (mris == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not read source surface %s\n", Progname,argv[2]) ;

  MRISsaveVertexPositions(mris, ORIGINAL_VERTICES) ;
  if (MRISreadVertexPositions(mris, argv[1]) != NO_ERROR)
    ErrorExit(ERROR_NOFILE, "%s: could not read target surface %s\n", Progname,argv[1]) ;

  if (like_vol_name == NULL)
  {
    mri = MRIallocSequence(mris->vg.width, mris->vg.height, mris->vg.depth, MRI_FLOAT, 3) ;
    MRIcopyVolGeomToMRI(mri, &mris->vg) ;
  }
  else
  {
    MRI *mri_tmp ;
    mri_tmp = MRIread(like_vol_name) ;
    if (mri_tmp == NULL)
    {
      ErrorExit(ERROR_NOFILE, "%s: could not like volume %s\n", like_vol_name) ;
    }
    mri = MRIallocSequence(mri_tmp->width, mri_tmp->height, mri_tmp->depth, MRI_FLOAT, 3) ;
    MRIcopyHeader(mri_tmp, mri) ;
    MRIfree(&mri_tmp) ;
  }
  if (Gdiag & DIAG_SHOW && DIAG_VERBOSE_ON)
  {
    double xv, yv, zv ;
    VERTEX *v = &mris->vertices[0] ;
    MRISsurfaceRASToVoxel(mris, mri, v->x, v->y, v->z, &xv, &yv, &zv) ;
    printf("v 0: sras (%f, %f, %f) --> vox (%f, %f, %f)\n", v->x,v->y,v->z,xv,yv,zv);
    MRISsurfaceRASToVoxelCached(mris, mri, v->x, v->y, v->z, &xv, &yv, &zv) ;
    printf("v 0: sras (%f, %f, %f) --> vox (%f, %f, %f)\n", v->x,v->y,v->z,xv,yv,zv);
    DiagBreak() ;
  }
  {
    MRI *mri_tmp ;
    mri_tmp = expand_mri_to_fit_surface(mris, mri) ;
    MRIfree(&mri) ; mri = mri_tmp ;
  }
  write_surface_warp_into_volume(mris, mri, niter) ;

  if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
    MRIwrite(mri, "warp.mgz") ;
  gcam = GCAMalloc(mri->width, mri->height, mri->depth) ;
  GCAMinitVolGeom(gcam, mri, mri) ;
  GCAMremoveSingularitiesAndReadWarpFromMRI(gcam, mri) ;
//  GCAMreadWarpFromMRI(gcam, mri) ;
  //  GCAsetVolGeom(gca, &gcam->atlas);
#if 0
  gcam->gca = gcaAllocMax(1, 1, 1,
			  mri->width, mri->height,
			  mri->depth,
			  0, 0) ;
 GCAMinit(gcam, mri, NULL, NULL, 0) ;
#endif
#if 0
  GCAMinvert(gcam, mri) ;
  GCAMwriteInverseWarpToMRI(gcam, mri) ;
  GCAMremoveSingularitiesAndReadWarpFromMRI(gcam, mri) ;  // should be inverse now
#endif
  if (mri_in)
  {
    MRI *mri_warped, *mri_tmp ;
    printf("applying warp to %s and writing to %s\n", mri_in->fname, out_fname) ;
    mri_tmp = MRIextractRegionAndPad(mri_in, NULL, NULL, pad) ; MRIfree(&mri_in) ; mri_in = mri_tmp ;
    mri_warped = GCAMmorphToAtlas(mri_in, gcam, NULL, -1, SAMPLE_TRILINEAR) ;
    MRIwrite(mri_warped, out_fname) ;
    if (Gdiag_no >= 0)
    {
      double  xi, yi, zi, xo, yo, zo, val;
      int     xp, yp, zp ;
      GCA_MORPH_NODE *gcamn ;

      VERTEX *v = &mris->vertices[Gdiag_no] ;
      MRISsurfaceRASToVoxelCached(mris, mri, v->origx, v->origy, v->origz, &xi, &yi, &zi) ;
      MRISsurfaceRASToVoxelCached(mris, mri, v->x, v->y, v->z, &xo, &yo, &zo) ;
      printf("surface vertex %d: inflated (%2.0f, %2.0f, %2.0f), orig (%2.0f, %2.0f, %2.0f)\n", Gdiag_no, xi, yi, zi, xo, yo, zo) ;
      MRIsampleVolume(mri_in, xo, yo, zo, &val) ;
      xp = nint(xi) ; yp = nint(yi) ; zp = nint(zi) ;
      gcamn = &gcam->nodes[xp][yp][zp] ;
      printf("warp = (%2.1f, %2.1f, %2.1f), orig (%2.1f %2.1f %2.1f) = %2.1f \n", 
	     gcamn->x, gcamn->y, gcamn->z,
	     gcamn->origx, gcamn->origy, gcamn->origz,val) ;
      DiagBreak() ;
    }
  }
  if (no_write == 0)
  {
    out_name = argv[3] ;
    GCAMwrite(gcam, out_name) ;
  }
  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  fprintf(stderr, "warp field calculation took %d minutes and %d seconds.\n", minutes, seconds) ;
  exit(0) ;
  return(0) ;
}
Exemplo n.º 16
0
int
main(int argc, char *argv[]) 
{
  char   **av, fname[STRLEN], *cp ;
  int    ac, nargs ;
  char   *subject, *out_fname, *hemi, *ohemi ;
  int    msec, minutes, seconds ;
  struct timeb start ;
  MRI          *mri, *mri_features, *mri_ribbon, *mri_aseg, *mri_aparc ;
  MRI_SURFACE  *mris, *mris_contra ;
  LABEL        *cortex ;

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

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

  TimerStart(&start) ;

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

  if (argc < 4)
    usage_exit(1) ;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


  MRIwrite(mri_features, out_fname) ;

  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  fprintf(stderr, "feature extraction took %d minutes and %d seconds.\n", minutes, seconds) ;
  exit(0) ;
  return(0) ;
}
int
main(int argc, char *argv[]) {
  char         **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 */
}
Exemplo n.º 18
0
int
main(int argc, char *argv[]) {
  char         **av, fname[STRLEN], *input_name, *subject_name, *cp,*hemi,
  *svm_name, *surf_name, *output_subject_name ;
  int          ac, nargs, vno ;
  int          msec, minutes, seconds ;
  struct timeb start ;
  MRI_SURFACE  *mris ;
  SVM          *svm ;
  double       classification ;
  float        *inputs ;
  MRI_SP       *mrisp ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mris_svm_classify.c,v 1.6 2011/03/02 00:04:34 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 (!strlen(subjects_dir)) /* hasn't been set on command line */
  {
    cp = getenv("SUBJECTS_DIR") ;
    if (!cp)
      ErrorExit(ERROR_BADPARM, "%s: SUBJECTS_DIR not defined in environment",
                Progname);
    strcpy(subjects_dir, cp) ;
  }
  if (argc < 7)
    usage_exit(1) ;

  subject_name = argv[1] ;
  hemi = argv[2] ;
  surf_name = argv[3] ;
  input_name = argv[4] ;
  output_subject_name = argv[5] ;
  svm_name = argv[6] ;

  printf("reading svm from %s...\n", svm_name) ;
  svm = SVMread(svm_name) ;
  if (!svm)
    ErrorExit(ERROR_NOFILE, "%s: could not read classifier from %s",
              Progname, svm_name) ;
  if (log_fname != NULL)
    printf("logging results to %s, true_class = %s\n",
           log_fname, true_class > 0 ? svm->class1_name : svm->class2_name) ;

  sprintf(fname, "%s/%s/surf/%s.%s", subjects_dir,subject_name,hemi,surf_name);
  printf("reading surface from %s...\n", fname) ;
  mris = MRISread(fname) ;
  if (!mris)
    ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s for %s",
              Progname, fname, subject_name) ;
  MRISsaveVertexPositions(mris, CANONICAL_VERTICES) ;

  if (MRISreadCurvature(mris, input_name) != NO_ERROR)
    ErrorExit(ERROR_BADPARM, "%s: could not read curvature from %s", input_name) ;

    if (nannotations > 0)
    {
      int vno, a, found ;
      VERTEX *v ;
      
      if (MRISreadAnnotation(mris, annot_name) != NO_ERROR)
        ErrorExit(ERROR_NOFILE, 
                  "%s: could not read annot file %s for subject %s",
                  Progname, annot_name, subject_name) ;
      for (a = 0 ; a < nannotations ; a++)
      {
        int index ;
        
        CTABfindName(mris->ct, anames[a], &index) ;
        CTABannotationAtIndex(mris->ct, index, &annotations[a]) ;
        printf("mapping annot %s to %d\n",
               anames[a], annotations[a]) ;
      }
      // rip all vertices that don't have one of the specified annotations
      for (vno = 0 ; vno < mris->nvertices ; vno++)
      {
        v = &mris->vertices[vno] ;
        if (v->ripflag)
          continue ;
        found = 0 ;
        for (a = 0 ; a < nannotations ; a++)
          if (v->annotation == annotations[a])
            found = 1 ;
        if (found == 0)
          v->ripflag = 1 ;
      }
    }
  if (navgs > 0)
    MRISaverageCurvatures(mris, navgs) ;

  mrisp = MRIStoParameterization(mris, NULL, 1, 0) ;
  MRISfree(&mris) ;

  /* read in output surface */
  sprintf(fname, "%s/%s/surf/%s.%s", subjects_dir,output_subject_name,hemi,surf_name);
  printf("reading output surface from %s...\n", fname) ;
  mris = MRISread(fname) ;
  if (!mris)
    ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s for %s",
              Progname, fname, output_subject_name) ;
  MRISsaveVertexPositions(mris, CANONICAL_VERTICES) ;
  MRISfromParameterization(mrisp, mris, 0) ;

  if (label_name) {
    area = LabelRead(output_subject_name, label_name) ;
    if (!area)
      ErrorExit(ERROR_NOFILE, "%s: could not read label %s", Progname,
                label_name) ;
    MRISmaskNotLabel(mris, area) ;
  } else
    area = NULL ;
  if (mris->nvertices != svm->ninputs)
    ErrorExit(ERROR_BADPARM, "%s: svm input (%d) does not match # of "
              "surface vertices (%d)",
              Progname, svm->ninputs, mris->nvertices);

  inputs = (float *)calloc(mris->nvertices, sizeof(float)) ;
  if (!inputs)
    ErrorExit(ERROR_NOMEMORY, "%s: could not allocate %d input vector",
              Progname, mris->nvertices) ;
  for (vno = 0 ; vno < mris->nvertices ; vno++)
    inputs[vno] = mris->vertices[vno].curv ;
  classification = SVMclassify(svm, inputs) ;
  printf("classification %f, class = %s",classification,
         classification > 0 ? svm->class1_name : svm->class2_name) ;
  if (true_class != 0)
    printf(", %s", true_class*classification>0 ? "CORRECT" : "INCORRECT") ;
  printf("\n") ;

  if (log_fname) {
    FILE *fp ;
    fp = fopen(log_fname, "a") ;
    if (!fp)
      ErrorExit(ERROR_BADPARM, "%s: could not open log file %s", log_fname) ;
    fprintf(fp, "%-30.30s %s %d %f %f\n",
            subject_name, hemi, (true_class*classification)>0, classification,
            true_class) ;
    fclose(fp) ;
  }
  free(inputs) ;
  MRISfree(&mris) ;
  SVMfree(&svm) ;
  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  printf("classification took %d minutes and %d seconds.\n", minutes, seconds) ;
  exit(0) ;
  return(0) ;
}
Exemplo n.º 19
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 */
}
Exemplo n.º 20
0
int
main(int argc, char *argv[])
{
  char **av, *surf_fname, *template_fname, *out_fname, fname[STRLEN],*cp;
  int ac, nargs,err, msec ;
  MRI_SURFACE  *mris ;
  MRI_SP       *mrisp_template ;

  char cmdline[CMD_LINE_LEN] ;
  struct  timeb start ;

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

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

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

  memset(&parms, 0, sizeof(parms)) ;
  parms.projection = PROJECT_SPHERE ;
  parms.flags |= IP_USE_CURVATURE ;
  parms.tol = 0.5 ;    // was 1e-0*2.5
  parms.min_averages = 0 ;
  parms.l_area = 0.0 ;
  parms.l_parea = 0.1f ;  // used to be 0.2
  parms.l_dist = 5.0 ; // used to be 0.5, and before that 0.1
  parms.l_corr = 1.0f ;
  parms.l_nlarea = 1 ;
  parms.l_pcorr = 0.0f ;
  parms.niterations = 25 ;
  parms.n_averages = 1024 ;   // used to be 256
  parms.write_iterations = 100 ;
  parms.dt_increase = 1.01 /* DT_INCREASE */;
  parms.dt_decrease = 0.99 /* DT_DECREASE*/ ;
  parms.error_ratio = 1.03 /*ERROR_RATIO */;
  parms.dt_increase = 1.0 ;
  parms.dt_decrease = 1.0 ;
  parms.l_external = 10000 ;   /* in case manual label is specified */
  parms.error_ratio = 1.1 /*ERROR_RATIO */;
  parms.integration_type = INTEGRATE_ADAPTIVE ;
  parms.integration_type = INTEGRATE_MOMENTUM /*INTEGRATE_LINE_MINIMIZE*/ ;
  parms.integration_type = INTEGRATE_LINE_MINIMIZE ;
  parms.dt = 0.9 ;
  parms.momentum = 0.95 ;
  parms.desired_rms_height = -1.0 ;
  parms.nbhd_size = -10 ;
  parms.max_nbrs = 10 ;

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

  if (nsigmas > 0)
  {
    MRISsetRegistrationSigmas(sigmas, nsigmas) ;
  }
  parms.which_norm = which_norm ;
  if (argc < 4)
  {
    usage_exit() ;
  }

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

  surf_fname = argv[1] ;
  template_fname = argv[2] ;
  out_fname = argv[3] ;

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

  fprintf(stderr, "reading surface from %s...\n", surf_fname) ;
  mris = MRISread(surf_fname) ;
  if (!mris)
    ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
              Progname, surf_fname) ;

  if (parms.var_smoothness)
  {
    parms.vsmoothness = (float *)calloc(mris->nvertices, sizeof(float)) ;
    if (parms.vsmoothness == NULL)
    {
      ErrorExit(ERROR_NOMEMORY, "%s: could not allocate vsmoothness array",
                Progname) ;
    }
    parms.dist_error = (float *)calloc(mris->nvertices, sizeof(float)) ;
    if (parms.dist_error == NULL)
    {
      ErrorExit(ERROR_NOMEMORY, "%s: could not allocate dist_error array",
                Progname) ;
    }
    parms.area_error = (float *)calloc(mris->nvertices, sizeof(float)) ;
    if (parms.area_error == NULL)
    {
      ErrorExit(ERROR_NOMEMORY, "%s: could not allocate area_error array",
                Progname) ;
    }
    parms.geometry_error = (float *)calloc(mris->nvertices, sizeof(float)) ;
    if (parms.geometry_error == NULL)
    {
      ErrorExit(ERROR_NOMEMORY, "%s: could not allocate geometry_error array",
                Progname) ;
    }
  }

  MRISresetNeighborhoodSize(mris, 1) ;
  if (annot_name)
  {
    if (MRISreadAnnotation(mris, annot_name) != NO_ERROR)
      ErrorExit(ERROR_BADPARM,
                "%s: could not read annot file %s",
                Progname, annot_name) ;
    MRISripMedialWall(mris) ;
  }

  MRISsaveVertexPositions(mris, TMP2_VERTICES) ;
  MRISaddCommandLine(mris, cmdline) ;
  if (!FZERO(dalpha) || !FZERO(dbeta) || !FZERO(dgamma))
    MRISrotate(mris, mris, RADIANS(dalpha), RADIANS(dbeta),
               RADIANS(dgamma)) ;

  if (curvature_fname[0])
  {
    fprintf(stderr, "reading source curvature from %s\n",curvature_fname) ;
    MRISreadCurvatureFile(mris, curvature_fname) ;
  }
  if (single_surf)
  {
    char        fname[STRLEN], *cp, surf_dir[STRLEN], hemi[10]  ;
    MRI_SURFACE *mris_template ;
    int         sno, tnbrs=3 ;

    FileNamePath(template_fname, surf_dir) ;
    cp = strrchr(template_fname, '/') ;
    if (cp == NULL) // no path - start from beginning of file name
    {
      cp = template_fname ;
    }
    cp = strchr(cp, '.') ;
    if (cp == NULL)
      ErrorExit(ERROR_NOFILE,
                "%s: could no scan hemi from %s",
                Progname, template_fname) ;
    strncpy(hemi, cp-2, 2) ;
    hemi[2] = 0 ;
    fprintf(stderr, "reading spherical surface %s...\n", template_fname) ;
    mris_template = MRISread(template_fname) ;
    if (mris_template == NULL)
    {
      ErrorExit(ERROR_NOFILE, "") ;
    }
#if 0
    if (reverse_flag)
    {
      MRISreverse(mris_template, REVERSE_X, 1) ;
    }
#endif
    MRISsaveVertexPositions(mris_template, CANONICAL_VERTICES) ;
    MRIScomputeMetricProperties(mris_template) ;
    MRISstoreMetricProperties(mris_template) ;

    if (noverlays > 0)
    {
      mrisp_template = MRISPalloc(scale, IMAGES_PER_SURFACE*noverlays);
      for (sno = 0; sno < noverlays ; sno++)
      {
        sprintf(fname, "%s/../label/%s.%s", surf_dir, hemi, overlays[sno]) ;
        if (MRISreadValues(mris_template, fname)  != NO_ERROR)
          ErrorExit(ERROR_NOFILE,
                    "%s: could not read overlay from %s",
                    Progname, fname) ;
        MRIScopyValuesToCurvature(mris_template) ;
        MRISaverageCurvatures(mris_template, navgs) ;
        MRISnormalizeCurvature(mris_template, which_norm) ;
        fprintf(stderr,
                "computing parameterization for overlay %s...\n",
                fname);
        MRIStoParameterization(mris_template, mrisp_template, scale, sno*3) ;
        MRISPsetFrameVal(mrisp_template, sno*3+1, 1.0) ;
      }
    }
    else
    {
      mrisp_template = MRISPalloc(scale, PARAM_IMAGES);
      for (sno = 0; sno < SURFACES ; sno++)
      {
        if (curvature_names[sno])  /* read in precomputed curvature file */
        {
          sprintf(fname, "%s/%s.%s", surf_dir, hemi, curvature_names[sno]) ;
          if (MRISreadCurvatureFile(mris_template, fname) != NO_ERROR)
            ErrorExit(Gerror,
                      "%s: could not read curvature file '%s'\n",
                      Progname, fname) ;

          /* the two next lines were not in the original code */
          MRISaverageCurvatures(mris_template, navgs) ;
          MRISnormalizeCurvature(mris_template, which_norm) ;
        }
        else                         /* compute curvature of surface */
        {
          sprintf(fname, "%s/%s.%s", surf_dir, hemi, surface_names[sno]) ;
          if (MRISreadVertexPositions(mris_template, fname) != NO_ERROR)
            ErrorExit(ERROR_NOFILE,
                      "%s: could not read surface file %s",
                      Progname, fname) ;

          if (tnbrs > 1)
          {
            MRISresetNeighborhoodSize(mris_template, tnbrs) ;
          }
          MRIScomputeMetricProperties(mris_template) ;
          MRIScomputeSecondFundamentalForm(mris_template) ;
          MRISuseMeanCurvature(mris_template) ;
          MRISaverageCurvatures(mris_template, navgs) ;
          MRISrestoreVertexPositions(mris_template, CANONICAL_VERTICES) ;
          MRISnormalizeCurvature(mris_template, which_norm) ;
        }
        fprintf(stderr,
                "computing parameterization for surface %s...\n",
                fname);
        MRIStoParameterization(mris_template, mrisp_template, scale, sno*3) ;
        MRISPsetFrameVal(mrisp_template, sno*3+1, 1.0) ;
      }
    }
  }
  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) ;
    if (noverlays > 0)
    {
      if (mrisp_template->Ip->num_frame != IMAGES_PER_SURFACE*noverlays)
        ErrorExit(ERROR_BADPARM,
                  "template frames (%d) doesn't match input (%d x %d) = %d\n",
                  mrisp_template->Ip->num_frame, IMAGES_PER_SURFACE,noverlays,
                  IMAGES_PER_SURFACE*noverlays) ;
    }
  }
  if (use_defaults)
  {
    if (*IMAGEFseq_pix(mrisp_template->Ip, 0, 0, 2) <= 1.0)  /* 1st time */
    {
      parms.l_dist = 5.0 ;
      parms.l_corr = 1.0 ;
      parms.l_parea = 0.2 ;
    }
    else   /* subsequent alignments */
    {
      parms.l_dist = 5.0 ;
      parms.l_corr = 1.0 ;
      parms.l_parea = 0.2 ;
    }
  }

  if (nbrs > 1)
  {
    MRISresetNeighborhoodSize(mris, nbrs) ;
  }
  MRISprojectOntoSphere(mris, mris, DEFAULT_RADIUS) ;
  mris->status = MRIS_PARAMETERIZED_SPHERE ;
  MRIScomputeMetricProperties(mris) ;
  if (!FZERO(parms.l_dist))
  {
    MRISscaleDistances(mris, scale) ;
  }
#if 0
  MRISsaveVertexPositions(mris, ORIGINAL_VERTICES) ;
  MRISzeroNegativeAreas(mris) ;
  MRISstoreMetricProperties(mris) ;
#endif
  MRISstoreMeanCurvature(mris) ;  /* use curvature from file */
  MRISsetOriginalFileName(orig_name) ;
  if (inflated_name)
  {
    MRISsetInflatedFileName(inflated_name) ;
  }
  err = MRISreadOriginalProperties(mris, orig_name) ;
  if (err != 0)
  {
    printf("ERROR %d from MRISreadOriginalProperties().\n",err);
    exit(1);
  }

  if (MRISreadCanonicalCoordinates(mris, canon_name) != NO_ERROR)
    ErrorExit(ERROR_BADFILE, "%s: could not read canon surface %s",
              Progname, canon_name) ;

  if (reverse_flag)
  {
    MRISreverse(mris, REVERSE_X, 1) ;
    MRISsaveVertexPositions(mris, TMP_VERTICES) ;
    MRISrestoreVertexPositions(mris, CANONICAL_VERTICES) ;
    MRISreverse(mris, REVERSE_X, 0) ;
    MRISsaveVertexPositions(mris, CANONICAL_VERTICES) ;
    MRISrestoreVertexPositions(mris, TMP_VERTICES) ;
    MRIScomputeMetricProperties(mris) ;
  }
#if 0
  MRISsaveVertexPositions
  (mris, CANONICAL_VERTICES) ;  // uniform spherical positions
#endif
  if (starting_reg_fname)
    if (MRISreadVertexPositions(mris, starting_reg_fname) != NO_ERROR)
    {
      exit(Gerror) ;
    }

  if (multiframes)
  {
    if (use_initial_registration)
      MRISvectorRegister(mris, mrisp_template, &parms, max_passes,
                         min_degrees, max_degrees, nangles) ;
    parms.l_corr=parms.l_pcorr=0.0f;
#if 0
    parms.l_dist = 0.0 ;
    parms.l_corr = 0.0 ;
    parms.l_parea = 0.0 ;
    parms.l_area = 0.0 ;
    parms.l_parea = 0.0f ;
    parms.l_dist = 0.0 ;
    parms.l_corr = 0.0f ;
    parms.l_nlarea = 0.0f ;
    parms.l_pcorr = 0.0f ;
#endif
    MRISvectorRegister(mris,
                       mrisp_template,
                       &parms,
                       max_passes,
                       min_degrees,
                       max_degrees,
                       nangles) ;
  }
  else
  {
    double l_dist = parms.l_dist ;
    if (multi_scale > 0)
    {
      int i ;

      parms.l_dist = l_dist * pow(5.0, (multi_scale-1.0)) ;
      parms.flags |= IPFLAG_NOSCALE_TOL ;
      parms.flags &= ~IP_USE_CURVATURE ;
      for (i = 0 ; i < multi_scale ; i++)
      {
        printf("*************** round %d, l_dist = %2.3f **************\n", i,
               parms.l_dist) ;
        MRISregister(mris, mrisp_template,
                     &parms, max_passes,
                     min_degrees, max_degrees, nangles) ;
        parms.flags |= IP_NO_RIGID_ALIGN ;
        parms.flags &= ~IP_USE_INFLATED ;
        parms.l_dist /= 5 ;
      }

      if (parms.nbhd_size < 0)
      {
        parms.nbhd_size *= -1 ;
        printf("**** starting 2nd epoch, with long-range distances *****\n");
        parms.l_dist = l_dist * pow(5.0, (multi_scale-2.0)) ;
        for (i = 1 ; i < multi_scale ; i++)
        {
          printf("*********** round %d, l_dist = %2.3f *************\n", i,
                 parms.l_dist) ;
          MRISregister(mris, mrisp_template,
                       &parms, max_passes,
                       min_degrees, max_degrees, nangles) ;
          parms.l_dist /= 5 ;
        }
      }
      printf("****** final curvature registration ***************\n") ;
      if (parms.nbhd_size > 0)
      {
        parms.nbhd_size *= -1 ;  // disable long-range stuff
      }
      parms.l_dist *= 5 ;
      parms.flags |= (IP_USE_CURVATURE | IP_NO_SULC);
      MRISregister(mris, mrisp_template,
                   &parms, max_passes,
                   min_degrees, max_degrees, nangles) ;
    }
    else
      MRISregister(mris, mrisp_template,
                   &parms, max_passes,
                   min_degrees, max_degrees, nangles) ;

  }
  if (remove_negative)
  {
    parms.niterations = 1000 ;
    MRISremoveOverlapWithSmoothing(mris,&parms) ;
  }
  fprintf(stderr, "writing registered surface to %s...\n", out_fname) ;
  MRISwrite(mris, out_fname) ;
  if (jacobian_fname)
  {
    MRIScomputeMetricProperties(mris) ;
    compute_area_ratios(mris) ;  /* will put results in v->curv */
#if 0
    MRISwriteArea(mris, jacobian_fname) ;
#else
    MRISwriteCurvature(mris, jacobian_fname) ;
#endif
  }

  msec = TimerStop(&start) ;
  if (Gdiag & DIAG_SHOW)
    printf("registration took %2.2f hours\n",
           (float)msec/(1000.0f*60.0f*60.0f));
  MRISPfree(&mrisp_template) ;
  MRISfree(&mris) ;
  exit(0) ;
  return(0) ;  /* for ansi */
}
Exemplo n.º 21
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) ;
}
Exemplo n.º 22
0
int
main(int argc, char *argv[]) {
  MRI_SURFACE  *mris ;
  char         **av, *curv_name, *surf_name, *hemi, fname[STRLEN],
  *cp, *subject_name, subjects_dir[STRLEN],
  **c1_subjects, **c2_subjects ;
  int          ac, nargs, n, num_class1, num_class2, i, nvertices,
  avgs, max_snr_avgs, nlabels = 0, done ;
  float        **c1_thickness, **c2_thickness, *curvs, *total_mean,
  *c1_mean, *c2_mean,
  *class_mean, *c1_var, *c2_var, *class_var,*pvals,
  **c1_avg_thickness,
  *vbest_snr, *vbest_avgs, *vtotal_var, *vsnr, **c2_avg_thickness,
  *vbest_pvalues, current_min_label_area, current_fthresh ;
  MRI_SP       *mrisp ;
  LABEL        *area, **labels = NULL ;
  FILE         *fp = NULL ;
  double       snr, max_snr ;
  struct timeb start ;
  int          msec, minutes, seconds ;
  double       **c1_label_thickness, **c2_label_thickness ;
  int          *sorted_indices = NULL, vno ;
  float        *test_thickness, *test_avg_thickness ;
  double       label_avg ;

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

  if (write_flag && DIAG_VERBOSE_ON)
    fp = fopen("scalespace.dat", "w") ;

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

  TimerStart(&start) ;

  /* subject_name hemi surface curvature */
  if (argc < 7)
    usage_exit() ;
  if (output_subject == NULL)
    ErrorExit(ERROR_BADPARM,
              "output subject must be specified with -o <subject name>");

  cp = getenv("SUBJECTS_DIR") ;
  if (!cp)
    ErrorExit(ERROR_BADPARM, "%s: SUBJECTS_DIR not defined in environment",
              Progname) ;

  strcpy(subjects_dir, cp) ;

  hemi = argv[1] ;
  surf_name = argv[2] ;
  curv_name = argv[3] ;

#define ARGV_OFFSET 4

  /* first determine the number of subjects in each class */
  num_class1 = 0 ;
  n = ARGV_OFFSET ;
  do {
    num_class1++ ;
    n++ ;
    if (argv[n] == NULL || n >= argc)
      ErrorExit(ERROR_BADPARM, "%s: must spectify ':' between class lists",
                Progname) ;
  } while (argv[n][0] != ':') ;

  /* find  # of vertices in output subject surface */
  sprintf(fname, "%s/%s/surf/%s.%s",
          subjects_dir,output_subject,hemi,surf_name);
  mris = MRISread(fname) ;
  if (!mris)
    ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
              Progname, fname) ;
  nvertices = mris->nvertices ;
  MRISfree(&mris) ;

  total_mean = (float *)calloc(nvertices, sizeof(float)) ;
  if (!total_mean)
    ErrorExit(ERROR_NOMEMORY,
              "%s: could not allocate mean list of %d curvatures",
              Progname, n, nvertices) ;
  c1_mean = (float *)calloc(nvertices, sizeof(float)) ;
  if (!c1_mean)
    ErrorExit(ERROR_NOMEMORY,
              "%s: could not allocate c1 mean list of %d curvatures",
              Progname, n, nvertices) ;
  pvals = (float *)calloc(nvertices, sizeof(float)) ;
  if (!pvals)
    ErrorExit(ERROR_NOMEMORY,
              "%s: could not allocate pvals",
              Progname, n, nvertices) ;
  c2_mean = (float *)calloc(nvertices, sizeof(float)) ;
  if (!c2_mean)
    ErrorExit(ERROR_NOMEMORY,
              "%s: could not allocate c2 mean list of %d curvatures",
              Progname, n, nvertices) ;

  c1_var = (float *)calloc(nvertices, sizeof(float)) ;
  if (!c1_var)
    ErrorExit(ERROR_NOMEMORY,
              "%s: could not allocate c1 var list of %d curvatures",
              Progname, n, nvertices) ;
  c2_var = (float *)calloc(nvertices, sizeof(float)) ;
  if (!c2_var)
    ErrorExit(ERROR_NOMEMORY,
              "%s: could not allocate c2 var list of %d curvatures",
              Progname, n, nvertices) ;

  num_class2 = 0 ;
  n++ ; /* skip ':' */
  if (n >= argc)
    ErrorExit(ERROR_BADPARM, "%s: class2 list empty", Progname) ;
  do {
    num_class2++ ;
    n++ ;
    if (n >= argc)
      break ;
  } while (argv[n] != NULL) ;

  fprintf(stderr, "%d subjects in class 1, %d subjects in class 2\n",
          num_class1, num_class2) ;

  c1_subjects = (char **)calloc(num_class1, sizeof(char *)) ;
  c1_thickness = (float **)calloc(num_class1, sizeof(char *)) ;
  c1_avg_thickness = (float **)calloc(num_class1, sizeof(char *)) ;
  c2_subjects = (char **)calloc(num_class2, sizeof(char *)) ;
  c2_thickness = (float **)calloc(num_class2, sizeof(char *)) ;
  c2_avg_thickness = (float **)calloc(num_class2, sizeof(char *)) ;
  for (n = 0 ; n < num_class1 ; n++) {
    c1_subjects[n] = argv[ARGV_OFFSET+n] ;
    c1_thickness[n] = (float *)calloc(nvertices, sizeof(float)) ;
    c1_avg_thickness[n] = (float *)calloc(nvertices, sizeof(float)) ;
    if (!c1_thickness[n] || !c1_avg_thickness[n])
      ErrorExit(ERROR_NOMEMORY,
                "%s: could not allocate %dth list of %d curvatures",
                Progname, n, nvertices) ;

    strcpy(c1_subjects[n], argv[ARGV_OFFSET+n]) ;
    /*    fprintf(stderr, "class1[%d] - %s\n", n, c1_subjects[n]) ;*/
  }
  i = n+1+ARGV_OFFSET ;  /* starting index */
  for (n = 0 ; n < num_class2 ; n++) {
    c2_subjects[n] = argv[i+n] ;
    c2_thickness[n] = (float *)calloc(nvertices, sizeof(float)) ;
    c2_avg_thickness[n] = (float *)calloc(nvertices, sizeof(float)) ;
    if (!c2_thickness[n] || !c2_avg_thickness[n])
      ErrorExit(ERROR_NOMEMORY,
                "%s: could not allocate %dth list of %d curvatures",
                Progname, n, nvertices) ;
    strcpy(c2_subjects[n], argv[i+n]) ;
    /*    fprintf(stderr, "class2[%d] - %s\n", n, c2_subjects[n]) ;*/
  }

  if (label_name) {
    area = LabelRead(output_subject, label_name) ;
    if (!area)
      ErrorExit(ERROR_NOFILE, "%s: could not read label %s", Progname,
                label_name) ;
  } else
    area = NULL ;

  if (read_dir) {
    sprintf(fname, "%s/%s/surf/%s.%s",
            subjects_dir,output_subject,hemi,surf_name);
    mris = MRISread(fname) ;
    if (!mris)
      ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
                Progname, fname) ;
    MRISsaveVertexPositions(mris, CANONICAL_VERTICES) ;

    /* real all the curvatures in for group1 */
    for (n = 0 ; n < num_class1+num_class2 ; n++) {
      /* transform each subject's curvature into the output subject's space */
      subject_name = n < num_class1 ? c1_subjects[n]:c2_subjects[n-num_class1];
      fprintf(stderr, "reading subject %d of %d: %s\n",
              n+1, num_class1+num_class2, subject_name) ;
      sprintf(fname, "%s/%s.%s", read_dir,hemi,subject_name);
      if (MRISreadValues(mris, fname) != NO_ERROR)
        ErrorExit(Gerror,
                  "%s: could not read curvature file %s",Progname,fname);
      if (area)
        MRISmaskNotLabel(mris, area) ;
      curvs = (n < num_class1) ? c1_thickness[n] : c2_thickness[n-num_class1] ;
      class_mean = (n < num_class1) ? c1_mean : c2_mean ;
      class_var = (n < num_class1) ? c1_var : c2_var ;
      MRISexportValVector(mris, curvs) ;
      cvector_accumulate(curvs, total_mean, nvertices) ;
      cvector_accumulate(curvs, class_mean, nvertices) ;
      cvector_accumulate_square(curvs, class_var, nvertices) ;
    }
  } else {

    /* real all the curvatures in for group1 */
    for (n = 0 ; n < num_class1+num_class2 ; n++) {
      /* transform each subject's curvature into the output subject's space */
      subject_name = n < num_class1 ? c1_subjects[n]:c2_subjects[n-num_class1];
      fprintf(stderr, "reading subject %d of %d: %s\n",
              n+1, num_class1+num_class2, subject_name) ;
      sprintf(fname, "%s/%s/surf/%s.%s",
              subjects_dir,subject_name,hemi,surf_name);
      mris = MRISread(fname) ;
      if (!mris)
        ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
                  Progname, fname) ;
      MRISsaveVertexPositions(mris, CANONICAL_VERTICES) ;
      if (strchr(curv_name, '/') != NULL)
        strcpy(fname, curv_name) ;  /* full path specified */
      else
        sprintf(fname,"%s/%s/surf/%s.%s",
                subjects_dir,subject_name,hemi,curv_name);
      if (MRISreadCurvatureFile(mris, fname) != NO_ERROR)
        ErrorExit(Gerror,"%s: could no read curvature file %s",Progname,fname);
      mrisp = MRIStoParameterization(mris, NULL, 1, 0) ;
      MRISfree(&mris) ;

      sprintf(fname, "%s/%s/surf/%s.%s",
              subjects_dir,output_subject,hemi,surf_name);
      mris = MRISread(fname) ;
      if (!mris)
        ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
                  Progname, fname) ;
      MRISfromParameterization(mrisp, mris, 0) ;
      if (area)
        MRISmaskNotLabel(mris, area) ;
      curvs = (n < num_class1) ? c1_thickness[n] : c2_thickness[n-num_class1] ;
      class_mean = (n < num_class1) ? c1_mean : c2_mean ;
      class_var = (n < num_class1) ? c1_var : c2_var ;
      MRISextractCurvatureVector(mris, curvs) ;
      cvector_accumulate(curvs, total_mean, nvertices) ;
      cvector_accumulate(curvs, class_mean, nvertices) ;
      cvector_accumulate_square(curvs, class_var, nvertices) ;
      MRISPfree(&mrisp) ;
      MRISfree(&mris) ;
    }
  }

  /* compute within-group means, and total mean */
  cvector_normalize(total_mean, num_class1+num_class2, nvertices) ;
  cvector_normalize(c1_mean, num_class1, nvertices) ;
  cvector_normalize(c2_mean, num_class2, nvertices) ;
  cvector_compute_variance(c1_var, c1_mean, num_class1, nvertices) ;
  cvector_compute_variance(c2_var, c2_mean, num_class2, nvertices) ;
  cvector_compute_t_test(c1_mean, c1_var, c2_mean, c2_var,
                         num_class1, num_class2, pvals, nvertices) ;

  sprintf(fname, "%s/%s/surf/%s.%s",
          subjects_dir,output_subject,hemi,surf_name);
  fprintf(stderr, "reading output surface %s...\n", fname) ;
  mris = MRISread(fname) ;
  if (!mris)
    ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
              Progname, fname) ;

  if (area)
    MRISripNotLabel(mris, area) ;
  vbest_snr = cvector_alloc(nvertices) ;
  vbest_pvalues = cvector_alloc(nvertices) ;
  vbest_avgs = cvector_alloc(nvertices) ;
  vtotal_var = cvector_alloc(nvertices) ;
  vsnr = cvector_alloc(nvertices) ;

  if (read_dir == NULL)  /* recompute everything */
  {
    if (use_buggy_snr)
      cvector_multiply_variances(c1_var, c2_var, num_class1, num_class2,
                                 vtotal_var, nvertices) ;
    else
      cvector_add_variances(c1_var, c2_var, num_class1, num_class2,
                            vtotal_var, nvertices) ;
    if (use_no_distribution)
      snr = cvector_compute_dist_free_snr(c1_thickness, num_class1,
                                          c2_thickness, num_class2,
                                          c1_mean, c2_mean,
                                          vsnr, nvertices, &i);
    else
      snr = cvector_compute_snr(c1_mean, c2_mean, vtotal_var, vsnr, nvertices,
                                &i, 0.0f);
    fprintf(stderr,
            "raw SNR %2.2f, n=%2.4f, d=%2.4f, vno=%d\n",
            sqrt(snr), c1_mean[i]-c2_mean[i], sqrt(vtotal_var[i]), i) ;
    max_snr = snr ;
    max_snr_avgs = 0 ;
    cvector_track_best_snr(vsnr, vbest_snr, vbest_avgs, 0, nvertices) ;

    for (n = 0 ; n < num_class1 ; n++)
      cvector_copy(c1_thickness[n], c1_avg_thickness[n], nvertices) ;
    for (n = 0 ; n < num_class2 ; n++)
      cvector_copy(c2_thickness[n], c2_avg_thickness[n], nvertices) ;

    /* now incrementally average the data, keeping track of the best
       snr at each location, and at what scale it occurred. vbest_avgs
       and vbest_snr will contain the scale and the snr at that scale.
    */
    for (avgs = 1 ; avgs <= max_avgs ; avgs++) {
      /* c?_avg_thickness is the thickness at the current scale */
      if (!(avgs % 50))
        fprintf(stderr, "testing %d averages...\n", avgs) ;
      cvector_clear(c1_mean, nvertices) ;
      cvector_clear(c2_mean, nvertices) ;
      cvector_clear(c1_var, nvertices) ;
      cvector_clear(c2_var, nvertices) ;
      cvector_clear(total_mean, nvertices) ;
      for (n = 0 ; n < num_class1 ; n++) {
        MRISimportCurvatureVector(mris, c1_avg_thickness[n]) ;
        MRISaverageCurvatures(mris, 1) ;
        MRISextractCurvatureVector(mris, c1_avg_thickness[n]) ;
        cvector_accumulate(c1_avg_thickness[n], total_mean, nvertices) ;
        cvector_accumulate(c1_avg_thickness[n], c1_mean, nvertices) ;
        cvector_accumulate_square(c1_avg_thickness[n], c1_var, nvertices) ;
      }
      for (n = 0 ; n < num_class2 ; n++) {
        MRISimportCurvatureVector(mris, c2_avg_thickness[n]) ;
        MRISaverageCurvatures(mris, 1) ;
        MRISextractCurvatureVector(mris, c2_avg_thickness[n]) ;
        cvector_accumulate(c2_avg_thickness[n], total_mean, nvertices) ;
        cvector_accumulate(c2_avg_thickness[n], c2_mean, nvertices) ;
        cvector_accumulate_square(c2_avg_thickness[n], c2_var, nvertices) ;
      }
      cvector_normalize(total_mean, num_class1+num_class2, nvertices) ;
      cvector_normalize(c1_mean, num_class1, nvertices) ;
      cvector_normalize(c2_mean, num_class2, nvertices) ;
      cvector_compute_variance(c1_var, c1_mean, num_class1, nvertices) ;
      cvector_compute_variance(c2_var, c2_mean, num_class2, nvertices) ;
      if (use_buggy_snr)
        cvector_multiply_variances(c1_var, c2_var, num_class1, num_class2,
                                   vtotal_var, nvertices) ;
      else
        cvector_add_variances(c1_var, c2_var, num_class1, num_class2,
                              vtotal_var, nvertices) ;
      if (use_no_distribution)
        snr =
          cvector_compute_dist_free_snr(c1_avg_thickness,num_class1,
                                        c2_avg_thickness, num_class2, c1_mean,
                                        c2_mean, vsnr, nvertices, &i);
      else
        snr =
          cvector_compute_snr(c1_mean, c2_mean, vtotal_var, vsnr, nvertices,&i,
                              bonferroni ? log((double)avgs) : 0.0f);
      if (write_flag && DIAG_VERBOSE_ON) {
        fprintf(fp, "%d %2.1f  %2.2f %2.2f %2.2f ",
                avgs, sqrt((float)avgs), sqrt(snr), c1_mean[i]-c2_mean[i],
                sqrt(vtotal_var[i])) ;
        fflush(fp) ;
        for (n = 0 ; n < num_class1 ; n++)
          fprintf(fp, "%2.2f ", c1_avg_thickness[n][i]) ;
        for (n = 0 ; n < num_class2 ; n++)
          fprintf(fp, "%2.2f ", c2_avg_thickness[n][i]) ;
        fprintf(fp, "\n") ;
        fclose(fp) ;
      }
      if (snr > max_snr) {
        fprintf(stderr,
                "new max SNR found at avgs=%d (%2.1f mm)=%2.1f, n=%2.4f, "
                "d=%2.4f, vno=%d\n",
                avgs, sqrt((float)avgs), sqrt(snr), c1_mean[i]-c2_mean[i],
                sqrt(vtotal_var[i]), i) ;
        max_snr = snr ;
        max_snr_avgs = avgs ;
      }
      cvector_track_best_snr(vsnr, vbest_snr, vbest_avgs, avgs, nvertices) ;
    }
    if (compute_stats)
      cvector_compute_t(vbest_snr, vbest_pvalues,num_class1+num_class2,
                        nvertices) ;
    printf("max snr=%2.2f at %d averages\n", max_snr, max_snr_avgs) ;
    if (write_flag) {
      MRISimportValVector(mris, vbest_snr) ;
      sprintf(fname, "./%s.%s_best_snr", hemi,prefix) ;
      MRISwriteValues(mris, fname) ;
      MRISimportValVector(mris, vbest_avgs) ;
      sprintf(fname, "./%s.%s_best_avgs", hemi, prefix) ;
      MRISwriteValues(mris, fname) ;
      if (compute_stats) {
        MRISimportValVector(mris, vbest_pvalues) ;
        sprintf(fname, "./%s.%s_best_pval", hemi,prefix) ;
        MRISwriteValues(mris, fname) ;
      }
    }
  }
  else  /* read from directory containing precomputed optimal values */
  {
    sprintf(fname, "%s/%s.%s_best_snr", read_dir, hemi, prefix) ;
    if (MRISreadValues(mris, fname) != NO_ERROR)
      ErrorExit(Gerror, "%s: MRISreadValues(%s) failed",Progname,fname) ;
    MRISexportValVector(mris, vbest_snr) ;

    sprintf(fname, "%s/%s.%s_best_avgs", read_dir, hemi, prefix) ;
    if (MRISreadValues(mris, fname) != NO_ERROR)
      ErrorExit(Gerror, "%s: MRISreadValues(%s) failed",Progname,fname) ;
    MRISexportValVector(mris, vbest_avgs) ;
  }

  if (write_dir) {
    sprintf(fname, "%s/%s.%s_best_snr", write_dir, hemi,prefix) ;
    MRISimportValVector(mris, vbest_snr) ;
    if (MRISwriteValues(mris, fname) != NO_ERROR)
      ErrorExit(Gerror, "%s: MRISwriteValues(%s) failed",Progname,fname) ;

    sprintf(fname, "%s/%s.%s_best_avgs", write_dir, hemi, prefix) ;
    MRISimportValVector(mris, vbest_avgs) ;
    if (MRISwriteValues(mris, fname) != NO_ERROR)
      ErrorExit(Gerror, "%s: MRISwriteValues(%s) failed",Progname,fname) ;
  }

  if (nsort < -1)
    nsort = mris->nvertices ;

  if (nsort <= 0) {
    nlabels = 0 ;
    current_min_label_area = min_label_area ;
    for (done = 0, current_fthresh = fthresh ;
         !FZERO(current_fthresh) && !done ;
         current_fthresh *= 0.95) {
      int   npos_labels, nneg_labels ;
      LABEL **pos_labels, **neg_labels ;

      for (current_min_label_area = min_label_area ;
           current_min_label_area > 0.5 ;
           current_min_label_area *= 0.75) {
        MRISclearMarks(mris) ;
        sprintf(fname, "%s-%s_thickness", hemi, prefix ? prefix : "") ;
        mark_thresholded_vertices(mris, vbest_snr, vbest_avgs,current_fthresh);
        segment_and_write_labels(output_subject, fname, mris,
                                 &pos_labels, &npos_labels, 0,
                                 current_min_label_area) ;
        MRISclearMarks(mris) ;
        mark_thresholded_vertices(mris, vbest_snr,vbest_avgs,-current_fthresh);
        segment_and_write_labels(output_subject, fname, mris, &neg_labels,
                                 &nneg_labels, npos_labels,
                                 current_min_label_area) ;

        nlabels = nneg_labels + npos_labels ;
        if (nlabels) {
          labels = (LABEL **)calloc(nlabels, sizeof(LABEL *)) ;
          for (i = 0 ; i < npos_labels ; i++)
            labels[i] = pos_labels[i] ;
          for (i = 0 ; i < nneg_labels ; i++)
            labels[i+npos_labels] = neg_labels[i] ;
          free(pos_labels) ;
          free(neg_labels) ;
        }
        done = (nlabels >= min_labels) ;
        if (done)  /* found enough points */
          break ;

        /* couldn't find enough  points - free stuff and try again */
        for (i = 0 ; i < nlabels ; i++)
          LabelFree(&labels[i]) ;
        if (nlabels)
          free(labels) ;
#if 0
        fprintf(stderr,"%d labels found (min %d), reducing constraints...\n",
                nlabels, min_labels) ;
#endif
      }
    }

    printf("%d labels found with F > %2.1f and area > %2.0f\n",
           nlabels, current_fthresh, current_min_label_area) ;
    for (i = 0 ; i < nlabels ; i++)
      fprintf(stderr, "label %d: %d points, %2.1f mm\n",
              i, labels[i]->n_points, LabelArea(labels[i], mris)) ;
  }

  /* read or compute thickness at optimal scale and put it into
     c?_avg_thickness.
  */
  if (!read_dir) {
    fprintf(stderr, "extracting thickness at optimal scale...\n") ;

    /* now build feature vectors for each subject */
    extract_thickness_at_best_scale(mris, c1_avg_thickness, vbest_avgs,
                                    c1_thickness, nvertices, num_class1);
    fprintf(stderr, "extracting thickness for class 2...\n") ;
    extract_thickness_at_best_scale(mris, c2_avg_thickness, vbest_avgs,
                                    c2_thickness, nvertices, num_class2);
  } else  /* read in precomputed optimal thicknesses */
  {
    char fname[STRLEN] ;

    fprintf(stderr, "reading precomputed thickness vectors\n") ;
    for (n = 0 ; n < num_class1 ; n++) {
      sprintf(fname, "%s/%s.%s", read_dir, hemi, argv[ARGV_OFFSET+n]) ;
      fprintf(stderr, "reading thickness vector from %s...\n", fname) ;
      if (MRISreadValues(mris, fname) != NO_ERROR)
        ErrorExit(Gerror, "%s: could not read thickness file %s",
                  Progname,fname) ;
      MRISexportValVector(mris, c1_avg_thickness[n]) ;
    }
    for (n = 0 ; n < num_class2 ; n++) {
      sprintf(fname, "%s/%s.%s", read_dir, hemi,
              argv[n+num_class1+1+ARGV_OFFSET]) ;
      fprintf(stderr, "reading curvature vector from %s...\n", fname) ;
      if (MRISreadValues(mris, fname) != NO_ERROR)
        ErrorExit(Gerror, "%s: could not read thickness file %s",
                  Progname,fname) ;
      MRISexportValVector(mris, c2_avg_thickness[n]) ;
    }
  }

  if (write_dir)   /* write out optimal thicknesses */
  {
    char fname[STRLEN] ;

    for (n = 0 ; n < num_class1 ; n++) {
      sprintf(fname, "%s/%s.%s", write_dir, hemi, argv[ARGV_OFFSET+n]) ;
      fprintf(stderr, "writing curvature vector to %s...\n", fname) ;
      MRISimportValVector(mris, c1_avg_thickness[n]) ;
      MRISwriteValues(mris, fname) ;
    }
    for (n = 0 ; n < num_class2 ; n++) {
      sprintf(fname, "%s/%s.%s", write_dir, hemi,
              argv[n+num_class1+1+ARGV_OFFSET]) ;
      fprintf(stderr, "writing curvature vector to %s...\n", fname) ;
      MRISimportValVector(mris, c2_avg_thickness[n]) ;
      MRISwriteValues(mris, fname) ;
    }
  }


  /* should free c?_thickness here */

  if (nsort <= 0) {
    /* We have the thickness values at the most powerful scale stored for
       each subject in the c1_avg_thickness and c2_avg_thickness vectors.
       Now collapse them across each label and build  feature vector for
       classification.
    */
    c1_label_thickness = (double **)calloc(num_class1, sizeof(double *)) ;
    c2_label_thickness = (double **)calloc(num_class2, sizeof(double *)) ;
    for (n = 0 ; n < num_class1 ; n++)
      c1_label_thickness[n] = (double *)calloc(nlabels, sizeof(double)) ;
    for (n = 0 ; n < num_class2 ; n++)
      c2_label_thickness[n] = (double *)calloc(nlabels, sizeof(double)) ;

    fprintf(stderr, "collapsing thicknesses within labels for class 1\n") ;
    for (n = 0 ; n < num_class1 ; n++)
      for (i = 0 ; i < nlabels ; i++)
        c1_label_thickness[n][i] =
          cvector_average_in_label(c1_avg_thickness[n], labels[i], nvertices) ;
    fprintf(stderr, "collapsing thicknesses within labels for class 2\n") ;
    for (n = 0 ; n < num_class2 ; n++)
      for (i = 0 ; i < nlabels ; i++)
        c2_label_thickness[n][i] =
          cvector_average_in_label(c2_avg_thickness[n], labels[i], nvertices) ;
    sprintf(fname, "%s_%s_class1.dat", hemi,prefix) ;
    fprintf(stderr, "writing class 1 info to %s...\n", fname) ;
    fp = fopen(fname, "w") ;
    for (i = 0 ; i < nlabels ; i++)  /* for each row */
    {
      for (n = 0 ; n < num_class1 ; n++)  /* for each column */
        fprintf(fp, "%2.2f  ", c1_label_thickness[n][i]) ;
      fprintf(fp, "\n") ;
    }
    fclose(fp) ;

    sprintf(fname, "%s_%s_class2.dat", hemi,prefix) ;
    fprintf(stderr, "writing class 2 info to %s...\n", fname) ;
    fp = fopen(fname, "w") ;
    for (i = 0 ; i < nlabels ; i++) {
      for (n = 0 ; n < num_class2 ; n++)
        fprintf(fp, "%2.2f  ", c2_label_thickness[n][i]) ;
      fprintf(fp, "\n") ;
    }
    fclose(fp) ;
  } else {
    sorted_indices = cvector_sort(vbest_snr, nvertices) ;
    vno = sorted_indices[0] ;
    write_vertex_data("c1.dat", vno, c1_avg_thickness,num_class1);
    write_vertex_data("c2.dat", vno, c2_avg_thickness,num_class2);
    printf("sorting complete\n") ;

    /* re-write class means at these locations */
    sprintf(fname, "%s_%s_class1.dat", hemi,prefix) ;
    fprintf(stderr, "writing class 1 info to %s...\n", fname) ;
    fp = fopen(fname, "w") ;
    for (i = 0 ; i < nsort ; i++) {
      for (n = 0 ; n < num_class1 ; n++)
        fprintf(fp, "%2.2f  ", c1_avg_thickness[n][sorted_indices[i]]) ;
      fprintf(fp, "\n") ;
    }
    fclose(fp) ;
    sprintf(fname, "%s_%s_class2.dat", hemi,prefix) ;
    fprintf(stderr, "writing class 2 info to %s...\n", fname) ;
    fp = fopen(fname, "w") ;
    for (i = 0 ; i < nsort ; i++) {
      for (n = 0 ; n < num_class2 ; n++)
        fprintf(fp, "%2.2f  ", c2_avg_thickness[n][sorted_indices[i]]) ;
      fprintf(fp, "\n") ;
    }
    fclose(fp) ;
  }

  if (test_subject) {
    test_thickness = cvector_alloc(nvertices) ;
    test_avg_thickness = cvector_alloc(nvertices) ;
    MRISfree(&mris) ;
    fprintf(stderr, "reading subject %s\n", test_subject) ;
    sprintf(fname, "%s/%s/surf/%s.%s",
            subjects_dir,test_subject,hemi,surf_name);
    mris = MRISread(fname) ;
    if (!mris)
      ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
                Progname, fname) ;
    MRISsaveVertexPositions(mris, CANONICAL_VERTICES) ;
    if (strchr(curv_name, '/') != NULL)
      strcpy(fname, curv_name) ;  /* full path specified */
    else
      sprintf(fname,"%s/%s/surf/%s.%s",
              subjects_dir,test_subject,hemi,curv_name);
    if (MRISreadCurvatureFile(mris, fname) != NO_ERROR)
      ErrorExit(Gerror,"%s: could no read curvature file %s",Progname,fname);
    mrisp = MRIStoParameterization(mris, NULL, 1, 0) ;
    MRISfree(&mris) ;

    sprintf(fname, "%s/%s/surf/%s.%s",
            subjects_dir,output_subject,hemi,surf_name);
    mris = MRISread(fname) ;
    if (!mris)
      ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
                Progname, fname) ;
    MRISfromParameterization(mrisp, mris, 0) ;
    if (area)
      MRISmaskNotLabel(mris, area) ;
    MRISextractCurvatureVector(mris, test_thickness) ;
    for (avgs = 0 ; avgs <= max_avgs ; avgs++) {
      cvector_extract_best_avg(vbest_avgs, test_thickness,test_avg_thickness,
                               avgs-1, nvertices) ;
      MRISimportCurvatureVector(mris, test_thickness) ;
      MRISaverageCurvatures(mris, 1) ;
      MRISextractCurvatureVector(mris, test_thickness) ;
    }

    if (nsort <= 0) {
      sprintf(fname, "%s_%s.dat", hemi,test_subject) ;
      fprintf(stderr, "writing test subject feature vector to %s...\n",
              fname) ;
      fp = fopen(fname, "w") ;
      for (i = 0 ; i < nlabels ; i++)  /* for each row */
      {
        label_avg =
          cvector_average_in_label(test_avg_thickness, labels[i], nvertices) ;
        fprintf(fp, "%2.2f\n", label_avg) ;
      }
      fclose(fp) ;
    } else   /* use sorting instead of connected areas */
    {
      double classification, offset, w ;
      int    total_correct, total_wrong, first_wrong, vno ;


      sprintf(fname, "%s_%s.dat", hemi,test_subject) ;
      fprintf(stderr, "writing test subject feature vector to %s...\n",
              fname) ;
      fp = fopen(fname, "w") ;

      first_wrong = -1 ;
      total_wrong = total_correct = 0 ;
      for (i = 0 ; i < nsort ; i++) {
        vno = sorted_indices[i] ;
        fprintf(fp, "%2.2f\n ", test_avg_thickness[sorted_indices[i]]) ;
        offset = (c1_mean[vno]+c2_mean[vno])/2.0 ;
        w = (c1_mean[vno]-c2_mean[vno]) ;
        classification = (test_avg_thickness[vno] - offset) * w ;

        if (((classification < 0) && (true_class == 1)) ||
            ((classification > 0) && (true_class == 2))) {
          total_wrong++ ;
          if (first_wrong < 0)
            first_wrong = i ;
        } else
          total_correct++ ;
      }
      fclose(fp) ;
      fprintf(stderr, "%d of %d correct = %2.1f%% (first wrong %d (%d)),"
              "min snr=%2.1f\n",
              total_correct, total_correct+total_wrong,
              100.0*total_correct / (total_correct+total_wrong),
              first_wrong, first_wrong >= 0 ? sorted_indices[first_wrong]:-1,
              vbest_snr[sorted_indices[nsort-1]]) ;

      if (first_wrong >= 0) {
        write_vertex_data("c1w.dat", sorted_indices[first_wrong],
                          c1_avg_thickness,num_class1);
        write_vertex_data("c2w.dat", sorted_indices[first_wrong],
                          c2_avg_thickness,num_class2);
      }
    }
  }

  msec = TimerStop(&start) ;
  free(total_mean);
  free(c1_mean) ;
  free(c2_mean) ;
  free(c1_var);
  free(c2_var);
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  fprintf(stderr, "classification took %d minutes and %d seconds.\n",
          minutes, seconds) ;
  exit(0) ;
  return(0) ;  /* for ansi */
}
Exemplo n.º 23
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 */
}
Exemplo n.º 24
0
FCD_DATA   *
FCDloadData(char *sdir, char *subject)
{
  FCD_DATA    *fcd ;
  char        fname[STRLEN] ;
  MRI         *mri_interior, *mri_dist, *mri_int_lh, *mri_int_rh, *mri_pvals ;

  fcd = (FCD_DATA *)calloc(1, sizeof(FCD_DATA)) ;

  sprintf(fname, "%s/%s/surf/lh.white", sdir, subject) ;
  fcd->mris_lh = MRISread(fname) ;
  if (fcd->mris_lh == NULL)
  {
    ErrorExit(ERROR_NOFILE, "FCDloadData: couldn't load %s", fname) ;
  }
  MRISsaveVertexPositions(fcd->mris_lh, WHITE_VERTICES) ;
  if (MRISreadPialCoordinates(fcd->mris_lh, "pial") != NO_ERROR)
  {
    ErrorExit(ERROR_NOFILE, "FCDloadData: couldn't load lh pial vertices") ;
  }

  sprintf(fname, "%s/%s/surf/lh.pial", sdir, subject) ;
  fcd->mris_lh_pial = MRISread(fname) ;
  if (fcd->mris_lh_pial == NULL)
  {
    ErrorExit(ERROR_NOFILE, "FCDloadData: couldn't load %s", fname) ;
  }

  sprintf(fname, "%s/%s/surf/lh.sphere.d1.left_right", sdir, subject) ;
  fcd->mris_lh_sphere_d1 = MRISread(fname) ;
  if (fcd->mris_lh_sphere_d1 == NULL)
  {
    ErrorExit(ERROR_NOFILE, "FCDloadData: couldn't load %s", fname) ;
  }

  exec_progress_callback(1, 12, 0, 1) ;
  sprintf(fname, "%s/%s/surf/rh.white", sdir, subject) ;
  fcd->mris_rh = MRISread(fname) ;
  if (fcd->mris_rh == NULL)
  {
    ErrorExit(ERROR_NOFILE, "FCDloadData: couldn't load %s", fname) ;
  }
  MRISsaveVertexPositions(fcd->mris_rh, WHITE_VERTICES) ;
  if (MRISreadPialCoordinates(fcd->mris_rh, "pial") != NO_ERROR)
  {
    ErrorExit(ERROR_NOFILE, "FCDloadData: couldn't load rh pial vertices") ;
  }

  sprintf(fname, "%s/%s/surf/rh.pial", sdir, subject) ;
  fcd->mris_rh_pial = MRISread(fname) ;
  if (fcd->mris_rh_pial == NULL)
  {
    ErrorExit(ERROR_NOFILE, "FCDloadData: couldn't load %s", fname) ;
  }

  sprintf(fname, "%s/%s/surf/rh.sphere.d1.left_right", sdir, subject) ;
  fcd->mris_rh_sphere_d1 = MRISread(fname) ;
  if (fcd->mris_rh_sphere_d1 == NULL)
  {
    ErrorExit(ERROR_NOFILE, "FCDloadData: couldn't load %s", fname) ;
  }

  exec_progress_callback(2, 12, 0, 1) ;
  sprintf(fname, "%s/%s/mri/aseg.mgz", sdir, subject) ;
  fcd->mri_aseg = MRIread(fname) ;
  if (fcd->mri_aseg == NULL)
  {
    ErrorExit(ERROR_NOFILE, "FCDloadData: couldn't load %s", fname) ;
  }

  exec_progress_callback(3, 12, 0, 1) ;
  sprintf(fname, "%s/%s/mri/aparc+aseg.mgz", sdir, subject) ;
  fcd->mri_aparc = MRIread(fname) ;
  if (fcd->mri_aparc == NULL)
  {
    ErrorExit(ERROR_NOFILE, "FCDloadData: couldn't load %s", fname) ;
  }

  exec_progress_callback(4, 12, 0, 1) ;
  fcd->mri_flair = NULL;
  sprintf(fname, "%s/%s/mri/flair.reg.norm.mgz", sdir, subject) ; 
  if ( ! FileExists(fname))
  {
    sprintf(fname, "%s/%s/mri/FLAIR.mgz", sdir, subject) ; 
    if ( ! FileExists(fname))
    {
      sprintf(fname, "%s/%s/mri/FLAIRax.mgz", sdir, subject) ; 
      if ( ! FileExists(fname))
      {
        sprintf(fname, "%s/%s/mri/FLAIRcor.mgz", sdir, subject) ; 
        if ( ! FileExists(fname))
        {
          sprintf(fname, " ");
        }
      }
    }
  }
  if (strlen(fname) > 1)
  {
    fcd->mri_flair = MRIread(fname) ;
    if (fcd->mri_flair == NULL)
    {
      ErrorExit(ERROR_NOFILE, "FCDloadData: couldn't load $s", fname) ;
    }
  }

  fcd->mri_t2 = NULL;
  sprintf(fname, "%s/%s/mri/T2.mgz", sdir, subject) ; 
  if ( ! FileExists(fname))
  {
    sprintf(fname, "%s/%s/mri/T2ax.mgz", sdir, subject) ; 
    if ( ! FileExists(fname))
    {
      sprintf(fname, "%s/%s/mri/T2cor.mgz", sdir, subject) ; 
      if ( ! FileExists(fname))
      {
        sprintf(fname, " ");
      }
    }
  }
  if (strlen(fname) > 1)
  {
    fcd->mri_t2 = MRIread(fname) ;
    if (fcd->mri_t2 == NULL)
    {
      ErrorExit(ERROR_NOFILE, "FCDloadData: couldn't load $s", fname) ;
    }
  }

  exec_progress_callback(5, 12, 0, 1) ;
  sprintf(fname, "%s/%s/mri/norm.mgz", sdir, subject) ;
  fcd->mri_norm = MRIread(fname) ;
  if (fcd->mri_norm == NULL)
  {
    ErrorExit(ERROR_NOFILE, "FCDloadData: couldn't load %s", fname) ;
  }

  fcd->mri_thickness_increase = 
    MRIcloneDifferentType(fcd->mri_aseg, MRI_FLOAT) ;
  fcd->mri_thickness_decrease = 
    MRIcloneDifferentType(fcd->mri_aseg, MRI_FLOAT) ;
  fcd->mri_thickness_difference = MRIadd(fcd->mri_thickness_increase, fcd->mri_thickness_decrease, NULL);

  exec_progress_callback(6, 12, 0, 1) ;
  sprintf(fname, "%s/%s/surf/lh.rh.thickness.smooth0.mgz", sdir, subject) ;
  fcd->rh_thickness_on_lh = MRIread(fname) ;
  if (fcd->mri_aseg == NULL)
  {
    ErrorExit(ERROR_NOFILE, "FCDloadData: couldn't load %s", fname) ;
  }

  exec_progress_callback(7, 12, 0, 1) ;
  sprintf(fname, "%s/%s/surf/rh.thickness.mgz", sdir, subject) ;
  fcd->rh_thickness_on_rh = MRIread(fname) ;
  if (fcd->rh_thickness_on_rh == NULL)
  {
    ErrorExit(ERROR_NOFILE, "FCDloadData: couldn't load %s", fname) ;
  }

  exec_progress_callback(8, 12, 0, 1) ;
  sprintf(fname, "%s/%s/surf/lh.thickness.mgz", sdir, subject) ;
  fcd->lh_thickness_on_lh = MRIread(fname) ;
  if (fcd->lh_thickness_on_lh == NULL)
  {
    ErrorExit(ERROR_NOFILE, "FCDloadData: couldn't load %s", fname) ;
  }

  exec_progress_callback(9, 12, 0, 1) ;
  sprintf(fname, "%s/%s/surf/rh.lh.thickness.smooth0.mgz", sdir, subject) ;
  if ( ! FileExists(fname))
  {
    sprintf(fname, "%s/%s/surf/rh.lh.thickness.mgz", sdir, subject) ;
    if (fcd->lh_thickness_on_rh == NULL)
    {
      ErrorExit(ERROR_NOFILE, "FCDloadData: couldn't load %s", fname) ;
    }
  }
  fcd->lh_thickness_on_rh = MRIread(fname) ;

  exec_progress_callback(10, 12, 0, 1) ;
  mri_int_lh = MRIclone(fcd->mri_norm, NULL) ;
  mri_int_rh = MRIclone(fcd->mri_norm, NULL) ;
  mri_interior = MRIclone(fcd->mri_norm, NULL) ;
  mri_dist = MRIcloneDifferentType(mri_interior, MRI_FLOAT) ;
  MRISrestoreVertexPositions(fcd->mris_lh, PIAL_VERTICES) ;
  MRISrestoreVertexPositions(fcd->mris_rh, PIAL_VERTICES) ;
  MRISfillInterior(fcd->mris_lh, mri_interior->xsize, mri_int_lh) ;
  MRISfillInterior(fcd->mris_rh, mri_interior->xsize, mri_int_rh) ;

  exec_progress_callback(11, 12, 0, 1) ;
  MRIor(mri_int_lh, mri_int_rh, mri_interior, 0) ;
  MRIfree(&mri_int_lh) ;
  MRIfree(&mri_int_rh) ;
  MRIbinarize(mri_interior, mri_interior, 1, 0, 1) ;
  if (Gdiag & DIAG_WRITE)
  {
    MRIwrite(mri_interior, "int.mgz") ;
  }
  MRIdistanceTransform(mri_interior,
                       mri_dist,
                       1,
                       2*MAX_DIST,
                       DTRANS_MODE_SIGNED,
                       NULL);
  if (Gdiag & DIAG_WRITE)
  {
    MRIwrite(mri_dist, "dist.mgz") ;
  }
  mri_pvals = build_distance_by_intensity_histo(fcd->mri_norm, 
                                                mri_dist,
                                                fcd->mri_aseg,
                                                DIST_SPACING,
                                                MAX_DIST) ;
  exec_progress_callback(12, 12, 0, 1) ;
  augment_thicknesses(fcd, mri_pvals, 1.5, 5, 1) ;

  MRISrestoreVertexPositions(fcd->mris_lh, WHITE_VERTICES) ;
  MRISrestoreVertexPositions(fcd->mris_rh, WHITE_VERTICES) ;
  MRIfree(&mri_dist) ;
  MRIfree(&mri_interior) ;
  MRIfree(&mri_pvals) ;

  return(fcd) ;
}