/*----------------------------------------------------------------------
  Parameters:

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

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

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

  TimerStart(&start) ;

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

  if (argc < 3)
    usage_exit(1) ;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

                // Check whether this point is in the ribbon
                if (UseRibbon)
                {
                    lhRibbonVal = MRIgetVoxVal(lhRibbon,c,r,s,0);
                    rhRibbonVal = MRIgetVoxVal(rhRibbon,c,r,s,0);
                    if (IsCortex)
                    {
                        // ASeg says it's in cortex
                        if (lhRibbonVal < 0.5 && rhRibbonVal < 0.5)
                        {
                            // but it is not part of the ribbon,
                            // so set it to unknown (0) and go to the next voxel.
                            MRIsetVoxVal(ASeg,c,r,s,0,0);
                            continue;
                        }
                    }
                }

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

                // Get the index of the closest vertex in the
                // lh.white, lh.pial, rh.white, rh.pial
                if (UseHash)
                {
                    lhwvtx = MHTfindClosestVertexNo(lhwhite_hash,lhwhite,&vtx,&dlhw);
                    lhpvtx = MHTfindClosestVertexNo(lhpial_hash, lhpial, &vtx,&dlhp);
                    rhwvtx = MHTfindClosestVertexNo(rhwhite_hash,rhwhite,&vtx,&drhw);
                    rhpvtx = MHTfindClosestVertexNo(rhpial_hash, rhpial, &vtx,&drhp);
                    if (lhwvtx < 0 && lhpvtx < 0 && rhwvtx < 0 && rhpvtx < 0)
                    {
                        /*
                        printf("  Could not map to any surface with hash table:\n");
                        printf("  crs = %d %d %d, ras = %6.4f %6.4f %6.4f \n",
                        c,r,s,vtx.x,vtx.y,vtx.z);
                        printf("  Using brute force search %d ... \n",nbrute);
                        fflush(stdout);
                        */
                        lhwvtx = MRISfindClosestVertex(lhwhite,vtx.x,vtx.y,vtx.z,&dlhw);
                        lhpvtx = MRISfindClosestVertex(lhpial,vtx.x,vtx.y,vtx.z,&dlhp);
                        rhwvtx = MRISfindClosestVertex(rhwhite,vtx.x,vtx.y,vtx.z,&drhw);
                        rhpvtx = MRISfindClosestVertex(rhpial,vtx.x,vtx.y,vtx.z,&drhp);
                        nbrute ++;
                        //exit(1);
                    }
                }
                else
                {
                    lhwvtx = MRISfindClosestVertex(lhwhite,vtx.x,vtx.y,vtx.z,&dlhw);
                    lhpvtx = MRISfindClosestVertex(lhpial,vtx.x,vtx.y,vtx.z,&dlhp);
                    rhwvtx = MRISfindClosestVertex(rhwhite,vtx.x,vtx.y,vtx.z,&drhw);
                    rhpvtx = MRISfindClosestVertex(rhpial,vtx.x,vtx.y,vtx.z,&drhp);
                }

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

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

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

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

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

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

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

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

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

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

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

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

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

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


    return(0);
}
int
main(int argc, char *argv[]) {
  char          **av, *surf_fname, *profile_fname, *seg_fname ;
  int           ac, nargs ;
  MRI_SURFACE   *mris, *mris_ico = NULL ;
  // LABEL         *label = NULL ;
  MRI           *mri_profiles ;
  CLUSTER       *ct ;

  setRandomSeed(10L) ;

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

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

  profile_fname = argv[1] ;
  surf_fname = argv[2] ;
  seg_fname = argv[3] ;
  mris = MRISread(surf_fname) ;
  if (!mris)
    ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
              Progname, surf_fname) ;
  MRISsetNeighborhoodSize(mris, 2) ;

  if (MRISreadAnnotation(mris, "ad_aparc") != NO_ERROR) {
    if (MRISreadAnnotation(mris, "aparc") != NO_ERROR)
      ErrorExit(ERROR_NOFILE, "%s: could not read annotation file ad_aparc", Progname) ;
  }

  printf("reading intensity profile volume from %s...\n", profile_fname) ;
  mri_profiles = MRIread(profile_fname) ;
  if (!mri_profiles)
    ErrorExit(ERROR_NOFILE, "%s: could not read intensity volume %s",
              Progname, profile_fname) ;
  rip_vertices_out_of_fov(mris, mri_profiles) ;
  rip_bad_vertices(mris, mri_profiles) ;
  MRISclearAnnotations(mris) ;

#if 0
  if (nlabels > 0) {
    int l ;
    char label_name[STRLEN] ;
    LABEL *ltotal = NULL ;

    for (l = 0 ; l < nlabels ; l++) {
      sprintf(label_name, "%s/%s/label/%s.%s.label", sdir, sname, hemi,label_names[l]) ;

      label = LabelRead(NULL, label_name) ;
      if (!label)
        ErrorExit(ERROR_NOFILE, "%s: could not read label file %s...\n", Progname,
                  label_name) ;
      if (num_erode > 0) {
        printf("eroding label %d times, npoints went from %d ", num_erode,label->n_points) ;
        LabelErode(label, mris, num_erode) ;
        printf("to %d ", label->n_points) ;
      }
      ltotal = LabelCombine(label, ltotal) ;
    }
    if (nlabels == 0)
      ltotal = LabelInFOV(mris, mri, MIN_BORDER_DIST) ;

    LabelRipRestOfSurfaceWithThreshold(ltotal, mris, thresh) ;
  }
#endif

  if (navgs > 0) {
    printf("smoothing profiles %d times\n", navgs) ;
    MRISsmoothFrames(mris, mri_profiles, navgs) ;
  }
  if (ico_fname) {
    mris_ico = MRISread(ico_fname) ;
    if (mris_ico == NULL)
      ErrorExit(ERROR_BADPARM, "%s: could not read icosahedron from %s...\n", Progname, ico_fname) ;
  }
  ct = MRIScluster(mris, mri_profiles, cluster_type, k, start_fname, mris_ico) ;
  printf("writing cortical intensity clusters to %s...\n", seg_fname) ;
  MRISwriteAnnotation(mris, seg_fname) ;
  {
    int    vno ;
    VERTEX *v ;
    int    c, i ;
    char   fname[STRLEN], ext[STRLEN] ;

    // write average profiles into mri_profiles and write it out
    for (vno = 0 ; vno < mris->nvertices ; vno++) {
      v = &mris->vertices[vno] ;
      if (v->ripflag)
        continue ;
      c = v->curv ;
      if (c < 0)
        continue ;
      for (i = 0 ; i < mri_profiles->nframes ; i++)
        MRIsetVoxVal(mri_profiles, vno, 0, 0, i, VECTOR_ELT(ct[c].v_mean,i+1)) ;
    }
    FileNameExtension(seg_fname, ext) ;
    FileNameRemoveExtension(seg_fname, fname) ;
    strcat(fname, "_cluster_avg.mgz") ;
    printf("writing average cluster profiles to %s...\n", fname) ;
    MRIwrite(mri_profiles, fname) ;
  }

  MRIfree(&mri_profiles) ;

  exit(0) ;
  return(0) ;  /* for ansi */
}
static CLUSTER *
MRISclusterAgglomerative(MRI_SURFACE *mris, MRI *mri_profiles, int k,
                         char *start_fname, MRI_SURFACE *mris_ico) {
  int    i, nsamples, iter, done, vno, cluster ;
  char   fname[STRLEN] ;
  CLUSTER *ct ;

  if (start_fname) {
    VERTEX *v ;

    if (MRISreadAnnotation(mris, start_fname) != NO_ERROR)
      ErrorExit(ERROR_NOFILE, "%s: could not read initial annotation file %s",
                Progname, start_fname) ;
    k = 0 ;
    for (vno = 0 ; vno < mris->nvertices ; vno++) {
      v = &mris->vertices[vno] ;
      if (v->annotation == 0) {
        v->ripflag = 1;
        continue ;
      }
      CTABfindAnnotation(mris->ct, v->annotation, &cluster);
      if (cluster >= k)
        k = cluster+1 ;
      v->curv = cluster ;
    }
    printf("%d clusters detected...\n", k) ;
    ct = calloc(k, sizeof(CLUSTER)) ;
    if (!ct)
      ErrorExit(ERROR_BADPARM, "%s: could not allocate %d clusters", Progname, k) ;
    nsamples = mri_profiles->nframes ;
    for (i = 0 ; i < k ; i++) {
      ct[i].v_mean = VectorAlloc(nsamples, MATRIX_REAL) ;
      ct[i].m_cov = MatrixIdentity(nsamples, NULL) ;
      ct[i].npoints = 0 ;
    }
    for (vno = 0 ; vno < mris->nvertices ; vno++) {
      v = &mris->vertices[vno] ;
      if (v->ripflag)
        continue ;
      add_vertex_to_cluster(mris, mri_profiles, ct, v->curv, vno);
    }
  } else {
    if (mris_ico)
      k = mris_ico->nvertices ;
    ct = calloc(k, sizeof(CLUSTER)) ;
    if (!ct)
      ErrorExit(ERROR_BADPARM, "%s: could not allocate %d clusters", Progname, k) ;
    nsamples = mri_profiles->nframes ;
    for (i = 0 ; i < k ; i++) {
      ct[i].v_mean = VectorAlloc(nsamples, MATRIX_REAL) ;
      ct[i].m_cov = MatrixIdentity(nsamples, NULL) ;
      ct[i].npoints = 0 ;
    }

    MRISsetCurvature(mris, -1) ;
    if (mris_ico)
      initialize_cluster_centers_with_ico(mris, mri_profiles, ct, mris_ico) ;
    else
      initialize_cluster_centers(mris, mri_profiles, ct, k) ;

    done = iter = 0 ;
    do {
      vno = find_most_likely_unmarked_vertex(mris, mri_profiles, ct, k, &cluster);
      if (vno < 0)
        break ;
      add_vertex_to_cluster(mris, mri_profiles, ct, cluster, vno);
      if (write_iters > 0 && ((iter % write_iters) == 0)) {
        sprintf(fname, "%s.clusters%6.6d.annot",
                mris->hemisphere == LEFT_HEMISPHERE ? "lh" : "rh", iter) ;
        printf("%6.6d: writing %s\n", iter, fname) ;
        MRISwriteAnnotation(mris, fname) ;
        sprintf(fname, "./%s.clusters%6.6d.indices",
                mris->hemisphere == LEFT_HEMISPHERE ? "lh" : "rh", iter) ;
        //   MRISwriteCurvature(mris, fname) ;
      }
      if (write_iters == 0 && ((iter % 5000) == 0))
        printf("%6.6d of %6.6d\n", iter, mris->nvertices-k) ;
      if (iter++ > mris->nvertices-k || iter > max_iterations)
        done = 1 ;
    } while (!done) ;
  }
  iter = done = 0 ;
  do {
    vno = find_most_likely_vertex_to_swap(mris, mri_profiles, ct, k, &cluster);
    if (vno < 0)
      break ;
    remove_vertex_from_cluster(mris, mri_profiles, ct, mris->vertices[vno].curv, vno) ;
    add_vertex_to_cluster(mris, mri_profiles, ct, cluster, vno);
    if (write_iters > 0 && ((iter % write_iters) == 0)) {
      sprintf(fname, "%s.more_clusters%6.6d.annot",
              mris->hemisphere == LEFT_HEMISPHERE ? "lh" : "rh", iter) ;
      printf("%6.6d: writing %s\n", iter, fname) ;
      MRISwriteAnnotation(mris, fname) ;
      sprintf(fname, "./%s.more_clusters%6.6d.indices",
              mris->hemisphere == LEFT_HEMISPHERE ? "lh" : "rh", iter) ;
      //   MRISwriteCurvature(mris, fname) ;
    }
    if (write_iters == 0 && ((iter % 5000) == 0))
      printf("%6.6d of %6.6d\n", iter, mris->nvertices) ;
    if (iter++ > mris->nvertices || iter > max_iterations)
      done = 1 ;
  } while (!done) ;
  return(ct);
}
示例#5
0
int
main(int argc, char *argv[]) {
  char   **av, *label_name, *vol_name, *out_name ;
  int    ac, nargs ;
  int    msec, minutes, seconds,  i  ;
  LABEL  *area ;
  struct timeb start ;
  MRI    *mri,  *mri_seg ;
  Real   xw, yw, zw, xv, yv, zv, val;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mri_label_vals.c,v 1.16 2015/08/24 18:22:05 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) ;

  vol_name = argv[1] ;
  label_name = argv[2]  ;
  out_name = argv[3] ;

  mri = MRIread(vol_name) ;
  if (!mri)
    ErrorExit(ERROR_NOFILE, "%s: could not read volume from %s",Progname, vol_name) ;
  if (scaleup_flag) {
    float scale, fov_x, fov_y, fov_z  ;

    scale = 1.0/MIN(MIN(mri->xsize, mri->ysize),mri->zsize) ;
    fprintf(stderr, "scaling voxel sizes up by %2.2f\n", scale) ;
    mri->xsize *= scale ;
    mri->ysize *= scale ;
    mri->zsize *= scale ;
    fov_x = mri->xsize * mri->width;
    fov_y = mri->ysize * mri->height;
    fov_z = mri->zsize * mri->depth;
    mri->xend = fov_x / 2.0;
    mri->xstart = -mri->xend;
    mri->yend = fov_y / 2.0;
    mri->ystart = -mri->yend;
    mri->zend = fov_z / 2.0;
    mri->zstart = -mri->zend;

    mri->fov = (fov_x > fov_y ? (fov_x > fov_z ? fov_x : fov_z) : (fov_y > fov_z ? fov_y : fov_z) );
  }

  if (segmentation_flag >= 0) {
    int x, y, z  ;
    VECTOR *v_seg, *v_mri ;
    MATRIX *m_seg_to_mri ;

    v_seg = VectorAlloc(4, MATRIX_REAL) ;
    v_mri = VectorAlloc(4, MATRIX_REAL) ;
    VECTOR_ELT(v_seg, 4) = 1.0 ;
    VECTOR_ELT(v_mri, 4) = 1.0 ;

    mri_seg = MRIread(argv[2]) ;
    if (!mri_seg)
      ErrorExit(ERROR_NOFILE, "%s: could not read volume from %s",Progname, argv[2]) ;
    if (erode) {
      MRI *mri_tmp ;

      mri_tmp = MRIclone(mri_seg, NULL) ;
      MRIcopyLabel(mri_seg, mri_tmp, segmentation_flag) ;
      while (erode-- > 0)
        MRIerode(mri_tmp, mri_tmp) ;
      MRIcopy(mri_tmp, mri_seg) ;
      MRIfree(&mri_tmp) ;
    }

    m_seg_to_mri = MRIgetVoxelToVoxelXform(mri_seg, mri) ;
    for (x = 0  ; x  < mri_seg->width ; x++) {
      V3_X(v_seg) = x ;
      for (y = 0  ; y  < mri_seg->height ; y++) {
        V3_Y(v_seg) = y ;
        for (z = 0  ; z  < mri_seg->depth ; z++) {
          V3_Z(v_seg) = z ;
          if (MRIvox(mri_seg, x, y,  z) == segmentation_flag) {
            MatrixMultiply(m_seg_to_mri, v_seg, v_mri) ;
            xv = V3_X(v_mri) ;
            yv = V3_Y(v_mri) ;
            zv = V3_Z(v_mri) ;
            MRIsampleVolumeType(mri, xv,  yv, zv, &val, SAMPLE_NEAREST);
#if  0
            if (val < .000001) {
              val *= 1000000;
              printf("%f*0.000001\n", val);
            } else
#endif
              if (coords)
                printf("%2.1f %2.1f %2.1f %f\n", xv, yv, zv, val);
              else
                printf("%f\n", val);
          }
        }
      }
    }
    MatrixFree(&m_seg_to_mri) ;
    VectorFree(&v_seg) ;
    VectorFree(&v_mri) ;
  } else {
    if (cras == 1)
      fprintf(stderr,"using the label coordinates to be c_(r,a,s) != 0.\n");

    if (surface_dir) {
      MRI_SURFACE *mris ;
      char fname[STRLEN] ;
      sprintf(fname, "%s/%s.white", surface_dir, hemi) ;
      mris = MRISread(fname) ;
      if (mris == NULL)
        ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s...\n", Progname,fname) ;
      sprintf(fname, "%s/%s.thickness", surface_dir, hemi) ;
      if (MRISreadCurvatureFile(mris, fname) != NO_ERROR)
        ErrorExit(ERROR_BADPARM, "%s: could not read thickness file %s...\n", Progname,fname) ;

      if (annot_prefix)   /* read an annotation in and print vals in it */
      {
#define MAX_ANNOT 10000
        int   vno, annot_counts[MAX_ANNOT], index ;
        VERTEX *v ;
        Real  xw, yw, zw, xv, yv, zv, val ;
        float annot_means[MAX_ANNOT] ;
        FILE  *fp ;

        memset(annot_means, 0, sizeof(annot_means)) ;
        memset(annot_counts, 0, sizeof(annot_counts)) ;
        if (MRISreadAnnotation(mris, label_name) != NO_ERROR)
          ErrorExit(ERROR_BADPARM, "%s: could not read annotation file %s...\n", Progname,fname) ;
        if (mris->ct == NULL)
          ErrorExit(ERROR_BADPARM, "%s: annot file does not contain a color table, specifiy one with -t ", Progname);
        for (vno = 0 ; vno < mris->nvertices ; vno++) {
          v = &mris->vertices[vno] ;
          if (v->ripflag)
            continue ;
          CTABfindAnnotation(mris->ct, v->annotation, &index) ;
          if (index >= 0 && index < mris->ct->nentries) {
            annot_counts[index]++ ;
            xw = v->x + v->curv*.5*v->nx ;
            yw = v->y + v->curv*.5*v->ny ;
            zw = v->z + v->curv*.5*v->nz ;
            if (cras == 1)
              MRIworldToVoxel(mri, xw, yw,  zw, &xv, &yv, &zv) ;
            else
              MRIsurfaceRASToVoxel(mri, xw, yw, zw, &xv, &yv, &zv);
            MRIsampleVolume(mri, xv, yv, zv, &val) ;
            annot_means[index] += val ;
            sprintf(fname, "%s-%s-%s.dat", annot_prefix, hemi, mris->ct->entries[index]->name) ;
            fp = fopen(fname, "a") ;
            fprintf(fp, "%f\n", val) ;
            fclose(fp) ;
          }
        }
      }
      else  /* read label in and print vals in it */
      {
        area = LabelRead(NULL, label_name) ;
        if (!area)
          ErrorExit(ERROR_NOFILE, "%s: could not read label from %s",Progname, label_name) ;

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

      for (i = 0 ;  i  < area->n_points ; i++) {

        xw =  area->lv[i].x ;
        yw =  area->lv[i].y ;
        zw =  area->lv[i].z ;
        if (cras == 1)
          MRIworldToVoxel(mri, xw, yw,  zw, &xv, &yv, &zv) ;
        else
          MRIsurfaceRASToVoxel(mri, xw, yw, zw, &xv, &yv, &zv);
        MRIsampleVolumeType(mri, xv,  yv, zv, &val, SAMPLE_NEAREST);
#if 0
        if (val < .000001) {
          val *= 1000000;
          printf("%f*0.000001\n", val);
        } else
#endif
          printf("%f\n", val);
      }
    }
  }
  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;

  if (DIAG_VERBOSE_ON)
    fprintf(stderr, "label value extractiong took %d minutes and %d seconds.\n",
            minutes, seconds) ;

  exit(0) ;
  return(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 */
}
示例#7
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 */
}
示例#8
0
/*---------------------------------------------------------------*/
int main(int argc, char *argv[]) {
  int nargs, nthvtx, nnbrs1, nnbrs2, nthnbr, nbrvtxno1, nbrvtxno2;
  int nthface, annot1, annot2;
  VERTEX *vtx1, *vtx2;
  FACE *face1, *face2;
  float diff, maxdiff;

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

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

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

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

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

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

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

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

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

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

  maxdiff=0;

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

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

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

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

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

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

  return 0;
}
示例#9
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) ;
}
/*---------------------------------------------------------------*/
int main(int argc, char *argv[]) {
  int         ac, nargs, *nunits, index ;
  MRI_SURFACE *mris ;
  char        **av, fname[STRLEN], *annot_name, *out_fname, *cp,
  *subject, *hemi ;
  float       area_thresh ;

  nargs = handle_version_option (argc, argv, vcid, "$Name:  $");
  if (nargs && argc - nargs == 1)  exit (0);
  argc -= nargs;

  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(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 < 6)  usage_exit() ;
  subject = argv[1] ;
  hemi = argv[2] ;
  annot_name = argv[3] ;
  area_thresh = atof(argv[4]) ;
  out_fname = argv[5] ;

  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.sphere", sdir, subject, hemi) ;
  mris = MRISread(fname) ;
  if (mris == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not read surface from %s",
              Progname, fname) ;
  if (MRISreadAnnotation(mris, annot_name) != NO_ERROR)
    ErrorExit(ERROR_NOFILE, "%s: could not read annotation %s",
              Progname, annot_name) ;
  if (mris->ct == NULL)
    ErrorExit(ERROR_NOFILE, "%s: annotation %s must have embedded color table",
              Progname, annot_name) ;

  nunits = (int *)calloc(mris->ct->nentries, sizeof(int)) ;
  if (!nunits)
    ErrorExit(ERROR_BADPARM, "%s: could not allocate %d nunits table", Progname,mris->ct->nentries) ;

  MRIScomputeMetricProperties(mris) ;
  if (isdigit(*argv[4]))  // area threshold specified
  {
    int    vno ;
    VERTEX *v ;
    float  *area ;
    area = (float *)calloc(mris->ct->nentries, sizeof(float)) ;
    if (!area)
      ErrorExit(ERROR_BADPARM, "%s: could not allocate %d area table", Progname,mris->ct->nentries) ;
    for (vno = 0 ; vno < mris->nvertices ; vno++) {
      v = &mris->vertices[vno] ;
      CTABfindAnnotation(mris->ct, v->annotation, &index) ;
      if (index < 0 || v->ripflag)
        continue ;
      area[index] += v->area ;
    }
    for (index = 0 ; index < mris->ct->nentries ; index++)
      nunits[index] =  (int)(area[index] / area_thresh)+1 ;
    free(area) ;
  } else                 // interpret it as a file with parcellation names and # of units
  {
    char  line[STRLEN], *cp, name[STRLEN] ;
    FILE  *fp ;
    int   num ;

    printf("interpreting 4th command line arg as split file name\n") ;
    fp = fopen(argv[4], "r") ;
    if (fp == NULL)
      ErrorExit(ERROR_NOFILE, "%s: could not open parcellation division file %s", Progname,argv[4]) ;
    while ((cp = fgetl(line, STRLEN-1, fp)) != NULL) {
      if (sscanf(line, "%s %d", name, &num) != 2)
        ErrorExit(ERROR_BADFILE, "%s: could not parse name/num pair from '%s'", Progname, line) ;
      CTABfindName(mris->ct, name, &index) ;
      if (index < 0)
        ErrorExit(ERROR_BADFILE, "%s: could not find name '%s' in color table", Progname, name) ;
      nunits[index] = num ;
    }
  }

  for (index = 0 ; index < mris->ct->nentries ; index++)
    if (nunits[index] > 1)
      printf("dividing %s (%d) into %d parts\n", mris->ct->entries[index]->name, index, nunits[index]) ;

  MRISdivideAnnotation(mris, nunits) ;

  free(nunits) ;
  printf("saving annotation to %s\n", out_fname) ;
  MRISwriteAnnotation(mris, out_fname) ;
  return 0;
}
示例#11
0
/*--------------------------------------------------*/
int main(int argc, char **argv) {
  int nargs, err, asegid, c, r, s, annot, hemioffset;
  int annotid;
  struct utsname uts;
  char *cmdline, cwd[2000];

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, vcid, "$Name: stable5 $");
  if (nargs && argc - nargs == 1) exit (0);
  argc -= nargs;
  cmdline = argv2cmdline(argc,argv);
  uname(&uts);
  getcwd(cwd,2000);

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

  if (argc == 0) usage_exit();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  printf("mri_aparc2wmseg done\n");
  return(0);
}
示例#12
0
/*---------------------------------------------------------------*/
int main(int argc, char *argv[]) {
  int nargs,n,err;
  MRIS *SurfReg[100];
  MRI *SrcVal, *TrgVal;
  char *base;
  COLOR_TABLE *ctab=NULL;

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

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

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

  // Load in source data
  SrcVal = NULL;
  if(DoSynthRand) {
    if (SynthSeed < 0) SynthSeed = PDFtodSeed();
    printf("INFO: synthesizing, seed = %d\n",SynthSeed);
    srand48(SynthSeed);
    MRIrandn(SrcVal->width, SrcVal->height, SrcVal->depth,
             SrcVal->nframes,0, 1, SrcVal);
  }
  else if(DoSynthOnes != 0) {
    printf("INFO: filling input with all 1s\n");
    MRIconst(SrcVal->width, SrcVal->height, SrcVal->depth,
             SrcVal->nframes, 1, SrcVal);
  }
  else if(AnnotFile) {
    printf("Loading annotation %s\n",AnnotFile);
    err = MRISreadAnnotation(SurfReg[0], AnnotFile);
    if(err) exit(1);
    SrcVal = MRISannotIndex2Seg(SurfReg[0]);
    ctab = CTABdeepCopy(SurfReg[0]->ct);
  }
  else if(LabelFile) {
    LABEL *srclabel;
    printf("Loading label %s\n",LabelFile);
    srclabel = LabelRead(NULL, LabelFile);
    if(srclabel == NULL) exit(1);
    SrcVal = MRISlabel2Mask(SurfReg[0],srclabel,NULL);
    printf("   %d points in input label\n",srclabel->n_points);
    LabelFree(&srclabel);
  }
  else {
    printf("Loading %s\n",SrcValFile);
    SrcVal = MRIread(SrcValFile);
    if(SrcVal==NULL) exit(1);
  }

  // Apply registration to source
  TrgVal = MRISapplyReg(SrcVal, SurfReg, nsurfs, ReverseMapFlag, DoJac, UseHash);
  if(TrgVal == NULL) exit(1);

  // Save output
  if(AnnotFile){
    printf("Converting to target annot\n");
    err = MRISseg2annot(SurfReg[nsurfs-1],TrgVal,ctab);
    if(err) exit(1);
    printf("Writing %s\n",TrgValFile);
    MRISwriteAnnotation(SurfReg[nsurfs-1], TrgValFile);
  } 
  else if(LabelFile){
    LABEL *label;
    label = MRISmask2Label(SurfReg[nsurfs-1], TrgVal, 0, 10e-5);
    printf("   %d points in output label\n",label->n_points);
    err = LabelWrite(label,TrgValFile);
    if(err){
      printf("ERROR: writing label file %s\n",TrgValFile);
      exit(1);
    }
    LabelFree(&label);
  }
  else{
    printf("Writing %s\n",TrgValFile);
    MRIwrite(TrgVal,TrgValFile);
  }
  
  printf("mris_apply_reg done\n");
  return 0;
}
示例#13
0
/*---------------------------------------------------------------*/
int main(int argc, char *argv[]) {
    int nargs,r,c,s,n,segid,err;
    double val;

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

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

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

    if (DoDavid) {
        printf("Loading David's stat file\n");
        nitems = LoadDavidsTable(statfile, &lutindex, &log10p);
    }
    if (DoSue) {
        printf("Loading Sue's stat file\n");
        nitems = LoadSuesTable(statfile, datcol1, log10flag, &lutindex, &log10p);
    }
    if (nitems == 0) {
        printf("ERROR: could not find any items in %s\n",statfile);
        exit(1);
    }

    if (annot == NULL) {
        seg = MRIread(segfile);
        if (seg == NULL) exit(1);
    } else {
        printf("Constructing seg from annotation\n");
        sprintf(tmpstr,"%s/%s/surf/%s.white",SUBJECTS_DIR,subject,hemi);
        mris = MRISread(tmpstr);
        if (mris==NULL) exit(1);
        sprintf(tmpstr,"%s/%s/label/%s.%s.annot",SUBJECTS_DIR,subject,hemi,annot);
        err = MRISreadAnnotation(mris, tmpstr);
        if (err) exit(1);
        seg = MRISannotIndex2Seg(mris);
    }

    out = MRIallocSequence(seg->width,seg->height,seg->depth,MRI_FLOAT,1);
    MRIcopyHeader(seg,out);

    for (c=0; c < seg->width; c++) {
        //printf("%3d ",c);
        //if(c%20 == 19) printf("\n");
        fflush(stdout);
        for (r=0; r < seg->height; r++) {
            for (s=0; s < seg->depth; s++) {
                segid = MRIgetVoxVal(seg,c,r,s,0);
                val = 0;
                if (segid != 0) {
                    if (annot != NULL) {
                        if (strcmp(hemi,"lh")==0) segid = segid + 1000;
                        if (strcmp(hemi,"rh")==0) segid = segid + 2000;
                        MRIsetVoxVal(seg,c,r,s,0,segid);
                    }
                    for (n=0; n < nitems; n++) {
                        if (lutindex[n] == segid) {
                            val = log10p[n];
                            break;
                        }
                    }
                }
                MRIsetVoxVal(out,c,r,s,0,val);
            }
        }
    }
    printf("\n");
    MRIwrite(out,outfile);
    MRIwrite(seg,"segtmp.mgh");

    printf("mri_stats2seg done\n");
    return 0;
}