Esempio n. 1
0
static int
extract_labeled_image(MRI *mri_src,
                      TRANSFORM *transform,
                      int label,
                      MRI *mri_dst)
{
  MRI  *mri_binarized, *mri_tmp ;

  mri_binarized = MRIclone(mri_src, NULL) ;
  nvoxels += MRIcopyLabel(mri_src, mri_binarized, label) ;
  MRIbinarize(mri_binarized, mri_binarized, 1, 0, UNIT_VOLUME) ;
  if (transform)
    mri_tmp = TransformCreateDensityMap(transform, mri_binarized, NULL) ;
  else
    mri_tmp = MRIcopy(mri_binarized,NULL) ;

  MRIadd(mri_tmp, mri_dst, mri_dst) ;
  MRIfree(&mri_binarized) ;
  MRIfree(&mri_tmp) ;
  return(NO_ERROR) ;
}
static MRI *
MRIcomputeSurfaceDistanceProbabilities(MRI_SURFACE *mris,  MRI *mri_ribbon, MRI *mri, MRI *mri_aseg) 
{
  MRI          *mri_features, *mri_binary, *mri_white_dist, *mri_pial_dist, *mri_mask ;
  int          nwhite_bins, npial_bins, x, y, z, label, i ;
  HISTOGRAM2D *hw, *hp ; 
  float        pdist, wdist, val ;
  double       wval, pval ;

  mri_features = MRIallocSequence(mri->width, mri->height, mri->depth, MRI_FLOAT, 2) ;
  MRIcopyHeader(mri, mri_features) ;

  mri_binary = MRIcopy(mri_ribbon, NULL) ;
  mri_binary = MRIbinarize(mri_ribbon, NULL, 1, 0, 1) ;
  mri_pial_dist = MRIdistanceTransform(mri_binary, NULL, 1, max_pial_dist+1, DTRANS_MODE_SIGNED,NULL);
  if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
    MRIwrite(mri_pial_dist, "pd.mgz") ;

  MRIclear(mri_binary) ;
  MRIcopyLabel(mri_ribbon, mri_binary, Left_Cerebral_White_Matter) ;
  MRIcopyLabel(mri_ribbon, mri_binary, Right_Cerebral_White_Matter) ;
  MRIbinarize(mri_binary, mri_binary, 1, 0, 1) ;
  mri_white_dist = MRIdistanceTransform(mri_binary, NULL, 1, max_white_dist+1, DTRANS_MODE_SIGNED,NULL);
  if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
    MRIwrite(mri_white_dist, "wd.mgz") ;

  nwhite_bins = ceil((max_white_dist - min_white_dist) / white_bin_size)+1 ;
  npial_bins = ceil((max_pial_dist - min_pial_dist) / pial_bin_size)+1 ;
  hw = HISTO2Dalloc(NBINS, nwhite_bins) ;
  hp = HISTO2Dalloc(NBINS, npial_bins) ;

  HISTO2Dinit(hw, NBINS, nwhite_bins, 0, NBINS-1, min_white_dist, max_white_dist) ;
  HISTO2Dinit(hp, NBINS, npial_bins, 0, NBINS-1, min_pial_dist, max_pial_dist) ;

  for (x = 0 ; x < mri->width ; x++)
    for (y = 0 ; y < mri->height ; y++)
      for (z = 0 ; z < mri->depth ; z++)
      {
	label = MRIgetVoxVal(mri_aseg, x, y, z, 0) ;
	if (IS_CEREBELLUM(label) || IS_VENTRICLE(label) || label == Brain_Stem || IS_CC(label))
	  continue ;
	pdist = MRIgetVoxVal(mri_pial_dist, x, y, z, 0) ;
	wdist = MRIgetVoxVal(mri_pial_dist, x, y, z, 0) ;
	val  = MRIgetVoxVal(mri, x, y, z, 0) ;
	if (pdist >= min_pial_dist && pdist <= max_pial_dist)
	  HISTO2DaddSample(hp, val, pdist, 0, 0, 0, 0) ;
	if (wdist >= min_white_dist && wdist <= max_white_dist)
	  HISTO2DaddSample(hw, val, wdist, 0, 0, 0, 0) ;
      }
  HISTO2DmakePDF(hp, hp) ;
  HISTO2DmakePDF(hw, hw) ;
  for (x = 0 ; x < mri->width ; x++)
    for (y = 0 ; y < mri->height ; y++)
      for (z = 0 ; z < mri->depth ; z++)
      {
	label = MRIgetVoxVal(mri_aseg, x, y, z, 0) ;
	if (IS_CEREBELLUM(label) || IS_VENTRICLE(label) || label == Brain_Stem || IS_CC(label))
	  continue ;
	pdist = MRIgetVoxVal(mri_pial_dist, x, y, z, 0) ;
	wdist = MRIgetVoxVal(mri_pial_dist, x, y, z, 0) ;
	val  = MRIgetVoxVal(mri, x, y, z, 0) ;
	wval = HISTO2DgetCount(hw, val, wdist);
	if (DZERO(wval) == 0)
	  MRIsetVoxVal(mri_features, x, y, z, 1, -log10(wval)) ;
	pval = HISTO2DgetCount(hp, val, pdist);
	if (DZERO(pval) == 0)
	  MRIsetVoxVal(mri_features, x, y, z, 0, -log10(pval)) ;
      }

  MRIclear(mri_binary) ;
  MRIbinarize(mri_ribbon, mri_binary, 1, 0, 1) ;
  mri_mask = MRIcopy(mri_binary, NULL) ;
  for (i = 0 ; i < close_order ; i++)
  {
    MRIdilate(mri_binary, mri_mask) ;
    MRIcopy(mri_mask, mri_binary) ;
  }
  
  for (i = 0 ; i < close_order ; i++)
  {
    MRIerode(mri_binary, mri_mask) ;
    MRIcopy(mri_mask, mri_binary) ;
  }

  MRIwrite(mri_mask, "m.mgz") ;
  MRImask(mri_features, mri_mask, mri_features, 0, 0) ;
  HISTO2Dfree(&hw) ;
  HISTO2Dfree(&hp) ;
  MRIfree(&mri_white_dist) ; MRIfree(&mri_pial_dist) ; MRIfree(&mri_binary) ;
  return(mri_features) ;
}
Esempio n. 3
0
int
main(int argc, char *argv[])
{
  char   **av ;
  int    ac, nargs, n ;
  MRI    *mri_src, *mri_dst = NULL, *mri_bias, *mri_orig, *mri_aseg = NULL ;
  char   *in_fname, *out_fname ;
  int          msec, minutes, seconds ;
  struct timeb start ;

  char cmdline[CMD_LINE_LEN] ;

  make_cmd_version_string
  (argc, argv,
   "$Id: mri_normalize.c,v 1.80 2012/10/16 21:38:35 nicks Exp $",
   "$Name:  $",
   cmdline);

  /* rkt: check for and handle version tag */
  nargs = handle_version_option
          (argc, argv,
           "$Id: mri_normalize.c,v 1.80 2012/10/16 21:38:35 nicks Exp $",
           "$Name:  $");
  if (nargs && argc - nargs == 1)
  {
    exit (0);
  }
  argc -= nargs;

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

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

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

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

  if(verbose)
  {
    printf( "reading from %s...\n", in_fname) ;
  }
  mri_src = MRIread(in_fname) ;
  if (!mri_src)
    ErrorExit(ERROR_NO_FILE, "%s: could not open source file %s",
              Progname, in_fname) ;
  MRIaddCommandLine(mri_src, cmdline) ;

  if(nsurfs > 0)
  {
    MRI_SURFACE *mris ;
    MRI         *mri_dist=NULL, *mri_dist_sup=NULL, *mri_ctrl, *mri_dist_one ;
    LTA          *lta= NULL ;
    int          i ;
    TRANSFORM    *surface_xform ;

    if (control_point_fname)  // do one pass with only file control points first
    {
      MRI3dUseFileControlPoints(mri_src, control_point_fname) ;
      mri_dst =
        MRI3dGentleNormalize(mri_src,
                             NULL,
                             DEFAULT_DESIRED_WHITE_MATTER_VALUE,
                             NULL,
                             intensity_above,
                             intensity_below/2,1,
                             bias_sigma, mri_not_control);
    }
    else
    {
      mri_dst = MRIcopy(mri_src, NULL) ;
    }
    for (i = 0 ; i < nsurfs ; i++)
    {
      mris = MRISread(surface_fnames[i]) ;
      if (mris == NULL)
        ErrorExit(ERROR_NOFILE,"%s: could not surface %s",
                  Progname,surface_fnames[i]);
      surface_xform = surface_xforms[i] ;
      TransformInvert(surface_xform, NULL) ;
      if (surface_xform->type == MNI_TRANSFORM_TYPE ||
          surface_xform->type == TRANSFORM_ARRAY_TYPE ||
          surface_xform->type  == REGISTER_DAT)
      {
        lta = (LTA *)(surface_xform->xform) ;

#if 0
        if (invert)
        {
          VOL_GEOM vgtmp;
          LT *lt;
          MATRIX *m_tmp = lta->xforms[0].m_L ;
          lta->xforms[0].m_L = MatrixInverse(lta->xforms[0].m_L, NULL) ;
          MatrixFree(&m_tmp) ;
          lt = &lta->xforms[0];
          if (lt->dst.valid == 0 || lt->src.valid == 0)
          {
            printf( "WARNING:***************************************************************\n");
            printf( "WARNING:dst volume infor is invalid.  Most likely produce wrong inverse.\n");
            printf( "WARNING:***************************************************************\n");
          }
          copyVolGeom(&lt->dst, &vgtmp);
          copyVolGeom(&lt->src, &lt->dst);
          copyVolGeom(&vgtmp, &lt->src);
        }
#endif
      }

      if (stricmp(surface_xform_fnames[i], "identity.nofile") != 0)
      {
        MRIStransform(mris, NULL, surface_xform, NULL) ;
      }

      mri_dist_one = MRIcloneDifferentType(mri_dst, MRI_FLOAT) ;
      printf("computing distance transform\n") ;
      MRIScomputeDistanceToSurface(mris, mri_dist_one, mri_dist_one->xsize) ;
      if (i == 0)
      {
        mri_dist = MRIcopy(mri_dist_one, NULL) ;
      }
      else
      {
        MRIcombineDistanceTransforms(mri_dist_one, mri_dist, mri_dist) ;
      }
//  MRIminAbs(mri_dist_one, mri_dist, mri_dist) ;
      MRIfree(&mri_dist_one) ;
    }
    MRIscalarMul(mri_dist, mri_dist, -1) ;

    if (nonmax_suppress)
    {
      printf("computing nonmaximum suppression\n") ;
      mri_dist_sup = MRInonMaxSuppress(mri_dist, NULL, 0, 1) ;
      mri_ctrl = MRIcloneDifferentType(mri_dist_sup, MRI_UCHAR) ;
      MRIbinarize(mri_dist_sup, mri_ctrl, min_dist, CONTROL_NONE, CONTROL_MARKED) ;
    }
    else if (erode)
    {
      int i ;
      mri_ctrl = MRIcloneDifferentType(mri_dist, MRI_UCHAR) ;
      MRIbinarize(mri_dist, mri_ctrl, min_dist, CONTROL_NONE, CONTROL_MARKED) ;
      for (i = 0 ; i < erode ; i++)
      {
        MRIerode(mri_ctrl, mri_ctrl) ;
      }
    }
    else
    {
      mri_ctrl = MRIcloneDifferentType(mri_dist, MRI_UCHAR) ;
      MRIbinarize(mri_dist, mri_ctrl, min_dist, CONTROL_NONE, CONTROL_MARKED) ;
    }

    if (control_point_fname)
    {
      MRInormAddFileControlPoints(mri_ctrl, CONTROL_MARKED) ;
    }

    if (mask_sigma > 0)
    {
      MRI *mri_smooth, *mri_mag, *mri_grad ;
      mri_smooth = MRIgaussianSmooth(mri_dst, mask_sigma, 1, NULL) ;
      mri_mag = MRIcloneDifferentType(mri_dst, MRI_FLOAT) ;
      mri_grad = MRIsobel(mri_smooth, NULL, mri_mag) ;
      MRIbinarize(mri_mag, mri_mag, mask_thresh, 1, 0) ;
      MRImask(mri_ctrl, mri_mag, mri_ctrl, 0, CONTROL_NONE) ;
      MRIfree(&mri_grad) ;
      MRIfree(&mri_mag) ;
      MRIfree(&mri_smooth) ;
    }
    if (mask_orig_fname)
    {
      MRI *mri_orig ;

      mri_orig = MRIread(mask_orig_fname) ;
      MRIbinarize(mri_orig, mri_orig, mask_orig_thresh, 0, 1) ;

      MRImask(mri_ctrl, mri_orig, mri_ctrl, 0, CONTROL_NONE) ;
      MRIfree(&mri_orig) ;
    }
    if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
    {
      MRIwrite(mri_dist, "d.mgz");
      MRIwrite(mri_dist_sup, "dm.mgz");
      MRIwrite(mri_ctrl, "c.mgz");
    }
    MRIeraseBorderPlanes(mri_ctrl, 4) ;
    if (aseg_fname)
    {
      mri_aseg = MRIread(aseg_fname) ;
      if (mri_aseg == NULL)
      {
        ErrorExit(ERROR_NOFILE,
                  "%s: could not load aseg from %s", Progname, aseg_fname) ;
      }
      remove_nonwm_voxels(mri_ctrl, mri_aseg, mri_ctrl) ;
      MRIfree(&mri_aseg) ;
    }
    else
    {
      remove_surface_outliers(mri_ctrl, mri_dist, mri_dst, mri_ctrl) ;
    }
    mri_bias = MRIbuildBiasImage(mri_dst, mri_ctrl, NULL, 0.0) ;
    if (mri_dist)
    {
      MRIfree(&mri_dist) ;
    }
    if (mri_dist_sup)
    {
      MRIfree(&mri_dist_sup) ;
    }
    if (bias_sigma> 0)
    {
      MRI *mri_kernel = MRIgaussian1d(bias_sigma, -1) ;
      if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
      {
        MRIwrite(mri_bias, "b.mgz") ;
      }
      printf("smoothing bias field\n") ;
      MRIconvolveGaussian(mri_bias, mri_bias, mri_kernel) ;
      if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
      {
        MRIwrite(mri_bias, "bs.mgz") ;
      }
      MRIfree(&mri_kernel);
    }
    MRIfree(&mri_ctrl) ;
    mri_dst = MRIapplyBiasCorrectionSameGeometry
              (mri_dst, mri_bias, mri_dst,
               DEFAULT_DESIRED_WHITE_MATTER_VALUE) ;
    printf("writing normalized volume to %s\n", out_fname) ;
    MRIwrite(mri_dst, out_fname) ;
    exit(0) ;
  } // end if(surface_fname)

  if (!mriConformed(mri_src) && conform > 0)
  {
    printf("unconformed source detected - conforming...\n") ;
    mri_src = MRIconform(mri_src) ;
  }

  if (mask_fname)
  {
    MRI *mri_mask ;

    mri_mask = MRIread(mask_fname) ;
    if (!mri_mask)
      ErrorExit(ERROR_NOFILE, "%s: could not open mask volume %s.\n",
                Progname, mask_fname) ;
    MRImask(mri_src, mri_mask, mri_src, 0, 0) ;
    MRIfree(&mri_mask) ;
  }

  if (read_flag)
  {
    MRI *mri_ctrl ;
    double scale ;

    mri_bias = MRIread(bias_volume_fname) ;
    if (!mri_bias)
      ErrorExit
      (ERROR_BADPARM,
       "%s: could not read bias volume %s", Progname, bias_volume_fname) ;
    mri_ctrl = MRIread(control_volume_fname) ;
    if (!mri_ctrl)
      ErrorExit
      (ERROR_BADPARM,
       "%s: could not read control volume %s",
       Progname, control_volume_fname) ;
    MRIbinarize(mri_ctrl, mri_ctrl, 1, 0, 128) ;
    mri_dst = MRImultiply(mri_bias, mri_src, NULL) ;
    scale = MRImeanInLabel(mri_dst, mri_ctrl, 128) ;
    printf("mean in wm is %2.0f, scaling by %2.2f\n", scale, 110/scale) ;
    scale = 110/scale ;
    MRIscalarMul(mri_dst, mri_dst, scale) ;
    MRIwrite(mri_dst, out_fname) ;
    exit(0) ;
  }

  if(long_flag)
  {
    MRI *mri_ctrl ;
    double scale ;

    mri_bias = MRIread(long_bias_volume_fname) ;
    if (!mri_bias)
      ErrorExit
      (ERROR_BADPARM,
       "%s: could not read bias volume %s", Progname, long_bias_volume_fname) ;
    mri_ctrl = MRIread(long_control_volume_fname) ;
    if (!mri_ctrl)
      ErrorExit
      (ERROR_BADPARM,
       "%s: could not read control volume %s",
       Progname, long_control_volume_fname) ;
    MRIbinarize(mri_ctrl, mri_ctrl, 1, 0, CONTROL_MARKED) ;
    if (mri_ctrl->type != MRI_UCHAR)
    {
      MRI *mri_tmp ;
      mri_tmp = MRIchangeType(mri_ctrl, MRI_UCHAR, 0, 1,1);
      MRIfree(&mri_ctrl) ;
      mri_ctrl = mri_tmp ;
    }
    scale = MRImeanInLabel(mri_src, mri_ctrl, CONTROL_MARKED) ;
    printf("mean in wm is %2.0f, scaling by %2.2f\n", scale, 110/scale) ;
    scale = DEFAULT_DESIRED_WHITE_MATTER_VALUE/scale ;
    mri_dst = MRIscalarMul(mri_src, NULL, scale) ;
    MRIremoveWMOutliers(mri_dst, mri_ctrl, mri_ctrl, intensity_below/2) ;
    mri_bias = MRIbuildBiasImage(mri_dst, mri_ctrl, NULL, 0.0) ;
    MRIsoapBubble(mri_bias, mri_ctrl, mri_bias, 50, 1) ;
    MRIapplyBiasCorrectionSameGeometry(mri_dst, mri_bias, mri_dst,
                                       DEFAULT_DESIRED_WHITE_MATTER_VALUE);
    //    MRIwrite(mri_dst, out_fname) ;
    //    exit(0) ;
  } // end if(long_flag)

  if (grad_thresh > 0)
  {
    float thresh ;
    MRI   *mri_mag, *mri_grad, *mri_smooth ;
    MRI *mri_kernel = MRIgaussian1d(.5, -1) ;

    mri_not_control = MRIcloneDifferentType(mri_src, MRI_UCHAR) ;
    switch (scan_type)
    {
    case MRI_MGH_MPRAGE:
      thresh = 15 ;
      break ;
    case MRI_WASHU_MPRAGE:
      thresh = 20 ;
      break ;
    case MRI_UNKNOWN:
    default:
      thresh = 12 ;
      break ;
    }
    mri_smooth = MRIconvolveGaussian(mri_src, NULL, mri_kernel) ;
    thresh = grad_thresh ;
    mri_mag = MRIcloneDifferentType(mri_src, MRI_FLOAT) ;
    mri_grad = MRIsobel(mri_smooth, NULL, mri_mag) ;
    MRIwrite(mri_mag, "m.mgz") ;
    MRIbinarize(mri_mag, mri_not_control, thresh, 0, 1) ;
    MRIwrite(mri_not_control, "nc.mgz") ;
    MRIfree(&mri_mag) ;
    MRIfree(&mri_grad) ;
    MRIfree(&mri_smooth) ;
    MRIfree(&mri_kernel) ;
  }
#if 0
#if 0
  if ((mri_src->type != MRI_UCHAR) ||
      (!(mri_src->xsize == 1 && mri_src->ysize == 1 && mri_src->zsize == 1)))
#else
  if (conform || (mri_src->type != MRI_UCHAR && conform > 0))
#endif
  {
    MRI  *mri_tmp ;

    fprintf
    (stderr,
     "downsampling to 8 bits and scaling to isotropic voxels...\n") ;
    mri_tmp = MRIconform(mri_src) ;
    mri_src = mri_tmp ;
  }
#endif

  if(aseg_fname)
  {
    printf("Reading aseg %s\n",aseg_fname);
    mri_aseg = MRIread(aseg_fname) ;
    if (mri_aseg == NULL)
      ErrorExit
      (ERROR_NOFILE,
       "%s: could not read aseg from file %s", Progname, aseg_fname) ;
    if (!mriConformed(mri_aseg))
    {
      ErrorExit(ERROR_UNSUPPORTED, "%s: aseg volume %s must be conformed",
                Progname, aseg_fname) ;
    }
  }
  else
  {
    mri_aseg = NULL ;
  }

  if(verbose)
  {
    printf( "normalizing image...\n") ;
  }
  fflush(stdout);
  fflush(stderr);

  TimerStart(&start) ;

  if (control_point_fname)
  {
    MRI3dUseFileControlPoints(mri_src, control_point_fname) ;
  }

  // this just setup writing control-point volume saving
  if(control_volume_fname)
  {
    MRI3dWriteControlPoints(control_volume_fname) ;
  }


  /* first do a gentle normalization to get
     things in the right intensity range */
  if(long_flag == 0)   // if long, then this will already have been done with base control points
  {
    if(control_point_fname != NULL)  /* do one pass with only
                                         file control points first */
      mri_dst =
        MRI3dGentleNormalize(mri_src,
                             NULL,
                             DEFAULT_DESIRED_WHITE_MATTER_VALUE,
                             NULL,
                             intensity_above,
                             intensity_below/2,1,
                             bias_sigma, mri_not_control);
    else
    {
      mri_dst = MRIcopy(mri_src, NULL) ;
    }
  }
  fflush(stdout);
  fflush(stderr);

  if(mri_aseg)
  {
    MRI *mri_ctrl, *mri_bias ;
    int  i ;

    printf("processing with aseg\n");

    mri_ctrl = MRIclone(mri_aseg, NULL) ;
    for (i = 0 ; i < NWM_LABELS ; i++)
    {
      MRIcopyLabel(mri_aseg, mri_ctrl, aseg_wm_labels[i]) ;
    }
    printf("removing outliers in the aseg WM...\n") ;
    MRIremoveWMOutliersAndRetainMedialSurface(mri_dst,
        mri_ctrl,
        mri_ctrl,
        intensity_below) ;
    MRIbinarize(mri_ctrl, mri_ctrl, 1, CONTROL_NONE, CONTROL_MARKED) ;
    MRInormAddFileControlPoints(mri_ctrl, CONTROL_MARKED) ;

    if (interior_fname1)
    {
      MRIS *mris_interior1, *mris_interior2 ;
      mris_interior1 = MRISread(interior_fname1) ;
      if (mris_interior1 == NULL)
        ErrorExit(ERROR_NOFILE,
                  "%s: could not read white matter surface from %s\n",
                  Progname, interior_fname1) ;
      mris_interior2 = MRISread(interior_fname2) ;
      if (mris_interior2 == NULL)
        ErrorExit(ERROR_NOFILE,
                  "%s: could not read white matter surface from %s\n",
                  Progname, interior_fname2) ;
      add_interior_points(mri_ctrl,
                          mri_dst,
                          intensity_above,
                          1.25*intensity_below,
                          mris_interior1,
                          mris_interior2,
                          mri_aseg,
                          mri_ctrl) ;
      MRISfree(&mris_interior1) ;
      MRISfree(&mris_interior2) ;
    }
    if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
    {
      MRIwrite(mri_ctrl, "norm_ctrl.mgz") ;
    }

    printf("Building bias image\n");
    fflush(stdout);
    fflush(stderr);
    mri_bias = MRIbuildBiasImage(mri_dst, mri_ctrl, NULL, 0.0) ;
    fflush(stdout);
    fflush(stderr);

    if (bias_sigma> 0)
    {
      printf("Smoothing with sigma %g\n",bias_sigma);
      MRI *mri_kernel = MRIgaussian1d(bias_sigma, -1) ;
      MRIconvolveGaussian(mri_bias, mri_bias, mri_kernel) ;
      MRIfree(&mri_kernel);
      fflush(stdout);
      fflush(stderr);
    }
    MRIfree(&mri_ctrl) ;
    MRIfree(&mri_aseg) ;
    printf("Applying bias correction\n");
    mri_dst = MRIapplyBiasCorrectionSameGeometry
              (mri_dst, mri_bias, mri_dst,
               DEFAULT_DESIRED_WHITE_MATTER_VALUE) ;
    if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
    {
      MRIwrite(mri_dst, "norm_1.mgz") ;
    }
    fflush(stdout);
    fflush(stderr);
  } // if(mri_aseg)
  else
  {
    printf("processing without aseg, no1d=%d\n",no1d);
    if (!no1d)
    {
      printf("MRInormInit(): \n");
      MRInormInit(mri_src, &mni, 0, 0, 0, 0, 0.0f) ;
      printf("MRInormalize(): \n");
      mri_dst = MRInormalize(mri_src, NULL, &mni) ;
      if (!mri_dst)
      {
        no1d = 1 ;
        printf("1d normalization failed - trying no1d...\n") ;
        // ErrorExit(ERROR_BADPARM, "%s: normalization failed", Progname) ;
      }
    }
    if(no1d)
    {
      if ((file_only && nosnr) ||
          ((gentle_flag != 0) && (control_point_fname != NULL)))
      {
        if (mri_dst == NULL)
        {
          mri_dst = MRIcopy(mri_src, NULL) ;
        }
      }
      else
      {
        if (nosnr)
        {
          if (interior_fname1)
          {
            MRIS *mris_interior1, *mris_interior2 ;
            MRI  *mri_ctrl ;

            printf("computing initial normalization using surface interiors\n");
            mri_ctrl = MRIcloneDifferentType(mri_src, MRI_UCHAR) ;
            mris_interior1 = MRISread(interior_fname1) ;
            if (mris_interior1 == NULL)
              ErrorExit(ERROR_NOFILE,
                        "%s: could not read white matter surface from %s\n",
                        Progname, interior_fname1) ;
            mris_interior2 = MRISread(interior_fname2) ;
            if (mris_interior2 == NULL)
              ErrorExit(ERROR_NOFILE,
                        "%s: could not read white matter surface from %s\n",
                        Progname, interior_fname2) ;
            add_interior_points(mri_ctrl,
                                mri_dst,
                                intensity_above,
                                1.25*intensity_below,
                                mris_interior1,
                                mris_interior2,
                                mri_aseg,
                                mri_ctrl) ;
            MRISfree(&mris_interior1) ;
            MRISfree(&mris_interior2) ;
            mri_bias = MRIbuildBiasImage(mri_dst, mri_ctrl, NULL, 0.0) ;
            if (bias_sigma> 0)
            {
              MRI *mri_kernel = MRIgaussian1d(bias_sigma, -1) ;
              MRIconvolveGaussian(mri_bias, mri_bias, mri_kernel) ;
              MRIfree(&mri_kernel);
            }
            mri_dst = MRIapplyBiasCorrectionSameGeometry
                      (mri_src,
                       mri_bias,
                       mri_dst,
                       DEFAULT_DESIRED_WHITE_MATTER_VALUE) ;
            MRIfree(&mri_ctrl) ;
          }
          else if (long_flag == 0)  // no initial normalization specified
          {
            mri_dst = MRIcopy(mri_src, NULL) ;
          }
        }
        else
        {
          printf("computing initial normalization using SNR...\n") ;
          mri_dst = MRInormalizeHighSignalLowStd
                    (mri_src, mri_dst, bias_sigma,
                     DEFAULT_DESIRED_WHITE_MATTER_VALUE) ;
        }
      }
      if (!mri_dst)
        ErrorExit
        (ERROR_BADPARM, "%s: could not allocate volume", Progname) ;
    }
  } // else (not using aseg)
  fflush(stdout);
  fflush(stderr);

  if (file_only == 0)
    MRI3dGentleNormalize(mri_dst, NULL, DEFAULT_DESIRED_WHITE_MATTER_VALUE,
                         mri_dst,
                         intensity_above, intensity_below/2,
                         file_only, bias_sigma, mri_not_control);

  mri_orig = MRIcopy(mri_dst, NULL) ;
  printf("\n");
  printf("Iterating %d times\n",num_3d_iter);
  for (n = 0 ; n < num_3d_iter ; n++)
  {
    if(file_only)
    {
      break ;
    }

    printf( "---------------------------------\n");
    printf( "3d normalization pass %d of %d\n", n+1, num_3d_iter) ;
    if (gentle_flag)
      MRI3dGentleNormalize(mri_dst, NULL, DEFAULT_DESIRED_WHITE_MATTER_VALUE,
                           mri_dst,
                           intensity_above/2, intensity_below/2,
                           file_only, bias_sigma, mri_not_control);
    else
      MRI3dNormalize(mri_orig, mri_dst, DEFAULT_DESIRED_WHITE_MATTER_VALUE,
                     mri_dst,
                     intensity_above, intensity_below,
                     file_only, prune, bias_sigma, scan_type, mri_not_control);
  }
  printf( "Done iterating ---------------------------------\n");

  // this just setup writing control-point volume saving
  if(control_volume_fname)
  {
    MRI3dWriteControlPoints(control_volume_fname) ;
  }

  if(bias_volume_fname)
  {
    mri_bias = compute_bias(mri_src, mri_dst, NULL) ;
    printf("writing bias field to %s....\n", bias_volume_fname) ;
    MRIwrite(mri_bias, bias_volume_fname) ;
    MRIfree(&mri_bias) ;
  }

  if (verbose)
  {
    printf("writing output to %s\n", out_fname) ;
  }
  MRIwrite(mri_dst, out_fname) ;
  msec = TimerStop(&start) ;

  MRIfree(&mri_src);
  MRIfree(&mri_dst);

  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  printf( "3D bias adjustment took %d minutes and %d seconds.\n",
          minutes, seconds) ;
  exit(0) ;
  return(0) ;
}
Esempio n. 4
0
static MRI *
MRIremoveWMOutliersAndRetainMedialSurface(MRI *mri_src,
                                          MRI *mri_src_ctrl,
                                          MRI *mri_dst_ctrl,
                                          int intensity_below)
{
  MRI  *mri_inside, *mri_bin ;
  HISTOGRAM *histo, *hsmooth ;
  int   wm_peak, x, y, z, nremoved ;
  float thresh, hi_thresh ;
  double val, lmean, max ;

  if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
  {
    MRIwrite(mri_src_ctrl, "sc.mgz") ;
  }
  if (mri_dst_ctrl != mri_src_ctrl)
  {
    mri_dst_ctrl = MRIcopy(mri_src_ctrl, mri_dst_ctrl) ;
  }
  mri_inside = MRIerode(mri_dst_ctrl, NULL) ;
  MRIbinarize(mri_inside, mri_inside, 1, 0, 1) ;

  histo = MRIhistogramLabel(mri_src, mri_inside, 1, 256) ;
  hsmooth = HISTOcopy(histo, NULL) ;
  HISTOsmooth(histo, hsmooth, 2) ;
  if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
  {
    HISTOplot(histo, "h.plt") ;
    HISTOplot(hsmooth, "hs.plt") ;
  }
  printf("using wm (%d) threshold %2.1f for removing exterior voxels\n",
         wm_peak, thresh) ;
  wm_peak = HISTOfindHighestPeakInRegion(hsmooth, 1, hsmooth->nbins-1) ;
  wm_peak = hsmooth->bins[wm_peak] ;
  thresh = wm_peak-intensity_below ;
  hi_thresh = wm_peak-.5*intensity_below ;
  printf("using wm (%d) threshold %2.1f for removing exterior voxels\n",
         wm_peak, thresh) ;

  // now remove stuff that's on the border and is pretty dark
  for (nremoved = x = 0 ; x < mri_src->width ; x++)
  {
    for (y = 0 ; y < mri_src->height ; y++)
    {
      for (z = 0 ; z < mri_src->depth ; z++)
      {
        if (x == Gx && y == Gy && z == Gz)
        {
          DiagBreak() ;
        }
        /* if it's a control point,
            it's not in the interior of the wm,
            and it's T1 val is too low */
        if (MRIgetVoxVal(mri_dst_ctrl, x, y, z, 0) == 0)
        {
          continue ;  // not a  control point
        }

        /* if it's way far from the wm mode
            then remove it even if it's in the interior */
        val = MRIgetVoxVal(mri_src, x, y, z, 0) ;
        if (val < thresh-5)
        {
          MRIsetVoxVal(mri_dst_ctrl, x, y, z, 0, 0) ;
          nremoved++ ;
        }

        if (nint(MRIgetVoxVal(mri_inside, x, y, z, 0)) > 0)
          // don't process interior voxels further
        {
          continue ;  // in the interior
        }
        if (val < thresh)
        {
          MRIsetVoxVal(mri_dst_ctrl, x, y, z, 0, 0) ;
          nremoved++ ;
        }
        else
        {
          lmean =
            MRImeanInLabelInRegion(mri_src, mri_inside, 1, x, y, z, 7);
          if (val < lmean-10)
          {
            MRIsetVoxVal(mri_dst_ctrl, x, y, z, 0, 0) ;
            nremoved++ ;
          }
        }
      }
    }
  }

#if 0
  for (x = 0 ; x < mri_src->width ; x++)
  {
    for (y = 0 ; y < mri_src->height ; y++)
    {
      for (z = 0 ; z < mri_src->depth ; z++)
      {
        if (x == Gx && y == Gy && z == Gz)
        {
          DiagBreak() ;
        }
        /* if it's a control point,
            it's not in the interior of the wm,
            and it's T1 val is too low */
        if (MRIgetVoxVal(mri_dst_ctrl, x, y, z, 0) == 0)
        {
          continue ;  // not a  control point
        }
        if (MRIcountNonzeroInNbhd(mri_dst_ctrl,3, x, y, z)<=2)
        {
          MRIsetVoxVal(mri_dst_ctrl, x, y, z, 0, 0) ;
          nremoved++ ;
        }
      }
    }
  }
#endif

  /* now take out voxels that have too big an intensity diff
     with surrounding ones */
  mri_bin = MRIbinarize(mri_dst_ctrl, NULL, 1, 0, 1) ;
  for (x = 0 ; x < mri_src->width ; x++)
  {
    for (y = 0 ; y < mri_src->height ; y++)
    {
      for (z = 0 ; z < mri_src->depth ; z++)
      {
        if (x == Gx && y == Gy && z == Gz)
        {
          DiagBreak() ;
        }
        /* if it's a control point,
            it's not in the interior of the wm,
            and it's T1 val is too low */
        if (MRIgetVoxVal(mri_dst_ctrl, x, y, z, 0) == 0)
        {
          continue ;  // not a  control point
        }
        val = MRIgetVoxVal(mri_src, x, y, z, 0) ;
        max = MRImaxInLabelInRegion(mri_src, mri_bin, 1, x, y, z, 3);
        if (val+7 < max && val < hi_thresh)
        {
          MRIsetVoxVal(mri_dst_ctrl, x, y, z, 0, 0) ;
          nremoved++ ;
        }
      }
    }
  }
  MRIfree(&mri_bin) ;

  printf( "%d control points removed\n", nremoved) ;
  if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
  {
    MRIwrite(mri_dst_ctrl, "dc.mgz") ;
  }
  HISTOfree(&histo) ;
  HISTOfree(&hsmooth) ;
  MRIfree(&mri_inside) ;
  return(mri_dst_ctrl) ;
}
Esempio n. 5
0
static MRI *
MRIremoveWMOutliers(MRI *mri_src, MRI *mri_src_ctrl, MRI *mri_dst_ctrl,
                    int intensity_below)
{
  MRI       *mri_bin, *mri_outliers = NULL ;
  float     max, thresh, val;
  HISTOGRAM *histo, *hsmooth ;
  int       wm_peak, x, y, z, nremoved = 0, whalf = 5, total  ;

  if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
  {
    MRIwrite(mri_src_ctrl, "sc.mgz") ;
  }

  if (mri_dst_ctrl == NULL)
  {
    mri_dst_ctrl = MRIcopy(mri_src_ctrl, NULL) ;
  }
  mri_bin = MRIbinarize(mri_src_ctrl, NULL, 1, 0, CONTROL_MARKED) ;
  histo = MRIhistogramLabel(mri_src, mri_bin, 1, 256) ;
  hsmooth = HISTOcopy(histo, NULL) ;
  HISTOsmooth(histo, hsmooth, 2) ;
  if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
  {
    HISTOplot(histo, "h.plt") ;
    HISTOplot(hsmooth, "hs.plt") ;
  }
  wm_peak = HISTOfindHighestPeakInRegion(hsmooth, 1, hsmooth->nbins-1) ;
  wm_peak = hsmooth->bins[wm_peak] ;
  thresh = wm_peak-intensity_below ;

  HISTOfree(&histo) ;
  HISTOfree(&hsmooth) ;
  if (Gdiag & DIAG_WRITE)
  {
    mri_outliers = MRIclone(mri_dst_ctrl, NULL) ;
  }
  for (total = x = 0 ; x < mri_src->width ; x++)
  {
    for (y = 0 ; y < mri_src->height ; y++)
    {
      for (z = 0 ; z < mri_src->depth ; z++)
      {
        if (x == Gx && y == Gy && z == Gz)
        {
          DiagBreak() ;
        }
        if (nint(MRIgetVoxVal(mri_dst_ctrl, x, y, z, 0)) == 0)
        {
          continue ;
        }
        max = MRImaxInLabelInRegion(mri_src, mri_bin, 1, x, y, z, whalf);
        val = MRIgetVoxVal(mri_src, x, y, z, 0) ;
        total++ ;
        if (val+intensity_below < max && val < thresh)
        {
          MRIsetVoxVal(mri_dst_ctrl, x, y, z, 0, 0) ;
          if (mri_outliers)
          {
            MRIsetVoxVal(mri_outliers, x, y, z, 0, 128) ;
          }
          nremoved++ ;
        }
      }
    }
  }

  printf( "%d control points removed (%2.1f%%)\n",
          nremoved, 100.0*(double)nremoved/(double)total) ;
  if (mri_outliers)
  {
    printf( "writing out.mgz outlier volume\n") ;
    MRIwrite(mri_outliers, "out.mgz") ;
    MRIfree(&mri_outliers) ;
  }
  if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
  {
    MRIwrite(mri_dst_ctrl, "dc.mgz") ;
  }
  MRIfree(&mri_bin) ;
  return(mri_dst_ctrl);
}
Esempio n. 6
0
static MRI *
MRIremoveWMOutliersAndRetainMedialSurface(MRI *mri_src,
                                          MRI *mri_src_ctrl,
                                          MRI *mri_dst_ctrl,
                                          int intensity_below)
{
  MRI       *mri_bin, *mri_dist, *mri_dist_sup, *mri_outliers = NULL ;
  float     max, thresh, val;
  HISTOGRAM *histo, *hsmooth ;
  int       wm_peak, x, y, z, nremoved = 0, whalf = 5 ;

  if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
  {
    MRIwrite(mri_src_ctrl, "sc.mgz") ;
  }

  mri_bin = MRIbinarize(mri_dst_ctrl, NULL, 1, 0, 1) ;
  mri_dist = MRIdistanceTransform(mri_bin, NULL, 1, -1,
                                  DTRANS_MODE_SIGNED, NULL);
  MRIscalarMul(mri_dist, mri_dist, -1) ;
  mri_dist_sup = MRInonMaxSuppress(mri_dist, NULL, 0, 1) ;
  mri_dst_ctrl = MRIbinarize(mri_dist_sup, mri_dst_ctrl, 1, 0, 1) ;
  histo = MRIhistogramLabel(mri_src, mri_src_ctrl, 1, 256) ;
  hsmooth = HISTOcopy(histo, NULL) ;
  HISTOsmooth(histo, hsmooth, 2) ;
  if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
  {
    HISTOplot(histo, "h.plt") ;
    HISTOplot(hsmooth, "hs.plt") ;
  }
  wm_peak = HISTOfindHighestPeakInRegion(hsmooth, 1, hsmooth->nbins-1) ;
  wm_peak = hsmooth->bins[wm_peak] ;
  thresh = wm_peak-intensity_below ;

  HISTOfree(&histo) ;
  HISTOfree(&hsmooth) ;
  if (Gdiag & DIAG_WRITE)
  {
    mri_outliers = MRIclone(mri_dst_ctrl, NULL) ;
  }
  for (x = 0 ; x < mri_src->width ; x++)
  {
    for (y = 0 ; y < mri_src->height ; y++)
    {
      for (z = 0 ; z < mri_src->depth ; z++)
      {
        if (x == Gx && y == Gy && z == Gz)
        {
          DiagBreak() ;
        }
        if (nint(MRIgetVoxVal(mri_dst_ctrl, x, y, z, 0)) == 0)
        {
          continue ;
        }
        max = MRImaxInLabelInRegion(mri_src, mri_dst_ctrl, 1, x, y, z, whalf);
        val = MRIgetVoxVal(mri_src, x, y, z, 0) ;
        if (val+intensity_below < max && val < thresh)
        {
          MRIsetVoxVal(mri_dst_ctrl, x, y, z, 0, 0) ;
          if (mri_outliers)
          {
            MRIsetVoxVal(mri_outliers, x, y, z, 0, 128) ;
          }
          nremoved++ ;
        }
      }
    }
  }

  printf( "%d control points removed\n", nremoved) ;
  if (mri_outliers)
  {
    printf( "writing out.mgz outlier volume\n") ;
    MRIwrite(mri_outliers, "out.mgz") ;
    MRIfree(&mri_outliers) ;
  }
  if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
  {
    MRIwrite(mri_dst_ctrl, "dc.mgz") ;
  }
  MRIfree(&mri_bin) ;
  MRIfree(&mri_dist);
  MRIfree(&mri_dist_sup);
  return(mri_dst_ctrl);
}
Esempio n. 7
0
int
main(int argc, char *argv[]) {
    char         **av, fname[STRLEN], *out_fname, *subject_name, *cp ;
    int          ac, nargs, i, n, noint = 0, options ;
    int          msec, minutes, seconds, nsubjects, input ;
    struct timeb start ;
    GCA          *gca ;
    MRI          *mri_seg, *mri_tmp, *mri_inputs ;
    TRANSFORM    *transform ;
    LTA          *lta;
    GCA_BOUNDARY *gcab ;

    Progname = argv[0] ;

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

    TimerStart(&start) ;

    parms.use_gradient = 0 ;
    spacing = 8 ;

    /* rkt: check for and handle version tag */
    nargs = handle_version_option
            (argc, argv,
             "$Id: mri_gcab_train.c,v 1.4 2011/03/16 20:23:33 fischl Exp $",
             "$Name:  $");
    if (nargs && argc - nargs == 1)
        exit (0);
    argc -= nargs;

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

    printf("reading gca from %s\n", argv[1]) ;
    gca = GCAread(argv[1]) ;
    if (!gca)
        exit(Gerror) ;

    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 < 4)
            usage_exit(1) ;
    }

    // options parsed.   subjects and gca name remaining
    out_fname = argv[argc-1] ;
    nsubjects = argc-3 ;
    for (options = i = 0 ; i < nsubjects ; i++) {
        if (argv[i+1][0] == '-') {
            nsubjects-- ;
            options++ ;
        }
    }

    printf("training on %d subject and writing results to %s\n",
           nsubjects, out_fname) ;

    n = 0 ;

    gcab = GCABalloc(gca, 8, 0, 30, 10, target_label);
    strcpy(gcab->gca_fname, argv[1]) ;
    // going through the subject one at a time
    for (nargs = i = 0 ; i < nsubjects+options ; i++) {
        subject_name = argv[i+2] ;
        //////////////////////////////////////////////////////////////
        printf("***************************************"
               "************************************\n");
        printf("processing subject %s, %d of %d...\n", subject_name,i+1-nargs,
               nsubjects);

        if (stricmp(subject_name, "-NOINT") == 0) {
            printf("not using intensity information for subsequent subjects...\n");
            noint = 1 ;
            nargs++ ;
            continue ;
        } else if (stricmp(subject_name, "-INT") == 0) {
            printf("using intensity information for subsequent subjects...\n");
            noint = 0 ;
            nargs++ ;
            continue ;
        }
        // reading this subject segmentation
        sprintf(fname, "%s/%s/mri/%s", subjects_dir, subject_name, seg_dir) ;
        if (Gdiag & DIAG_SHOW && DIAG_VERBOSE_ON)
            fprintf(stderr, "Reading segmentation from %s...\n", fname) ;
        mri_seg = MRIread(fname) ;
        if (!mri_seg)
            ErrorExit(ERROR_NOFILE, "%s: could not read segmentation file %s",
                      Progname, fname) ;
        if ((mri_seg->type != MRI_UCHAR) && (mri_seg->type != MRI_FLOAT)) {
            ErrorExit
            (ERROR_NOFILE,
             "%s: segmentation file %s is not type UCHAR or FLOAT",
             Progname, fname) ;
        }

        if (binarize) {
            int j ;
            for (j = 0 ; j < 256 ; j++) {
                if (j == binarize_in)
                    MRIreplaceValues(mri_seg, mri_seg, j, binarize_out) ;
                else
                    MRIreplaceValues(mri_seg, mri_seg, j, 0) ;
            }
        }
        if (insert_fname) {
            MRI *mri_insert ;

            sprintf(fname, "%s/%s/mri/%s",
                    subjects_dir, subject_name, insert_fname) ;
            mri_insert = MRIread(fname) ;
            if (mri_insert == NULL)
                ErrorExit(ERROR_NOFILE,
                          "%s: could not read volume from %s for insertion",
                          Progname, insert_fname) ;

            MRIbinarize(mri_insert, mri_insert, 1, 0, insert_label) ;
            MRIcopyLabel(mri_insert, mri_seg, insert_label) ;
            MRIfree(&mri_insert) ;
        }

        replaceLabels(mri_seg) ;
        MRIeraseBorderPlanes(mri_seg, 1) ;

        for (input = 0 ; input < gca->ninputs ; input++) {
            //////////// set the gca type //////////////////////////////
            // is this T1/PD training?
            // how can we allow flash data training ???????
            // currently checks the TE, TR, FA to be the same for all inputs
            // thus we cannot allow flash data training.
            ////////////////////////////////////////////////////////////

            sprintf(fname, "%s/%s/mri/%s",
                    subjects_dir, subject_name,input_names[input]);
            if (DIAG_VERBOSE_ON)
                printf("reading co-registered input from %s...\n", fname) ;
            fprintf(stderr, "   reading input %d: %s\n", input, fname);
            mri_tmp = MRIread(fname) ;
            if (!mri_tmp)
                ErrorExit
                (ERROR_NOFILE,
                 "%s: could not read image from file %s", Progname, fname) ;
            // input check 1
            if (getSliceDirection(mri_tmp) != MRI_CORONAL) {
                ErrorExit
                (ERROR_BADPARM,
                 "%s: must be in coronal direction, but it is not\n",
                 fname);
            }
            // input check 2
            if (mri_tmp->xsize != 1 || mri_tmp->ysize != 1 || mri_tmp->zsize != 1) {
                ErrorExit
                (ERROR_BADPARM,
                 "%s: must have 1mm voxel size, but have (%f, %f, %f)\n",
                 fname, mri_tmp->xsize, mri_tmp->ysize, mri_tmp->ysize);
            }
            // input check 3 is removed.  now we can handle c_(ras) != 0 case
            // input check 4
            if (i == 0) {
                TRs[input] = mri_tmp->tr ;
                FAs[input] = mri_tmp->flip_angle ;
                TEs[input] = mri_tmp->te ;
            } else if (!FEQUAL(TRs[input],mri_tmp->tr) ||
                       !FEQUAL(FAs[input],mri_tmp->flip_angle) ||
                       !FEQUAL(TEs[input], mri_tmp->te))
                ErrorExit
                (ERROR_BADPARM,
                 "%s: subject %s input volume %s: sequence parameters "
                 "(%2.1f, %2.1f, %2.1f)"
                 "don't match other inputs (%2.1f, %2.1f, %2.1f)",
                 Progname, subject_name, fname,
                 mri_tmp->tr, DEGREES(mri_tmp->flip_angle), mri_tmp->te,
                 TRs[input], DEGREES(FAs[input]), TEs[input]) ;
            // first time do the following
            if (input == 0) {
                int nframes = gca->ninputs ;

                ///////////////////////////////////////////////////////////
                mri_inputs =
                    MRIallocSequence(mri_tmp->width, mri_tmp->height, mri_tmp->depth,
                                     mri_tmp->type, nframes) ;
                if (!mri_inputs)
                    ErrorExit
                    (ERROR_NOMEMORY,
                     "%s: could not allocate input volume %dx%dx%dx%d",
                     mri_tmp->width, mri_tmp->height, mri_tmp->depth,nframes) ;
                MRIcopyHeader(mri_tmp, mri_inputs) ;
            }
            // -mask option ////////////////////////////////////////////
            if (mask_fname)
            {
                MRI *mri_mask ;

                sprintf(fname, "%s/%s/mri/%s",
                        subjects_dir, subject_name, mask_fname);
                printf("reading volume %s for masking...\n", fname) ;
                mri_mask = MRIread(fname) ;
                if (!mri_mask)
                    ErrorExit(ERROR_NOFILE, "%s: could not open mask volume %s.\n",
                              Progname, fname) ;

                MRImask(mri_tmp, mri_mask, mri_tmp, 0, 0) ;
                MRIfree(&mri_mask) ;
            }
            MRIcopyFrame(mri_tmp, mri_inputs, 0, input) ;
            MRIfree(&mri_tmp) ;
        }// end of inputs per subject


        /////////////////////////////////////////////////////////
        // xform_name is given, then we can use the consistent c_(r,a,s) for gca
        /////////////////////////////////////////////////////////
        if (xform_name)
        {
            // we read talairach.xfm which is a RAS-to-RAS
            sprintf(fname, "%s/%s/mri/transforms/%s",
                    subjects_dir, subject_name, xform_name) ;
            if (Gdiag & DIAG_SHOW && DIAG_VERBOSE_ON)
                printf("INFO: reading transform file %s...\n", fname);
            if (!FileExists(fname))
            {
                fprintf(stderr,"ERROR: cannot find transform file %s\n",fname);
                exit(1);
            }
            transform = TransformRead(fname);
            if (!transform)
                ErrorExit(ERROR_NOFILE, "%s: could not read transform from file %s",
                          Progname, fname);

            modify_transform(transform, mri_inputs, gca);
            // Here we do 2 things
            // 1. modify gca direction cosines to
            // that of the transform destination (both linear and non-linear)
            // 2. if ras-to-ras transform,
            // then change it to vox-to-vox transform (linear case)

            // modify transform to store inverse also
            TransformInvert(transform, mri_inputs) ;
            // verify inverse
            lta = (LTA *) transform->xform;
        }
        else
        {
            GCAreinit(mri_inputs, gca);
            // just use the input value, since dst = src volume
            transform = TransformAlloc(LINEAR_VOXEL_TO_VOXEL, NULL) ;
        }


        ////////////////////////////////////////////////////////////////////
        // train gca
        ////////////////////////////////////////////////////////////////////
        // segmentation is seg volume
        // inputs       is the volumes of all inputs
        // transform    is for this subject
        // noint        is whether to use intensity information or not
        GCABtrain(gcab, mri_inputs, mri_seg, transform, target_label) ;
        MRIfree(&mri_seg) ;
        MRIfree(&mri_inputs) ;
        TransformFree(&transform) ;
    }
    GCABcompleteTraining(gcab) ;

    if (smooth > 0) {
        printf("regularizing conditional densities with smooth=%2.2f\n", smooth) ;
        GCAregularizeConditionalDensities(gca, smooth) ;
    }
    if (navgs) {
        printf("applying mean filter %d times to conditional densities\n", navgs) ;
        GCAmeanFilterConditionalDensities(gca, navgs) ;
    }

    printf("writing trained GCAB to %s...\n", out_fname) ;
    if (GCABwrite(gcab, out_fname) != NO_ERROR)
        ErrorExit
        (ERROR_BADFILE, "%s: could not write gca to %s", Progname, out_fname) ;

    if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
    {
        MRI *mri ;

        mri = GCAbuildMostLikelyVolume(gca, NULL) ;
        MRIwrite(mri, "m.mgz") ;
        MRIfree(&mri) ;
    }

    if (histo_fname) {
        FILE *fp ;
        int   histo_counts[10000], xn, yn, zn, max_count ;
        GCA_NODE  *gcan ;

        memset(histo_counts, 0, sizeof(histo_counts)) ;
        fp = fopen(histo_fname, "w") ;
        if (!fp)
            ErrorExit(ERROR_BADFILE, "%s: could not open histo file %s",
                      Progname, histo_fname) ;

        max_count = 0 ;
        for (xn = 0 ; xn < gca->node_width;  xn++) {
            for (yn = 0 ; yn < gca->node_height ; yn++) {
                for (zn = 0 ; zn < gca->node_depth ; zn++) {
                    gcan = &gca->nodes[xn][yn][zn] ;
                    if (gcan->nlabels < 1)
                        continue ;
                    if (gcan->nlabels == 1 && IS_UNKNOWN(gcan->labels[0]))
                        continue ;
                    histo_counts[gcan->nlabels]++ ;
                    if (gcan->nlabels > max_count)
                        max_count = gcan->nlabels ;
                }
            }
        }
        max_count = 20 ;
        for (xn = 1 ; xn < max_count ;  xn++)
            fprintf(fp, "%d %d\n", xn, histo_counts[xn]) ;
        fclose(fp) ;
    }

    GCAfree(&gca) ;
    msec = TimerStop(&start) ;
    seconds = nint((float)msec/1000.0f) ;
    minutes = seconds / 60 ;
    seconds = seconds % 60 ;
    printf("classifier array training took %d minutes"
           " and %d seconds.\n", minutes, seconds) ;
    exit(0) ;
    return(0) ;
}
Esempio n. 8
0
int
main(int argc, char *argv[]) {
  char   **av, *cp ;
  int    ac, nargs, i, dof, no_transform, which, sno = 0, nsubjects = 0 ;
  MRI    *mri=0, *mri_mean = NULL, *mri_std=0, *mri_T1=0,*mri_binary=0,*mri_dof=NULL,
                             *mri_priors = NULL ;
  char   *subject_name, *out_fname, fname[STRLEN] ;
  /*  LTA    *lta;*/
  MRI *mri_tmp=0 ;

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

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

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

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

  if (argc < 3)  usage_exit(1) ;

  out_fname = argv[argc-1] ;

  no_transform = first_transform ;
  if (binary_name)   /* generate binarized volume with priors and */
  {                  /* separate means and variances */
    for (which = BUILD_PRIORS ; which <= OFF_STATS ; which++) {
      /* for each subject specified on cmd line */
      for (dof = 0, i = 1 ; i < argc-1 ; i++) {
        if (*argv[i] == '-')   /* don't do transform for next subject */
        { no_transform = 1 ;
          continue ;
        }
        dof++ ;
        subject_name = argv[i] ;
        if (which != BUILD_PRIORS) {
          sprintf(fname, "%s/%s/mri/%s", subjects_dir, subject_name, T1_name);
          fprintf(stderr, "%d of %d: reading %s...\n", i, argc-2, fname) ;
          mri_T1 = MRIread(fname) ;
          if (!mri_T1)
            ErrorExit(ERROR_NOFILE,"%s: could not open volume %s",
                      Progname,fname);
        }

        sprintf(fname, "%s/%s/mri/%s",subjects_dir,subject_name,binary_name);
        fprintf(stderr, "%d of %d: reading %s...\n", i, argc-2, fname) ;
        mri_binary = MRIread(fname) ;
        if (!mri_binary)
          ErrorExit(ERROR_NOFILE,"%s: could not open volume %s",
                    Progname,fname);

        /* only count voxels which are mostly labeled */
        MRIbinarize(mri_binary, mri_binary, WM_MIN_VAL, 0, 100) ;
        if (transform_fname && no_transform-- <= 0) {
          sprintf(fname, "%s/%s/mri/transforms/%s",
                  subjects_dir, subject_name, transform_fname) ;

          fprintf(stderr, "reading transform %s...\n", fname) ;
          ////////////////////////////////////////////////////////
#if 1
          {
            TRANSFORM *transform ;
            transform = TransformRead(fname) ;
            if (transform == NULL)
              ErrorExit(ERROR_NOFILE, "%s: could not open transform file %s\n",Progname, fname) ;
            mri_tmp = TransformApply(transform, mri_T1, NULL) ;
            TransformFree(&transform) ;
          }
#else
          lta = LTAreadEx(fname);
          if (lta == NULL)
            ErrorExit(ERROR_NOFILE,
                      "%s: could not open transform file %s\n",
                      Progname, fname) ;
          /* LTAtransform() runs either MRIapplyRASlinearTransform()
          for RAS2RAS or MRIlinearTransform() for Vox2Vox. */
          /* MRIlinearTransform() calls MRIlinearTransformInterp() */
          mri_tmp = LTAtransform(mri_T1, NULL, lta);
          MRIfree(&mri_T1) ;
          mri_T1 = mri_tmp ;
          LTAfree(&lta);
          lta = NULL;
#endif
          if (DIAG_VERBOSE_ON)
            fprintf(stderr, "transform application complete.\n") ;
        }
        if (which == BUILD_PRIORS) {
          mri_priors =
            MRIupdatePriors(mri_binary, mri_priors) ;
        } else {
          if (!mri_mean) {
            mri_dof = MRIalloc(mri_T1->width, mri_T1->height, mri_T1->depth,
                               MRI_UCHAR) ;
            mri_mean =
              MRIalloc(mri_T1->width, mri_T1->height,mri_T1->depth,MRI_FLOAT);
            mri_std =
              MRIalloc(mri_T1->width,mri_T1->height,mri_T1->depth,MRI_FLOAT);
            if (!mri_mean || !mri_std)
              ErrorExit(ERROR_NOMEMORY, "%s: could not allocate templates.\n",
                        Progname) ;
          }

          if (DIAG_VERBOSE_ON)
            fprintf(stderr, "updating mean and variance estimates...\n") ;
          if (which == ON_STATS) {
            MRIaccumulateMaskedMeansAndVariances(mri_T1, mri_binary, mri_dof,
                                                 90, 100, mri_mean, mri_std) ;
            fprintf(stderr, "T1 = %d, binary = %d, mean = %2.1f\n",
                    (int)MRIgetVoxVal(mri_T1, 141,100,127,0),
                    MRIvox(mri_binary, 141,100,127),
                    MRIFvox(mri_mean, 141,100,127)) ;
          } else  /* computing means and vars for off */
            MRIaccumulateMaskedMeansAndVariances(mri_T1, mri_binary, mri_dof,
                                                 0, WM_MIN_VAL-1,
                                                 mri_mean, mri_std) ;
          MRIfree(&mri_T1) ;
        }
        MRIfree(&mri_binary) ;
      }

      if (which == BUILD_PRIORS) {
        mri = MRIcomputePriors(mri_priors, dof, NULL) ;
        MRIfree(&mri_priors) ;
        fprintf(stderr, "writing priors to %s...\n", out_fname) ;
      } else {
        MRIcomputeMaskedMeansAndStds(mri_mean, mri_std, mri_dof) ;
        mri_mean->dof = dof ;

        fprintf(stderr, "writing T1 means with %d dof to %s...\n", mri_mean->dof,
                out_fname) ;
        if (!which)
          MRIwrite(mri_mean, out_fname) ;
        else
          MRIappend(mri_mean, out_fname) ;
        MRIfree(&mri_mean) ;
        fprintf(stderr, "writing T1 variances to %s...\n", out_fname);
        if (dof <= 1)
          MRIreplaceValues(mri_std, mri_std, 0, 1) ;
        mri = mri_std ;
      }

      if (!which)
        MRIwrite(mri, out_fname) ;
      else
        MRIappend(mri, out_fname) ;
      MRIfree(&mri) ;
    }
  }
  else {
    /* for each subject specified on cmd line */

    if (xform_mean_fname) {
      m_xform_mean = MatrixAlloc(4,4,MATRIX_REAL) ;
      /* m_xform_covariance = MatrixAlloc(12,12,MATRIX_REAL) ;*/
    }

    dof = 0;
    for (i = 1 ; i < argc-1 ; i++) {

      if (*argv[i] == '-') {
        /* don't do transform for next subject */
        no_transform = 1 ;
        continue ;
      }
      dof++ ;

      subject_name = argv[i] ;
      sprintf(fname, "%s/%s/mri/%s", subjects_dir, subject_name, T1_name);
      fprintf(stderr, "%d of %d: reading %s...\n", i, argc-2, fname) ;
      mri_T1 = MRIread(fname) ;
      if (!mri_T1)
        ErrorExit(ERROR_NOFILE,"%s: could not open volume %s",Progname,fname);
      check_mri(mri_T1) ;

      if (binarize)
        MRIbinarize(mri_T1, mri_T1, binarize, 0, 1) ;
      if (erode) {
        int i ;
        printf("eroding input %d times\n", erode) ;
        for (i = 0 ; i < erode ; i++)
          MRIerode(mri_T1, mri_T1) ;
      }
      if (open) {
        int i ;
        printf("opening input %d times\n", open) ;
        for (i = 0 ; i < open ; i++)
          MRIerode(mri_T1, mri_T1) ;
        for (i = 0 ; i < open ; i++)
          MRIdilate(mri_T1, mri_T1) ;
      }

      check_mri(mri_T1) ;
      if (transform_fname) {

        sprintf(fname, "%s/%s/mri/transforms/%s",
                subjects_dir, subject_name, transform_fname) ;

        fprintf(stderr, "reading transform %s...\n", fname) ;
        ////////////////////////////////////////////////////////
#if 1
        {
          TRANSFORM *transform ;
          transform = TransformRead(fname) ;
          if (transform == NULL)
            ErrorExit(ERROR_NOFILE, "%s: could not open transform file %s\n",Progname, fname) ;
          mri_tmp = TransformApply(transform, mri_T1, NULL) ;
          if (DIAG_VERBOSE_ON)
            MRIwrite(mri_tmp, "t1.mgz") ;
          TransformFree(&transform) ;
        }
#else
        lta = LTAreadEx(fname);
        if (lta == NULL)
          ErrorExit(ERROR_NOFILE,
                    "%s: could not open transform file %s\n",
                    Progname, fname) ;
        printf("transform matrix -----------------------\n");
        MatrixPrint(stdout,lta->xforms[0].m_L);
        /* LTAtransform() runs either MRIapplyRASlinearTransform()
        for RAS2RAS or MRIlinearTransform() for Vox2Vox. */
        /* MRIlinearTransform() calls MRIlinearTransformInterp() */
        mri_tmp = LTAtransform(mri_T1, NULL, lta);
        printf("----- -----------------------\n");
        LTAfree(&lta);
#endif
        MRIfree(&mri_T1);
        mri_T1 = mri_tmp ; // reassign pointers
        if (DIAG_VERBOSE_ON)
          fprintf(stderr, "transform application complete.\n") ;
      }

      if (!mri_mean) {
        mri_mean =
          MRIalloc(mri_T1->width, mri_T1->height, mri_T1->depth, MRI_FLOAT) ;
        mri_std =
          MRIalloc(mri_T1->width, mri_T1->height, mri_T1->depth, MRI_FLOAT) ;
        if (!mri_mean || !mri_std)
          ErrorExit(ERROR_NOMEMORY, "%s: could not allocate templates.\n",
                    Progname) ;
        // if(transform_fname == NULL){
        if (DIAG_VERBOSE_ON)
          printf("Copying geometry\n");
        MRIcopyHeader(mri_T1,mri_mean);
        MRIcopyHeader(mri_T1,mri_std);
        // }
      }

      check_mri(mri_mean) ;
      if (!stats_only) {
        if (DIAG_VERBOSE_ON)
          fprintf(stderr, "updating mean and variance estimates...\n") ;
        MRIaccumulateMeansAndVariances(mri_T1, mri_mean, mri_std) ;
      }

      check_mri(mri_mean) ;
      if (DIAG_VERBOSE_ON)
        MRIwrite(mri_mean, "t2.mgz") ;
      MRIfree(&mri_T1) ;
      no_transform = 0;
    } /* end loop over subjects */

    if (xform_mean_fname) {
      FILE   *fp ;
      VECTOR *v = NULL, *vT = NULL ;
      MATRIX *m_vvT = NULL ;
      int    rows, cols ;

      nsubjects = sno ;

      fp = fopen(xform_covariance_fname, "w") ;
      if (!fp)
        ErrorExit(ERROR_NOFILE, "%s: could not open covariance file %s",
                  Progname, xform_covariance_fname) ;
      fprintf(fp, "nsubjects=%d\n", nsubjects) ;

      MatrixScalarMul(m_xform_mean, 1.0/(double)nsubjects, m_xform_mean) ;
      printf("means:\n") ;
      MatrixPrint(stdout, m_xform_mean) ;
      MatrixAsciiWrite(xform_mean_fname, m_xform_mean) ;

      /* subtract the mean from each transform */
      rows = m_xform_mean->rows ;
      cols = m_xform_mean->cols ;
      for (sno = 0 ; sno < nsubjects ; sno++) {
        MatrixSubtract(m_xforms[sno], m_xform_mean, m_xforms[sno]) ;
        v = MatrixReshape(m_xforms[sno], v, rows*cols, 1) ;
        vT = MatrixTranspose(v, vT) ;
        m_vvT = MatrixMultiply(v, vT, m_vvT) ;
        if (!m_xform_covariance)
          m_xform_covariance =
            MatrixAlloc(m_vvT->rows, m_vvT->cols,MATRIX_REAL) ;
        MatrixAdd(m_vvT, m_xform_covariance, m_xform_covariance) ;
        MatrixAsciiWriteInto(fp, m_xforms[sno]) ;
      }

      MatrixScalarMul(m_xform_covariance, 1.0/(double)nsubjects,
                      m_xform_covariance) ;
      printf("covariance:\n") ;
      MatrixPrint(stdout, m_xform_covariance) ;
      MatrixAsciiWriteInto(fp, m_xform_covariance) ;
      fclose(fp) ;
      if (stats_only)
        exit(0) ;
    }

    MRIcomputeMeansAndStds(mri_mean, mri_std, dof) ;
    check_mri(mri_mean) ;
    check_mri(mri_std) ;

    mri_mean->dof = dof ;

    if (smooth) {
      MRI *mri_kernel, *mri_smooth ;

      printf("applying smoothing kernel\n") ;
      mri_kernel = MRIgaussian1d(smooth, 100) ;
      mri_smooth = MRIconvolveGaussian(mri_mean, NULL, mri_kernel) ;
      MRIfree(&mri_kernel) ;
      MRIfree(&mri_mean) ;
      mri_mean = mri_smooth ;
    }
    fprintf(stderr, "\nwriting T1 means with %d dof to %s...\n", mri_mean->dof,
            out_fname) ;
    MRIwrite(mri_mean, out_fname) ;
    MRIfree(&mri_mean) ;
    if (dof <= 1) /* can't calculate variances - set them to reasonable val */
    {
      //               src      dst
      MRIreplaceValues(mri_std, mri_std, 0, 1) ;
    }
    if (!novar) {
      // mri_std contains the variance here  (does it?? I don't think so -- BRF)
      if (!var_fname) {
        fprintf(stderr, "\nwriting T1 standard deviations to %s...\n", out_fname);
        MRIappend(mri_std, out_fname) ;
      } else {
        fprintf(stderr, "\nwriting T1 standard deviations to %s...\n", var_fname);
        MRIwrite(mri_std, var_fname) ;
      }
    }
    MRIfree(&mri_std) ;
    if (mri)
      MRIfree(&mri);
  } /* end if binarize */
  return(0) ;
}
Esempio n. 9
0
MRI *
MRIfillBasalGanglia(MRI *mri_src, MRI *mri_dst)
{
    float  low_thresh, hi_thresh ;
    int    total_filled, depth, height, width, x, y, z,
           xi, yi, zi, xk, yk, zk, fill, val0, val, i ;
    MRI    *mri_bg ;
    Real   tx, ty, tz ;
    MRI_SEGMENTATION  *mriseg ;
    MRI_SEGMENT       *mseg ;
    float  dx_left, dx_right, dy, dz, dist_left, dist_right ;

    if (!mri_dst)
    {
        mri_dst = MRIcopy(mri_src, NULL) ;
    }
    mri_bg = MRIclone(mri_src, NULL) ;

    width = mri_src->width ;
    height = mri_src->height ;
    depth = mri_src->depth ;
    low_thresh = 85 ;
    hi_thresh =  105 ;
    total_filled = 0 ;
    for (z = 0 ; z < depth ; z++)
    {
        for (y = 0 ; y < height ; y++)
        {
            for (x = 0 ; x < width ; x++)
            {
                if (x == 152 && y == 117 && z == 132)  /* 93 */
                {
                    DiagBreak() ;
                }
                val0 = MRIgetVoxVal(mri_src, x, y, z, 0) ;
#if 0
                if (val0 >= low_thresh && val0 <= hi_thresh &&
                        MRIvox(mri_dst,x,y,z) < WM_MIN_VAL)
#else
                if (val0 >= 85 && val0 <= 105)
#endif
                {
#undef WHALF
#undef WSIZE
#define WSIZE   7
#define WHALF  ((WSIZE-1)/2)
                    fill = 1 ;
                    for (zk = -WHALF ; fill && zk <= WHALF ; zk++)
                    {
                        zi = mri_src->zi[z+zk] ;
                        for (yk = -WHALF ; fill && yk <= WHALF ; yk++)
                        {
                            yi = mri_src->yi[y+yk] ;
                            for (xk = -WHALF ; fill && xk <= WHALF ; xk++)
                            {
                                xi = mri_src->xi[x+xk] ;
                                val = MRIgetVoxVal(mri_src, xi, yi, zi, 0) ;
                                if (val < 85 || val > 110)
                                {
                                    fill = 0 ;  /* not homogeneous enough */
                                }
                            }
                        }
                    }
                }
                else
                {
                    fill = 0 ;
                }
                if (fill)
                {
                    total_filled++ ;
                }
                if (fill)
                {
                    MRIsetVoxVal(mri_bg, x, y, z, 0, BASAL_GANGLIA_FILL) ;
                }
            }
        }
    }

    MRIclose(mri_bg, mri_bg) ;  /* remove small holes */

    /* segment into connected components */
    mriseg = MRIsegment(mri_bg, 1, 255) ;
    fprintf(stderr, "segmenting thick gray regions: %d %d mm segments found\n",
            mriseg->nsegments, WSIZE) ;

    /* dilate into regions that are not on */
    for (i = 0 ; i < 2*WSIZE ; i++)
    {
        MRIsegmentDilateThreshold(mriseg, mri_src, mri_src, 80, 100) ;
    }

    /* fill basal ganglia components */
    MRIclear(mri_bg) ;
    for (total_filled = i = 0 ; i < mriseg->nsegments ; i++)
    {
#define TAL_BG_LEFT_X    -30
#define TAL_BG_RIGHT_X   30
#define TAL_BG_Y         5
#define TAL_BG_Z         5
#define MAX_DIST         25

        mseg = &mriseg->segments[i] ;
        MRIvoxelToTalairach(mri_src, mseg->cx, mseg->cy, mseg->cz,&tx, &ty,&tz);
        dx_left = tx - TAL_BG_LEFT_X ;
        dx_right = tx - TAL_BG_RIGHT_X ;
        dy = ty - TAL_BG_Y ;
        dz = tz - TAL_BG_Z ;
        dist_left = sqrt(dx_left*dx_left+dy*dy+dz*dz) ;
        dist_right = sqrt(dx_right*dx_right+dy*dy+dz*dz) ;
        if (dist_left > MAX_DIST && dist_right > MAX_DIST)
        {
            continue ;
        }
        fprintf(stderr, "filling segment %d with %d voxels\n\tc = "
                "(%2.1f,%2.1f,%2.1f) tal (%2.1f,%2.1f,%2.1f), dist %2.1f,%2.1f\n",
                i, mseg->nvoxels, mseg->cx, mseg->cy, mseg->cz,
                tx, ty, tz, dist_left, dist_right) ;
        MRIsegmentToImage(mri_src, mri_bg, mriseg, i) ;
        total_filled += mseg->nvoxels ;
    }

#if 1
    /*  MRIremoveIslands(mri_bg, mri_bg, 3, .56) ;*/
    MRIbinarize(mri_bg, mri_bg, WM_MIN_VAL, 0, BASAL_GANGLIA_FILL) ;
#endif
    MRIsegmentFree(&mriseg) ;

    MRIunion(mri_dst, mri_bg, mri_dst) ;
    MRIfree(&mri_bg) ;
    if (Gdiag & DIAG_SHOW)
    {
        fprintf(stderr, "%d basal ganglia points filled\n", total_filled);
    }

    return(mri_dst) ;
}
Esempio n. 10
0
static int
MRIcheckRemovals(MRI *mri_T1, MRI *mri_dst, MRI *mri_labels, int wsize)
{
    int    x, y, z, width, depth, height, whalf, ntested, nchanged, on, vertex;
    MRI    *mri_tmp, *mri_region, *mri_plane, *mri_binary_plane ;
    float  min_on ;

    whalf = (wsize-1)/2 ;

    mri_tmp = MRIcopy(mri_dst, NULL) ;
    mri_region = MRIalloc(wsize, wsize, wsize, MRI_UCHAR) ;
    min_on = .1*wsize*wsize ;
    MRIcopyLabel(mri_labels, mri_tmp, 255) ;

    MRIbinarize(mri_tmp, mri_tmp, WM_MIN_VAL, 0, 100) ;
    width = mri_T1->width ;
    height = mri_T1->height ;
    depth = mri_T1->depth ;

    ntested = nchanged = 0 ;
    if (Gdiag == 99)
    {
        MRIwrite(mri_tmp, "tmp.mgh") ;
    }
    for (z = 0 ; z < depth ; z++)
    {
        for (y = 0 ; y < height ; y++)
        {
            for (x = 0 ; x < width ; x++)
            {
                if (z == 87 && y == 88 && x == 163)  /* test1 cs filled */
                {
                    DiagBreak() ;
                }
                if (z == 88 && y == 89 && x == 163)  /* test1 cs filled */
                {
                    DiagBreak() ;
                }

                if (z == 101 && y == 133 && x == 152)
                {
                    DiagBreak() ;
                }
                if (x == 157 && y == 143 && z == 98)
                {
                    DiagBreak() ;
                }
                if (x == 156 && y == 143 && z == 98)
                {
                    DiagBreak() ;
                }

                if (x == 154 && y == 167 && z == 128)
                {
                    DiagBreak() ;
                }
                if (x == 136 && y == 147 && z == 28)
                {
                    DiagBreak() ;
                }

                if (x == 163 && y == 88 && z == 86)
                {
                    DiagBreak() ;
                }

                if ((x == 140 && y == 141 && z == 54) ||
                        (x == 140 && y == 141 && z == 53) ||
                        (x == 140 && y == 142 && z == 53) ||
                        (x == 140 && y == 142 && z == 54) ||
                        (x == 140 && y == 140 && z == 53))
                {
                    DiagBreak() ;  /* test4 cerebellum */
                }
                if (x == 142 && y == 139 && z == 54)   /* test4 */
                {
                    DiagBreak() ;
                }

                if (!MRIgetVoxVal(mri_labels, x, y, z, 0))
                {
                    continue ;
                }
                ntested++ ;

                MRIextract(mri_tmp, mri_region, x-whalf,y-whalf,z-whalf,
                           wsize, wsize, wsize) ;

                vertex =
                    MRIcountCpolvOnAtVoxel(mri_region, whalf, whalf, whalf, wsize, &on) ;

                mri_plane = MRIextractVertexPlane(mri_tmp, NULL, vertex,x,y,z,wsize);
                MRIthreshold(mri_plane, mri_plane, 50) ;
                MRIremove1dStructures(mri_plane,mri_plane, 10000,2,NULL);
                mri_binary_plane = MRIfillFG(mri_plane, NULL, whalf, whalf, 0,
                                             50, 128, &on) ;
                if (on > min_on)
                {
                    int  xk, yk, i, ntransitions, i_prev  ;

                    /*
                       now look at the winding # (number of white-black transitions
                       in a circle around the central point
                    */

                    ntransitions = 0 ;
                    for (i = 0 ; i < NPTS ; i++)
                    {
                        xk = xpts[i] ;
                        yk = ypts[i] ;
                        i_prev = i-1 ;
                        if (i_prev < 0)
                        {
                            i_prev = NPTS-1 ;
                        }
                        if (MRIgetVoxVal(mri_binary_plane, whalf+xpts[i], whalf+ypts[i], 0, 0) !=
                                MRIgetVoxVal(mri_binary_plane,whalf+xpts[i_prev],
                                             whalf+ypts[i_prev],0, 0))
                        {
                            ntransitions++ ;
                        }
                    }
                    if (ntransitions > 2)   /* not planar */
                    {
                        nchanged++ ;
                        MRIsetVoxVal(mri_dst, x, y, z, 0, MRIgetVoxVal(mri_T1, x, y, z, 0)) ;
                    }
                }
                if (Gdiag & DIAG_WRITE)
                {
                    MRIwrite(mri_region, "region.mgh") ;
                    MRIwrite(mri_plane, "plane.mgh") ;
                    MRIwrite(mri_binary_plane, "binary_plane.mgh") ;
                }
                MRIfree(&mri_plane) ;
                MRIfree(&mri_binary_plane) ;
            }
        }
    }
    MRIfree(&mri_tmp) ;
    MRIfree(&mri_region) ;
    if (Gdiag & DIAG_SHOW)
    {
        fprintf(stderr, "               %8d voxels tested (%2.2f%%)\n",
                ntested, 100.0f*(float)ntested/ (float)(width*height*depth));
        fprintf(stderr, "               %8d voxels restored (%2.2f%%)\n",
                nchanged, 100.0f*(float)nchanged/ (float)(width*height*depth));
    }
    return(NO_ERROR) ;
}
Esempio n. 11
0
int
main(int argc, char *argv[])
{
    MRI     *mri_src, *mri_dst, *mri_tmp, *mri_labeled, *mri_labels;
    char    *input_file_name, *output_file_name ;
    int     nargs, i, msec ;
    struct timeb  then ;
    float   white_mean, white_sigma, gray_mean, gray_sigma ;

    char cmdline[CMD_LINE_LEN] ;

    TAGmakeCommandLineString(argc, argv, cmdline) ;

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

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

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

    if (argc < 3)
    {
        usage_exit(1);
    }

    TimerStart(&then) ;
    input_file_name = argv[1] ;
    output_file_name = argv[2] ;

    mri_src = MRIread(input_file_name) ;
    if (!mri_src)
        ErrorExit(ERROR_NOFILE, "%s: could not read source volume from %s",
                  Progname, input_file_name) ;
    MRIaddCommandLine(mri_src, cmdline) ;
    if (mri_src->type != MRI_UCHAR)
    {
        MRI *mri_tmp ;
        printf("changing input type from %d to UCHAR\n", mri_src->type) ;
        mri_tmp = MRIchangeType(mri_src, MRI_UCHAR, 0, 1000, 1) ;
        MRIfree(&mri_src) ;
        mri_src = mri_tmp ;
    }

    if (thicken > 1)
    {
        mri_dst = MRIcopy(mri_src, NULL) ;
        /*    MRIfilterMorphology(mri_dst, mri_dst) ;*/
        fprintf(stderr, "removing 1-dimensional structures...\n") ;
        MRIremove1dStructures(mri_dst, mri_dst, 10000, 2, NULL) ;
#if 0
        MRIcheckRemovals(mri_src, mri_dst, mri_labels, 5) ;
        fprintf(stderr, "thickening thin strands....\n") ;
        MRIthickenThinWMStrands(mri_src, mri_dst, mri_dst, thickness, nsegments,
                                wm_hi) ;
#endif
        MRIwrite(mri_dst, output_file_name) ;
        exit(0) ;
    }

    mri_labels = MRIclone(mri_src, NULL) ;
    if (auto_detect_stats && !wm_low_set) /* widen range to allow
                                           for more variability */
    {
        wm_low -= 10 ;
    }
    fprintf(stderr, "doing initial intensity segmentation...\n") ;
    mri_tmp = MRIintensitySegmentation(mri_src, NULL, wm_low, wm_hi, gray_hi);

    if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
    {
        MRIwrite(mri_tmp, "tmp1.mgz") ;
    }
    fprintf(stderr, "using local statistics to label ambiguous voxels...\n") ;
    MRIhistoSegment(mri_src, mri_tmp, wm_low, wm_hi, gray_hi, wsize, 3.0f) ;
    if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
    {
        MRIwrite(mri_tmp, "tmp2.mgz") ;
    }

    if (auto_detect_stats)
    {

        fprintf(stderr, "computing class statistics for intensity windows...\n") ;
        MRIcomputeClassStatistics(mri_src, mri_tmp, gray_low, WHITE_MATTER_MEAN,
                                  &white_mean, &white_sigma, &gray_mean,
                                  &gray_sigma) ;
        if (!finite(white_mean) || !finite(white_sigma) ||
                !finite(gray_mean) || !finite(gray_sigma))
            ErrorExit
            (ERROR_BADPARM,
             "%s: class statistics not finite - check input volume!",
             Progname);

        if (!wm_low_set)
        {
            if (FZERO(gray_sigma))
            {
                wm_low = (white_mean+gray_mean) / 2 ;
            }
            else
            {
                wm_low = gray_mean + gray_sigma ;
            }
        }

        if (!gray_hi_set)
        {
            gray_hi = gray_mean + 2*gray_sigma ;
#if 1
            if (gray_hi >= white_mean)
            {
                gray_hi = white_mean-1 ;
            }
#endif
        }
        fprintf(stderr, "setting bottom of white matter range to %2.1f\n",wm_low);
        fprintf(stderr, "setting top of gray matter range to %2.1f\n", gray_hi) ;

        if (log_stats)
        {
            FILE *fp ;

            fp = fopen("segment.dat", "w") ;
            if (fp)
            {
                fprintf(fp, "WM: %2.1f +- %2.1f\n",white_mean, white_sigma) ;
                fprintf(fp, "GM: %2.1f +- %2.1f\n",gray_mean, gray_sigma) ;
                fprintf(fp, "setting bottom of white matter range to %2.1f\n",wm_low);
                fprintf(fp, "setting top of gray matter range to %2.1f\n", gray_hi) ;
                fclose(fp) ;
            }
        }

        fprintf(stderr, "doing initial intensity segmentation...\n") ;
        mri_tmp = MRIintensitySegmentation(mri_src, NULL, wm_low, wm_hi, gray_hi);

        fprintf(stderr, "using local statistics to label ambiguous voxels...\n") ;
        MRIhistoSegment(mri_src, mri_tmp, wm_low, wm_hi, gray_hi, wsize, 3.0f) ;
    }
    else
    {
        /* just some not-too-dopey defaults - won't really be used */
        white_mean =  110 ;
        white_sigma = 5.0 ;
        gray_mean = 65 ;
        gray_sigma = 12 ;
    }

    fprintf(stderr,
            "using local geometry to label remaining ambiguous voxels...\n") ;
    mri_labeled = MRIcpolvMedianCurveSegment(mri_src, mri_tmp, NULL, 5, 3,
                  gray_hi, wm_low);
    fprintf(stderr,
            "\nreclassifying voxels using Gaussian border classifier...\n") ;

    /*
      now use the gray and white matter border voxels to build a Gaussian
      classifier at each point in space and reclassify all voxels in the
      range [wm_low-5,gray_hi].
      */
    for (i = 0 ; i < niter ; i++)
    {
        MRIreclassify(mri_src, mri_labeled, mri_labeled, wm_low-5,gray_hi,wsize);
    }
    MRIfree(&mri_tmp) ;

    mri_dst = MRImaskLabels(mri_src, mri_labeled, NULL) ;
    MRIfree(&mri_labeled) ;
    MRIrecoverBrightWhite(mri_src, mri_dst,mri_dst,wm_low,wm_hi,white_sigma,.33);
    fprintf(stderr,
            "\nremoving voxels with positive offset direction...\n") ;

#if 0
    MRIremoveWrongDirection(mri_dst, mri_dst, 3, wm_low-5, gray_hi, mri_labels) ;
#else
    MRIremoveWrongDirection(mri_dst, mri_dst, 3, wm_low-5, gray_hi, NULL) ;
#endif

    if (thicken)
    {
        /*    MRIfilterMorphology(mri_dst, mri_dst) ;*/
        fprintf(stderr, "removing 1-dimensional structures...\n") ;
        MRIremove1dStructures(mri_dst, mri_dst, 10000, 2, mri_labels) ;
#if 0
        MRIcheckRemovals(mri_src, mri_dst, mri_labels, 5) ;
#endif
        fprintf(stderr, "thickening thin strands....\n") ;
        MRIthickenThinWMStrands(mri_src, mri_dst, mri_dst, thickness, nsegments,
                                wm_hi) ;
    }

    mri_tmp = MRIfindBrightNonWM(mri_src, mri_dst) ;
    MRIbinarize(mri_tmp, mri_tmp, WM_MIN_VAL, 255, 0) ;
    MRImaskLabels(mri_dst, mri_tmp, mri_dst) ;
    MRIfilterMorphology(mri_dst, mri_dst) ;

    if (fill_bg)
    {
        fprintf(stderr, "filling basal ganglia....\n") ;
        MRIfillBasalGanglia(mri_src, mri_dst) ;
    }
    if (fill_ventricles)
    {
        fprintf(stderr, "filling ventricles....\n") ;
        MRIfillVentricles(mri_dst, mri_dst) ;
    }


    MRIfree(&mri_src) ;
    msec = TimerStop(&then) ;
    fprintf(stderr, "white matter segmentation took %2.1f minutes\n",
            (float)msec/(1000.0f*60.0f));
    fprintf(stderr, "writing output to %s...\n", output_file_name) ;
    if (keep_edits)
    {
        MRI *mri_old ;

        mri_old = MRIread(output_file_name) ;
        if (!mri_old)
        {
            ErrorPrintf
            (ERROR_NOFILE, "%s: could not read file %s to preserve edits",
             Progname, output_file_name) ;
            exit(1);
        }
        else
        {
            MRIcopyLabel(mri_old, mri_dst, WM_EDITED_ON_VAL) ;
            MRIcopyLabel(mri_old, mri_dst, WM_EDITED_OFF_VAL) ;
            MRIfree(&mri_old) ;
        }
    }
    MRIwrite(mri_dst, output_file_name) ;

    MRIfree(&mri_dst) ;

    exit(0) ;
    return(0) ;
}
Esempio n. 12
0
static int
MRISrepositionToInnerSkull(MRI_SURFACE *mris, MRI *mri_smooth, INTEGRATION_PARMS *parms) {
  MRI   *mri_dist, *mri_bin, *mri_kernel, *mri_bin_smooth, *mri_dist_smooth ;
  float l_spring, sigma ;
  int   i, ic_order, avgs ;

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

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

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

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

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

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


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

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

  MRIfree(&mri_bin) ;
  MRIfree(&mri_dist) ;
  return(NO_ERROR) ;
}
Esempio n. 13
0
int
main(int argc, char *argv[]) {
  char          **av, fname[STRLEN], *T1_fname, *PD_fname, *output_dir, *mdir ;
  int           ac, nargs, msec, s ;
  MRI_SURFACE   *mris ;
  MRI           *mri_flash1, *mri_flash2, *mri_masked, *mri_masked_smooth, *mri_kernel,
  *mri_mean, *mri_dif, *mri_binary, *mri_distance ;
  MRI *mri_smooth, *mri_grad, *mri_inner ;
  struct timeb  then ;
  double        l_spring ;
  MRI_SEGMENTATION *mriseg ;


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

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

  memset(&parms, 0, sizeof(parms)) ;

  parms.projection = NO_PROJECTION ;
  parms.tol = 0.05 ;
  parms.check_tol = 1 ;
  parms.ignore_energy = 1 ;
  parms.dt = 0.5f ;
  parms.base_dt = BASE_DT_SCALE*parms.dt ;

  parms.l_spring_norm = 1 ;
  parms.l_shrinkwrap = 0 ;
  parms.l_intensity = 1 ;

  parms.niterations = 0 ;
  parms.write_iterations = 0 /*WRITE_ITERATIONS */;
  parms.integration_type = INTEGRATE_MOMENTUM ;
  parms.momentum = 0.0 /*0.8*/ ;
  parms.l_intensity = 1 ;
  parms.dt_increase = 1.0 /* DT_INCREASE */;
  parms.dt_decrease = 0.50 /* DT_DECREASE*/ ;
  parms.error_ratio = 50.0 /*ERROR_RATIO */;
  /*  parms.integration_type = INTEGRATE_LINE_MINIMIZE ;*/
  parms.l_surf_repulse = 0.0 ;
  parms.l_repulse = 0 /*1*/ ;

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

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

  if (argc < 4)
    usage_exit() ;

  /* set default parameters for white and gray matter surfaces */
  parms.niterations = 1000 ;
  if (parms.momentum < 0.0)
    parms.momentum = 0.0 /*0.75*/ ;

  TimerStart(&then) ;
  T1_fname = argv[1] ;
  PD_fname = argv[2] ;
  output_dir = argv[3] ;
  fprintf(stderr, "reading volume %s...\n", T1_fname) ;
  mri_flash1 = MRIread(T1_fname) ;
  if (!mri_flash1)
    ErrorExit(ERROR_NOFILE, "%s: could not read input volume %s", Progname, T1_fname) ;

  mri_flash2 = MRIread(PD_fname) ;
  if (!mri_flash2)
    ErrorExit(ERROR_NOFILE, "%s: could not read input volume %s", Progname, T1_fname) ;

  //  setMRIforSurface(mri_flash1);
  sprintf(fname, "%s/lib/bem/ic%d.tri", mdir, ic_init) ;
  mris = MRISread(fname) ;
  if (!mris)
    ErrorExit(ERROR_NOFILE, "%s: could not read icosahedron %s", Progname, fname) ;

  mri_mean = MRImean(mri_flash1, NULL, 5) ;
  MRIwrite(mri_mean, "mean.mgz") ;

  mri_dif = MRIabsdiff(mri_flash1, mri_flash2, NULL) ;
  MRIwrite(mri_dif, "dif.mgz") ;

  mriseg = MRIsegment(mri_mean, 30, 100000) ;
  s = MRIsegmentMax(mriseg) ;
  mri_masked = MRIsegmentToImage(mri_flash1, NULL, mriseg, s) ;
  MRIwrite(mri_masked, "mask.mgz") ;
  MRIsegmentFree(&mriseg) ;

  // MRIthresholdMask(mri_dif, mri_masked, mri_dif, 1, 0) ;
  // MRIwrite(mri_dif, "dif_masked.mgz") ;


  mri_kernel = MRIgaussian1d(2, 0) ;
  mri_smooth = MRIconvolveGaussian(mri_dif, NULL, mri_kernel) ;
  MRIwrite(mri_smooth, "smooth.mgz") ;
  MRIScopyVolGeomFromMRI(mris, mri_smooth) ;
  mris->useRealRAS = 1 ;

  initialize_surface_position(mris, mri_dif, 1, &parms) ;
  MRISwrite(mris, "init") ;
  MRISrepositionToInnerSkull(mris, mri_smooth, &parms) ;

  exit(0) ;
  mri_grad = MRIsobel(mri_smooth, NULL, NULL) ;
  MRIwrite(mri_grad, "grad.mgz") ;
  mri_inner = MRIfindInnerBoundary(mri_dif, mri_grad, NULL, 5.0) ;
  MRIwrite(mri_inner, "inner.mgz") ;
  MRIbinarize(mri_inner, mri_inner, 10, 0, 128) ;

  MRISpositionOptimalSphere(mris, mri_inner, 6) ;
  MRISwrite(mris, "optimal") ;
  exit(0) ;
  parms.sigma = 4 / mri_flash1->xsize ;
  // mri_dist = create_distance_map(mri_masked, NULL, BORDER_VAL, OUTSIDE_BORDER_STEP) ;
  MRISsetVals(mris,parms.sigma) ;
  MRIScopyValToVal2(mris) ;
  MRISsetVals(mris, 0) ;
  sprintf(parms.base_name, "%s_inner_skull%s%s", "test", output_suffix, suffix) ;
  parms.mri_brain = mri_masked ;
  l_spring = parms.l_spring_norm ;
  mri_kernel = MRIgaussian1d(parms.sigma, 0) ;


  mri_binary = MRIbinarize(mri_dif, mri_binary, 40, 0, 128) ;
  MRIwrite(mri_binary, "bin.mgz") ;
  mri_distance = MRIdistanceTransform(mri_binary, NULL, 128, 100, DTRANS_MODE_SIGNED, NULL) ;
  MRIwrite(mri_distance, "dist.mgz") ;
  mri_masked_smooth = MRIconvolveGaussian(mri_distance, NULL, mri_kernel) ;
  MRIfree(&mri_kernel) ;
  MRIwrite(mri_masked_smooth, "dif_smooth.mgz") ;

  MRISwrite(mris, "inner_skull.tri") ;

  msec = TimerStop(&then) ;
  fprintf(stderr,"positioning took %2.1f minutes\n", (float)msec/(60*1000.0f));
  exit(0) ;
  return(0) ;  /* for ansi */
}
Esempio n. 14
0
int
main(int argc, char *argv[])
{
  char         **av, fname[STRLEN], *out_fname, *subject_name, *cp, *tp1_name, *tp2_name ;
  char         s1_name[STRLEN], s2_name[STRLEN], *sname ;
  int          ac, nargs, i, n, options, max_index ;
  int          msec, minutes, seconds, nsubjects, input ;
  struct timeb start ;
  MRI          *mri_seg, *mri_tmp, *mri_in ;
  TRANSFORM    *transform ;
//  int          counts ;
  int          t;
  RANDOM_FOREST *rf = NULL ;
  GCA           *gca = NULL ;

  Progname = argv[0] ;

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

  TimerStart(&start) ;

  parms.width = parms.height = parms.depth = DEFAULT_VOLUME_SIZE ;
  parms.ntrees = 10 ;
  parms.max_depth = 10 ;
  parms.wsize = 1 ;
  parms.training_size = 100 ;
  parms.training_fraction = .5 ;
  parms.feature_fraction = 1 ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option
          (argc, argv,
           "$Id: mri_rf_long_train.c,v 1.5 2012/06/15 12:22:28 fischl Exp $",
           "$Name:  $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  // parse command line args
  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 < 3)
    usage_exit(1) ;


  // options parsed.   subjects, tp1 and tp2 and rf name remaining
  out_fname = argv[argc-1] ;
  nsubjects = (argc-2)/3 ;
  for (options = i = 0 ; i < nsubjects ; i++)
  {
    if (argv[i+1][0] == '-')
    {
      nsubjects-- ;
      options++ ;
    }
  }

  printf("training on %d subject and writing results to %s\n",
         nsubjects, out_fname) ;

  // rf_inputs can be T1, PD, ...per subject
  if (parms.nvols == 0)
    parms.nvols = ninputs ;
  /* gca reads same # of inputs as we read
     from command line - not the case if we are mapping to flash */
  n = 0 ;

  //////////////////////////////////////////////////////////////////
  // set up gca direction cosines, width, height, depth defaults

  gca = GCAread(gca_name) ;
  if (gca == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not read GCA from %s", Progname, gca_name) ;
  
  
  /////////////////////////////////////////////////////////////////////////
  // weird way options and subject name are mixed here
  
  /////////////////////////////////////////////////////////
  // first calculate mean
  ////////////////////////////////////////////////////////
  // going through the subject one at a time
  max_index = nsubjects+options ;
  nargs = 0 ;
  mri_in = NULL ; 
#ifdef HAVE_OPENMP
  subject_name = NULL ; sname = NULL ; t = 0 ;
//  counts = 0 ;   would be private
  input = 0 ;
  transform = NULL ;
  tp1_name = tp2_name = NULL ;
  mri_tmp = mri_seg = NULL ;
#pragma omp parallel for firstprivate(tp1_name, tp2_name, mri_in,mri_tmp, input, xform_name, transform, subjects_dir, force_inputs, conform, Progname, mri_seg, subject_name, s1_name, s2_name, sname, t, fname) shared(mri_inputs, transforms, mri_segs,argv) schedule(static,1)
#endif
  for (i = 0 ; i < max_index ; i++)
  {
    subject_name = argv[3*i+1] ;
    tp1_name = argv[3*i+2] ;
    tp2_name = argv[3*i+3] ;
    sprintf(s1_name, "%s_%s.long.%s_base", subject_name, tp1_name, subject_name) ;
    sprintf(s2_name, "%s_%s.long.%s_base", subject_name, tp2_name, subject_name) ;

    //////////////////////////////////////////////////////////////
    printf("***************************************"
	   "************************************\n");
    printf("processing subject %s, %d of %d (%s and %s)...\n", subject_name,i+1-nargs,
	   nsubjects, s1_name,s2_name);

    for (t = 0 ; t < 2 ; t++)
    {
      sname = t == 0 ? s1_name : s2_name;

      // reading this subject segmentation
      sprintf(fname, "%s/%s/mri/%s", subjects_dir, sname, seg_dir) ;
      if (Gdiag & DIAG_SHOW && DIAG_VERBOSE_ON)
	fprintf(stderr, "Reading segmentation from %s...\n", fname) ;
      mri_seg = MRIread(fname) ;
      if (!mri_seg)
	ErrorExit(ERROR_NOFILE, "%s: could not read segmentation file %s",
		  Progname, fname) ;

      if ((mri_seg->type != MRI_UCHAR) && (make_uchar != 0))
      {
	MRI *mri_tmp ;
	mri_tmp = MRIchangeType(mri_seg, MRI_UCHAR, 0, 1,1);
	MRIfree(&mri_seg) ;
	mri_seg = mri_tmp ;
      }

      if (wmsa_fname)
      {
	MRI *mri_wmsa ;
	sprintf(fname, "%s/%s/mri/%s", subjects_dir, sname, wmsa_fname) ;
	printf("reading WMSA labels from %s...\n", fname) ;
	mri_wmsa = MRIread(fname) ;
	if (mri_wmsa == NULL)
	  ErrorExit(ERROR_NOFILE, "%s: could not read WMSA file %s", fname) ;
	MRIbinarize(mri_wmsa, mri_wmsa,  1, 0, WM_hypointensities) ;
	MRIcopyLabel(mri_wmsa, mri_seg, WM_hypointensities) ;
	lateralize_hypointensities(mri_seg) ;
	if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON )
	{
	  char s[STRLEN] ;
	  sprintf(s, "%s/%s/mri/seg_%s",
		  subjects_dir, subject_name, wmsa_fname) ;
	  MRIwrite(mri_seg, s) ;
	}
      }
      if (binarize)
      {
	int j ;
	for (j = 0 ; j < 256 ; j++)
	{
	  if (j == binarize_in)
	    MRIreplaceValues(mri_seg, mri_seg, j, binarize_out) ;
	  else
	    MRIreplaceValues(mri_seg, mri_seg, j, 0) ;
	}
      }
      if (insert_fname)
      {
	MRI *mri_insert ;
	
	sprintf(fname, "%s/%s/mri/%s",
		subjects_dir, subject_name, insert_fname) ;
	mri_insert = MRIread(fname) ;
	if (mri_insert == NULL)
	  ErrorExit(ERROR_NOFILE,
		    "%s: could not read volume from %s for insertion",
		    Progname, insert_fname) ;
	
	MRIbinarize(mri_insert, mri_insert, 1, 0, insert_label) ;
	MRIcopyLabel(mri_insert, mri_seg, insert_label) ;
	MRIfree(&mri_insert) ;
      }
      
      replaceLabels(mri_seg) ;
      MRIeraseBorderPlanes(mri_seg, 1) ;

      ////////////////////////////////////////////////////////////
      if (DIAG_VERBOSE_ON)
	fprintf(stderr,
		"Gather all input volumes for the subject %s.\n",
		subject_name);
      // inputs must be coregistered
      // note that inputs are T1, PD, ... per subject (same TE, TR, FA)
      for (input = 0 ; input < ninputs ; input++)
      {
	//////////// set the gca type //////////////////////////////
	// is this T1/PD training?
	// how can we allow flash data training ???????
	// currently checks the TE, TR, FA to be the same for all inputs
	// thus we cannot allow flash data training.
	////////////////////////////////////////////////////////////
	
	sprintf(fname, "%s/%s/mri/%s", subjects_dir, sname,input_names[input]);
	if (DIAG_VERBOSE_ON)
	  printf("reading co-registered input from %s...\n", fname) ;
	fprintf(stderr, "   reading input %d: %s\n", input, fname);
	mri_tmp = MRIread(fname) ;
	if (!mri_tmp)
	  ErrorExit
	    (ERROR_NOFILE,
	     "%s: could not read image from file %s", Progname, fname) ;
	// input check 1
	if (getSliceDirection(mri_tmp) != MRI_CORONAL)
	{
	  ErrorExit
	    (ERROR_BADPARM,
	     "%s: must be in coronal direction, but it is not\n",
	     fname);
	}
	// input check 2
	if (conform &&
	    (mri_tmp->xsize != 1 || mri_tmp->ysize != 1 || mri_tmp->zsize != 1))
	{
	  ErrorExit
	    (ERROR_BADPARM,
	     "%s: must have 1mm voxel size, but have (%f, %f, %f)\n",
	     fname, mri_tmp->xsize, mri_tmp->ysize, mri_tmp->ysize);
	}
	// input check 3 is removed.  now we can handle c_(ras) != 0 case
	// input check 4
	if (i == 0)
	{
	  TRs[input] = mri_tmp->tr ;
	  FAs[input] = mri_tmp->flip_angle ;
	  TEs[input] = mri_tmp->te ;
	}
	else if ((force_inputs == 0) &&
		 (!FEQUAL(TRs[input],mri_tmp->tr) ||
		  !FEQUAL(FAs[input],mri_tmp->flip_angle) ||
		  !FEQUAL(TEs[input], mri_tmp->te)))
	  ErrorExit
	    (ERROR_BADPARM,
	     "%s: subject %s input volume %s: sequence parameters "
	     "(%2.1f, %2.1f, %2.1f)"
	     "don't match other inputs (%2.1f, %2.1f, %2.1f)",
	     Progname, subject_name, fname,
	     mri_tmp->tr, DEGREES(mri_tmp->flip_angle), mri_tmp->te,
	     TRs[input], DEGREES(FAs[input]), TEs[input]) ;
	// first time do the following
	if (input == 0)
	{
	  int nframes = ninputs ;
	  
	  ///////////////////////////////////////////////////////////
	  mri_in = MRIallocSequence(mri_tmp->width, mri_tmp->height, mri_tmp->depth,
				    mri_tmp->type, nframes) ;
	  if (!mri_in)
	    ErrorExit
	      (ERROR_NOMEMORY,
	       "%s: could not allocate input volume %dx%dx%dx%d",
	       mri_tmp->width, mri_tmp->height, mri_tmp->depth,nframes) ;
	  MRIcopyHeader(mri_tmp, mri_in) ;
	}
	// -mask option ////////////////////////////////////////////
	if (mask_fname)
	{
	  MRI *mri_mask ;
	  
	  sprintf(fname, "%s/%s/mri/%s",
		  subjects_dir, subject_name, mask_fname);
	  printf("reading volume %s for masking...\n", fname) ;
	  mri_mask = MRIread(fname) ;
	  if (!mri_mask)
	  ErrorExit(ERROR_NOFILE, "%s: could not open mask volume %s.\n",
		    Progname, fname) ;
	
	  MRImask(mri_tmp, mri_mask, mri_tmp, 0, 0) ;
	  MRIfree(&mri_mask) ;
	}
	MRIcopyFrame(mri_tmp, mri_in, 0, input) ;
	MRIfree(&mri_tmp) ;

      }// end of inputs per subject
    
    
      /////////////////////////////////////////////////////////
      // xform_name is given, then we can use the consistent c_(r,a,s) for gca
      /////////////////////////////////////////////////////////
      if (xform_name)
      {
	// we read talairach.xfm which is a RAS-to-RAS
	sprintf(fname, "%s/%s/mri/transforms/%s", subjects_dir, sname, xform_name) ;
	if (Gdiag & DIAG_SHOW && DIAG_VERBOSE_ON)
	  printf("INFO: reading transform file %s...\n", fname);
	if (!FileExists(fname))
	{
	  fprintf(stderr,"ERROR: cannot find transform file %s\n",fname);
	  exit(1);
	}
	transform = TransformRead(fname);
	if (!transform)
	  ErrorExit(ERROR_NOFILE, "%s: could not read transform from file %s",
		    Progname, fname);
	
//        modify_transform(transform, mri_in, gca);
	// Here we do 2 things
	// 1. modify gca direction cosines to
	// that of the transform destination (both linear and non-linear)
	// 2. if ras-to-ras transform,
      // then change it to vox-to-vox transform (linear case)
	
      // modify transform to store inverse also
	TransformInvert(transform, mri_in) ;
      }
      else
      {
//        GCAreinit(mri_in, gca);
	// just use the input value, since dst = src volume
	transform = TransformAlloc(LINEAR_VOXEL_TO_VOXEL, NULL) ;
      }
      
      /////////////////////////////////////////////////////////
      if (do_sanity_check)
      {
	// conduct a sanity check of particular labels, most importantly
	// hippocampus, that such labels do not exist in talairach coords
	// where they are known not to belong (indicating a bad manual edit)
	int errs = check(mri_seg, subjects_dir, subject_name);
	if (errs) 
	{
	  printf(
	    "ERROR: mri_ca_train: possible bad training data! subject:\n"
	    "\t%s/%s\n\n", subjects_dir, subject_name);
	  fflush(stdout) ;
	  sanity_check_badsubj_count++;
	}
      }
      
      mri_segs[i][t] = mri_seg ;
      mri_inputs[i][t] = mri_in ;
      transforms[i][t] = transform ;
    }
  }
  rf = train_rforest(mri_inputs, mri_segs, transforms, nsubjects, gca, &parms, wm_thresh,wmsa_whalf, 2) ;
  printf("writing random forest to %s\n", out_fname) ;
  if (RFwrite(rf, out_fname) != NO_ERROR)
    ErrorExit
      (ERROR_BADFILE, "%s: could not write rf to %s", Progname, out_fname) ;
  
  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  printf("classifier array training took %d minutes and %d seconds.\n", minutes, seconds) ;
  exit(0) ;
  return(0) ;
  }
static MRI *
MRIcomputeSurfaceDistanceIntensities(MRI_SURFACE *mris,  MRI *mri_ribbon, MRI *mri_aparc, MRI *mri, MRI *mri_aseg, int whalf) 
{
  MRI          *mri_features, *mri_binary, *mri_white_dist, *mri_pial_dist ;
  int          vno, ngm, outside_of_ribbon, label0, label, ohemi_label, xi, yi, zi, xk, yk, zk, x0, y0, z0, hemi_label, assignable ;
  double       xv, yv, zv, step_size, dist, thickness, wdist, pdist, snx, sny, snz, nx, ny, nz, xl, yl, zl, x, y, z, dot, angle ;
  VERTEX       *v ;

  mri_features = MRIallocSequence(mris->nvertices, 1, 1, MRI_FLOAT, 1) ;  // one samples inwards, one in ribbon, and one outside
  MRIcopyHeader(mri, mri_features) ;

  mri_binary = MRIcopy(mri_ribbon, NULL) ;
  mri_binary = MRIbinarize(mri_ribbon, NULL, 1, 0, 1) ;
  mri_pial_dist = MRIdistanceTransform(mri_binary, NULL, 1, max_pial_dist+1, DTRANS_MODE_SIGNED,NULL);
  if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
    MRIwrite(mri_pial_dist, "pd.mgz") ;

  MRIclear(mri_binary) ;
  MRIcopyLabel(mri_ribbon, mri_binary, Left_Cerebral_White_Matter) ;
  MRIcopyLabel(mri_ribbon, mri_binary, Right_Cerebral_White_Matter) ;
  MRIbinarize(mri_binary, mri_binary, 1, 0, 1) ;
  mri_white_dist = MRIdistanceTransform(mri_binary, NULL, 1, max_white_dist+1, DTRANS_MODE_SIGNED,NULL);
  if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
    MRIwrite(mri_white_dist, "wd.mgz") ;

  if (mris->hemisphere == LEFT_HEMISPHERE)
  {
    ohemi_label = Right_Cerebral_Cortex ;
    hemi_label = Left_Cerebral_Cortex ;
  }
  else
  {
    hemi_label = Right_Cerebral_Cortex ;
    ohemi_label = Left_Cerebral_Cortex ;
  }

  step_size = mri->xsize/2 ;
  for (vno = 0 ; vno < mris->nvertices ; vno++)
  {
    v = &mris->vertices[vno] ;
    if (vno == Gdiag_no)
      DiagBreak() ;
    if (v->ripflag)
      continue ;  // not cortex
    nx = v->pialx - v->whitex ; ny = v->pialy - v->whitey ; nz = v->pialz - v->whitez ;
    thickness = sqrt(nx*nx + ny*ny + nz*nz) ;
    if (FZERO(thickness))
      continue ;   // no  cortex here


    x = (v->pialx + v->whitex)/2 ; y = (v->pialy + v->whitey)/2 ; z = (v->pialz + v->whitez)/2 ;  // halfway between white and pial is x0
    MRISsurfaceRASToVoxelCached(mris, mri_aseg, x, y, z, &xl, &yl, &zl) ;
    x0 = nint(xl); y0 = nint(yl) ; z0 = nint(zl) ;
    label0 = MRIgetVoxVal(mri_aparc, x0, y0, z0,0) ;

    // compute surface normal in voxel coords
    MRISsurfaceRASToVoxelCached(mris, mri_aseg, x+v->nx, y+v->ny, z+v->nz, &snx, &sny, &snz) ;
    snx -= xl ; sny -= yl ; snz -= zl ;

    for (ngm = 0, xk = -whalf ; xk <= whalf ; xk++)
    {
      xi = mri_aseg->xi[x0+xk] ;
      for (yk = -whalf ; yk <= whalf ; yk++)
      {
	yi = mri_aseg->yi[y0+yk] ;
	for (zk = -whalf ; zk <= whalf ; zk++)
	{
	  zi = mri_aseg->zi[z0+zk] ;
	  label = MRIgetVoxVal(mri_aseg, xi, yi, zi,0) ;
	  if (xi == Gx && yi == Gy && zi == Gz)
	    DiagBreak() ;
	  if (label != hemi_label)
	    continue ;
	  label = MRIgetVoxVal(mri_aparc, xi, yi, zi,0) ;
	  if (label && label != label0)  // if  outside the ribbon it won't be assigned to a parcel
	    continue ;  // constrain it to be in the same cortical parcel

	  // search along vector connecting x0 to this point to make sure it is we don't perforate wm or leave and re-enter cortex
	  nx = xi-x0 ; ny = yi-y0 ; nz = zi-z0 ;
	  thickness = sqrt(nx*nx + ny*ny + nz*nz) ;
	  assignable = 1 ;  // assume this point should be counted
	  if (thickness > 0)
	  {
	    nx /= thickness ; ny /= thickness ; nz /= thickness ;
	    dot = nx*snx + ny*sny + nz*snz ; angle = acos(dot) ;
	    if (FABS(angle) > angle_threshold)
	      assignable = 0 ;
	    outside_of_ribbon = 0 ;
	    for (dist = 0 ; assignable && dist <= thickness ; dist += step_size) 
	    {
	      xv = x0+nx*dist ;  yv = y0+ny*dist ;  zv = z0+nz*dist ; 
	      if (nint(xv) == Gx && nint(yv) == Gy && nint(zv) == Gz)
		DiagBreak() ;
	      MRIsampleVolume(mri_pial_dist, xv, yv, zv, &pdist) ;
	      MRIsampleVolume(mri_white_dist, xv, yv, zv, &wdist) ;
	      label = MRIgetVoxVal(mri_aseg, xi, yi, zi,0) ;
	      if (SKIP_LABEL(label) || label == ohemi_label)
		assignable = 0 ;
	      if (wdist < 0)  // entered wm - not assignable
		assignable = 0 ;
	      else
	      {
		if (pdist > 0)  // outside pial surface
		  outside_of_ribbon = 1 ;
		else
		{
		  if (outside_of_ribbon) // left ribbon and reentered
		    assignable = 0 ;
		}
	      }
	    }
	  }  // close of thickness > 0
	  if (assignable)
	    ngm++ ;
	  else
	    DiagBreak() ;
	}
      }
    }
    
    MRIsetVoxVal(mri_features, vno, 0, 0, 0, ngm) ;
  }

  MRIfree(&mri_white_dist) ; MRIfree(&mri_pial_dist) ; MRIfree(&mri_binary) ;
  return(mri_features) ;
}
int
main(int argc, char *argv[]) {
  char   **av, fname[STRLEN] ;
  int    ac, nargs ;
  char   *reg_fname, *in_fname, *out_stem, *cp ;
  int    msec, minutes, seconds, nvox, float2int ;
  struct timeb start ;
  MRI_SURFACE *mris_lh_white, *mris_rh_white, *mris_lh_pial, *mris_rh_pial ;
  MRI         *mri_aseg, *mri_seg, *mri_pial, *mri_tmp, *mri_ribbon, *mri_in, *mri_cortex, 
    *mri_subcort_gm, *mri_wm, *mri_csf ;
  MATRIX      *m_regdat ;
  float       intensity, betplaneres, inplaneres ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mri_compute_volume_fractions.c,v 1.9 2012/11/07 18:58:02 greve Exp $", "$Name:  $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  Progname = argv[0] ;
  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }
  if (argc < 4)
    usage_exit(1) ;
  if (!strlen(sdir)) {
    cp = getenv("SUBJECTS_DIR") ;
    if (!cp)
      ErrorExit(ERROR_BADPARM,
                "%s: SUBJECTS_DIR not defined in environment.\n", Progname) ;
    strcpy(sdir, cp) ;
  }
  reg_fname = argv[1] ; in_fname = argv[2] ;
  out_stem = argv[3] ; Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  TimerStart(&start) ;

  if (stricmp(reg_fname, "identity.nofile") == 0)
  {
    printf("using identity transform\n") ;
    m_regdat = NULL ;
    inplaneres = betplaneres = intensity = 1 ;
    float2int = 0 ;
    if (subject == NULL)
      subject = "unknown" ;
  }
  else
  {
    char *saved_subject = subject ;
    printf("reading registration file %s\n", reg_fname) ;
    regio_read_register(reg_fname, &subject, &inplaneres,
                        &betplaneres, &intensity,  &m_regdat,
                        &float2int);
    
    if (saved_subject)  // specified on cmdline
      subject = saved_subject ;
    m_regdat = regio_read_registermat(reg_fname) ;
    if (m_regdat == NULL)
      ErrorExit(ERROR_NOFILE, "%s: could not load registration file from %s", Progname,reg_fname) ;
  }
  printf("Format is %s\n",fmt);
    
  sprintf(fname, "%s/%s/surf/lh.white", sdir, subject) ;
  printf("reading surface %s\n", fname) ;
  mris_lh_white = MRISread(fname) ;
  if (mris_lh_white == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not load lh white surface from %s", Progname,fname) ;

  sprintf(fname, "%s/%s/surf/rh.white", sdir, subject) ;
  printf("reading surface %s\n", fname) ;
  mris_rh_white = MRISread(fname) ;
  if (mris_rh_white == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not load rh white surface from %s", Progname,fname) ;

  sprintf(fname, "%s/%s/surf/lh.pial", sdir, subject) ;
  printf("reading surface %s\n", fname) ;
  mris_lh_pial = MRISread(fname) ;
  if (mris_lh_pial == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not load lh pial surface from %s", Progname,fname) ;

  sprintf(fname, "%s/%s/surf/rh.pial", sdir, subject) ;
  printf("reading surface %s\n", fname) ;
  mris_rh_pial = MRISread(fname) ;
  if (mris_rh_pial == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not load rh pial surface from %s", Progname,fname) ;

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

  printf("reading movable volume %s\n", in_fname) ;
  mri_in = MRIread(in_fname) ;
  if (mri_in == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not load input volume from %s", Progname,in_fname) ;
 
  nvox = (int)ceil(256/resolution); 
  mri_pial = MRIalloc(nvox, nvox, nvox, MRI_UCHAR) ;
  MRIsetResolution(mri_pial, resolution, resolution, resolution) ;

  mri_pial->xstart = -resolution*mri_pial->width/2.0 ;
  mri_pial->xend = resolution*mri_pial->width/2.0 ;
  mri_pial->ystart = -resolution*mri_pial->height/2.0 ;
  mri_pial->yend = resolution*mri_pial->height/2.0 ;
  mri_pial->zstart = -resolution*mri_pial->depth/2.0 ;
  mri_pial->zend = resolution*mri_pial->depth/2 ;
  mri_pial->c_r = mri_aseg->c_r ; mri_pial->c_a = mri_aseg->c_a ; mri_pial->c_s = mri_aseg->c_s ;
  MRIreInitCache(mri_pial) ; 

  printf("filling interior of lh pial surface...\n") ;
  MRISfillInterior(mris_lh_pial, resolution, mri_pial) ;
  mri_seg = MRIclone(mri_pial, NULL) ;
  mri_tmp = MRIclone(mri_pial, NULL) ;
  printf("filling interior of rh pial surface...\n") ;
  MRISfillInterior(mris_rh_pial, resolution, mri_tmp) ;
  MRIcopyLabel(mri_tmp, mri_pial, 1) ;
  MRIclear(mri_tmp) ;
  printf("filling interior of lh white matter surface...\n") ;
  MRISfillWhiteMatterInterior(mris_lh_white, mri_aseg, mri_seg, resolution,
                              WM_VAL, SUBCORT_GM_VAL, CSF_VAL);
  printf("filling interior of rh white matter surface...\n") ;
  MRISfillWhiteMatterInterior(mris_rh_white, mri_aseg, mri_tmp, resolution,
                              WM_VAL, SUBCORT_GM_VAL, CSF_VAL);
  MRIcopyLabel(mri_tmp, mri_seg, WM_VAL) ;
  MRIcopyLabel(mri_tmp, mri_seg, SUBCORT_GM_VAL) ;
  MRIcopyLabel(mri_tmp, mri_seg, CSF_VAL) ;
  MRIfree(&mri_tmp) ;
  
  mri_ribbon = MRInot(mri_seg, NULL) ;
  MRIcopyLabel(mri_seg, mri_pial, CSF_VAL) ;
  MRIreplaceValuesOnly(mri_pial, mri_pial, CSF_VAL, 0) ;
  MRIand(mri_ribbon, mri_pial, mri_ribbon, 1) ;
  MRIbinarize(mri_ribbon, mri_ribbon, 1, 0, GM_VAL) ;
  MRIcopyLabel(mri_ribbon, mri_seg, GM_VAL) ;
  MRIreplaceValuesOnly(mri_seg, mri_seg, CSF_VAL, 0) ;
  add_aseg_structures_outside_ribbon(mri_seg, mri_aseg, mri_seg, WM_VAL, SUBCORT_GM_VAL, CSF_VAL) ;


  {
    MATRIX *m_conformed_to_epi_vox2vox, *m_seg_to_conformed_vox2vox,
           *m_seg_to_epi_vox2vox ;

    if (m_regdat == NULL)    // assume identity transform
      m_seg_to_epi_vox2vox = MRIgetVoxelToVoxelXform(mri_seg, mri_in) ;
    else
    {
      m_conformed_to_epi_vox2vox = MRIvoxToVoxFromTkRegMtx(mri_in, mri_aseg, m_regdat);
      m_seg_to_conformed_vox2vox = MRIgetVoxelToVoxelXform(mri_seg, mri_aseg) ;
      
      m_seg_to_epi_vox2vox = MatrixMultiply(m_conformed_to_epi_vox2vox, m_seg_to_conformed_vox2vox, NULL) ;
      MatrixFree(&m_regdat) ; MatrixFree(&m_conformed_to_epi_vox2vox) ; 
      MatrixFree(&m_seg_to_conformed_vox2vox);

    }
    printf("seg to EPI vox2vox matrix:\n") ;
    MatrixPrint(Gstdout, m_seg_to_epi_vox2vox) ;
    mri_cortex = MRIalloc(mri_in->width, mri_in->height, mri_in->depth, MRI_FLOAT) ;
    MRIcopyHeader(mri_in, mri_cortex) ;
    mri_subcort_gm = MRIclone(mri_cortex, NULL) ;
    mri_wm = MRIclone(mri_cortex, NULL) ;
    mri_csf = MRIclone(mri_cortex, NULL) ;
    printf("computing partial volume fractions...\n") ;
    MRIcomputePartialVolumeFractions(mri_in, m_seg_to_epi_vox2vox, mri_seg, mri_wm, mri_subcort_gm, mri_cortex, mri_csf,
                                     WM_VAL, SUBCORT_GM_VAL, GM_VAL, 0) ;
  }
  
  sprintf(fname, "%s.wm.%s", out_stem,fmt) ;
  printf("writing wm %% to %s\n", fname) ;
  MRIwrite(mri_wm, fname) ;

  sprintf(fname, "%s.subcort_gm.%s", out_stem,fmt) ;
  printf("writing subcortical gm %% to %s\n", fname) ;
  MRIwrite(mri_subcort_gm, fname) ;

  sprintf(fname, "%s.cortex.%s", out_stem, fmt) ;
  printf("writing cortical gm %% to %s\n", fname) ;
  MRIwrite(mri_cortex, fname) ;
  
  sprintf(fname, "%s.csf.%s", out_stem,fmt) ;
  printf("writing csf %% to %s\n", fname) ;
  MRIwrite(mri_csf, fname) ;

  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  printf("volume fraction calculation took %d minutes"
          " and %d seconds.\n", minutes, seconds) ;
  exit(0) ;
  return(0) ;
}
Esempio n. 17
0
FCD_DATA   *
FCDloadData(char *sdir, char *subject)
{
  FCD_DATA    *fcd ;
  char        fname[STRLEN] ;
  MRI         *mri_interior, *mri_dist, *mri_int_lh, *mri_int_rh, *mri_pvals ;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  return(fcd) ;
}