コード例 #1
0
ファイル: mri_nl_align.c プロジェクト: guo2004131/freesurfer
static MRI *
create_distance_transforms(MRI *mri_source, MRI *mri_target, MRI *mri_all_dtrans, float max_dist, GCA_MORPH *gcam)
{
  MRI   *mri_dtrans, *mri_atlas_dtrans ;
  int   frame ;
  char  fname[STRLEN] ;
  
  mri_all_dtrans = MRIallocSequence(mri_source->width, mri_source->height, mri_source->depth,
                                    MRI_FLOAT, NDTRANS_LABELS) ;
  MRIcopyHeader(mri_target, mri_all_dtrans) ;

  for (frame = 0 ; frame < NDTRANS_LABELS ; frame++)
    {
      printf("creating distance transform for %s, frame %d...\n", 
	     cma_label_to_name(dtrans_labels[frame]), frame) ;
      mri_dtrans = 
	MRIdistanceTransform(mri_source, NULL, dtrans_labels[frame], max_dist, 
			     DTRANS_MODE_SIGNED, NULL) ;
      sprintf(fname, "%s.mgz", cma_label_to_name(dtrans_labels[frame])) ;
      if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
	MRIwrite(mri_dtrans, fname) ;
      MRIcopyFrame(mri_dtrans, mri_all_dtrans, 0, frame) ;
      mri_atlas_dtrans = 
	MRIdistanceTransform(mri_target, NULL, dtrans_labels[frame], max_dist, 
			     DTRANS_MODE_SIGNED, NULL) ;
      MRInormalizeInteriorDistanceTransform(mri_atlas_dtrans, mri_dtrans, mri_atlas_dtrans) ;
      GCAMsetTargetDistancesForLabel(gcam, mri_target, mri_atlas_dtrans, dtrans_labels[frame]);

      MRIfree(&mri_dtrans) ;
      MRIfree(&mri_atlas_dtrans) ;
    }

  return(mri_all_dtrans) ;
}
コード例 #2
0
ファイル: VolumeFilter.cpp プロジェクト: CBoensel/freesurfer
MRI* VolumeFilter::CreateMRIFromVolume( LayerMRI* layer )
{
  vtkImageData* image = layer->GetImageData();
  int mri_type = MRI_FLOAT;
  switch ( image->GetScalarType() )
  {
    case VTK_CHAR:
    case VTK_SIGNED_CHAR:
    case VTK_UNSIGNED_CHAR:
      mri_type = MRI_UCHAR;
      break;
    case VTK_INT:
    case VTK_UNSIGNED_INT:
      mri_type = MRI_INT;
      break;
    case VTK_LONG:
    case VTK_UNSIGNED_LONG:
      mri_type = MRI_LONG;
      break;
    case VTK_SHORT:
    case VTK_UNSIGNED_SHORT:
      mri_type = MRI_SHORT;
      break;
    default:
      break ;
  }
  
  int* dim = image->GetDimensions();
  int zFrames = image->GetNumberOfScalarComponents();
  MRI* mri = MRIallocSequence( dim[0], dim[1], dim[2], mri_type, zFrames );
  if ( !mri )
  {
    cerr << "Can not allocate memory for MRI" << endl;
    return NULL;
  }
  
  int zX = mri->width;
  int zY = mri->height;
  int zZ = mri->depth;
  int nScalarSize = image->GetScalarSize();
  for ( int nZ = 0; nZ < zZ; nZ++ )
  {
    for ( int nY = 0; nY < zY; nY++ )
    {
      for ( int nX = 0; nX < zX; nX++ )
      {
        for ( int nFrame = 0; nFrame < zFrames; nFrame++ )
        {
          void* buf = (char*)&MRIseq_vox( mri, nX, nY, nZ, nFrame);
          void* ptr = (char*)image->GetScalarPointer( nX, nY, nZ )
              + nFrame * nScalarSize;
          memcpy( buf, ptr, nScalarSize );
        }
      }
    }
  }
  
  return mri;
}
コード例 #3
0
ファイル: mri_reduce.c プロジェクト: guo2004131/freesurfer
int
main(int argc, char *argv[]) {
  char   **av ;
  int    ac, nargs, i ;
  MRI    *mri_src, *mri_dst = NULL ;
  char   *in_fname, *out_fname ;

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

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

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

  if (argc < 1)
    argc = 1 ;

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

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

  fprintf(stderr, "reading from %s...", in_fname) ;
  mri_src = MRIread(in_fname) ;

  i = 0 ;
  do {
    if (i)
      mri_src = MRIcopy(mri_dst, NULL) ;
    fprintf(stderr, "\nreducing by 2");

    mri_dst = MRIallocSequence(mri_src->width/2, mri_src->height/2, mri_src->depth/2, MRI_FLOAT, mri_src->nframes);
    MRIreduce(mri_src, mri_dst) ;
    MRIfree(&mri_src) ;
  } while (++i < reductions) ;

  fprintf(stderr, "\nwriting to %s", out_fname) ;
  MRIwrite(mri_dst, out_fname) ;
  fprintf(stderr, "\n") ;
  exit(0) ;
  return(0) ;
}
コード例 #4
0
ファイル: fcreateMorph.cpp プロジェクト: CBoensel/freesurfer
int
main(int argc,
     char* argv[])
{
  IoParams params;
  try
  {
    params.parse(argc,argv);
  }
  catch (const std::exception& excp)
  {
    std::cerr << " Exception while parsing cmd-line\n"
    << excp.what() << std::endl;
    exit(1);
  }
  catch (...)
  {
    std::cerr << " unhandled exception caught while parsing cmd line\n";
    exit(1);
  }


  boost::shared_ptr<gmp::VolumeMorph> pmorph(new gmp::VolumeMorph);

  if ( !params.strTemplate.empty() )
  {
    MRI* mri = MRIread( const_cast<char*>(params.strTemplate.c_str()) );
    if (!mri)
      std::cerr << " Failed to open template mri "
                << params.strTemplate << std::endl;
    else
      pmorph->set_volGeom_fixed(mri);
    MRIfree(&mri);
  }
  if ( !params.strSubject.empty() )
  {
    MRI* mri = MRIread( const_cast<char*>(params.strSubject.c_str()) );
    if (!mri)
      std::cerr << " Failed to open subject mri "
                << params.strSubject << std::endl;
    else
      pmorph->set_volGeom_moving(mri);
    MRIfree(&mri);
  }

  IoParams::MorphContainerType::iterator it;
  for ( it = params.items.begin();
        it != params.items.end();
        ++it )
  {
    if ( it->type == "affine" )
    {
      boost::shared_ptr<gmp::AffineTransform3d>
      paffine( new gmp::AffineTransform3d);
      float* pf = read_transform( it->file.c_str() );
      if ( !pf )
      {
        std::cerr << " failed to read transform\n";
        exit(1);
      }
      paffine->set_pars( pf);
      pmorph->m_transforms.push_back( paffine );

    }
    else if ( it->type == "volume" )
    {
      boost::shared_ptr<gmp::DeltaTransform3d>
      pvol( new gmp::DeltaTransform3d);
      MRI* field = MRIread
                   ( const_cast<char*>( it->file.c_str() ) );
      if ( !field )
      {
        std::cerr << " failed to read field "  << std::endl;
        exit(1);
      }
      pvol->set_field(field);

      pmorph->m_transforms.push_back( pvol );
    }
    else if ( it->type == "gcam" )
    {
      boost::shared_ptr<gmp::DeltaTransform3d>
      pvol( new gmp::DeltaTransform3d);
      GCA_MORPH* gcam = GCAMread( const_cast<char*>( it->file.c_str() ) );
      if ( !gcam )
      {
        std::cerr << " failed to read GCAM " << std::endl;
        exit(1);
      }
      // create bogus MRI to hold the geometry
      MRI* mri_template = MRIread( const_cast<char*>
                                   ( params.strTemplate.c_str() ) );
      MRI* mriBuf = MRIalloc( gcam->image.width,
                              gcam->image.height,
                              gcam->image.depth,
                              MRI_UCHAR);
      useVolGeomToMRI( &gcam->image, mriBuf );
      GCAMrasToVox(gcam, mriBuf );
      MRIfree( &mriBuf );

      std::cout << " atlas geometry = "
      << gcam->atlas.width << " , " << gcam->atlas.height
      << " , " << gcam->atlas.depth << std::endl
      << " image geometry = "
      << gcam->image.width << " , " << gcam->image.height
      << " , " << gcam->image.depth << std::endl;


      MRI* mri = MRIallocSequence( mri_template->width,
                                   mri_template->height,
                                   mri_template->depth,
                                   MRI_FLOAT,
                                   3);
      MRIcopyHeader(mri_template, mri);
      g_vDbgCoords = params.vDbgCoords;
      try
      {
        //MRI* mask =
        CopyGcamToDeltaField(gcam, mri);

        pvol->set_field(mri);
        //pvol->set_mask(mask);
        pmorph->m_transforms.push_back( pvol );
      }
      catch (const std::string& e)
      {
        std::cerr << " Exception caught while processing GCAM node\n"
        << e << std::endl;
        exit(1);
      }
      MRIfree(&mri_template);
    }
    else if ( it->type == "morph" )
    {
      boost::shared_ptr<gmp::VolumeMorph> tmpMorph(new gmp::VolumeMorph);
      try
      {
        tmpMorph->load( it->file.c_str() );
      }
      catch (const char* msg)
      {
        std::cerr << " Exception caught while loading morph in file "
        << it->file << std::endl;
        exit(1);
      }
      for ( gmp::VolumeMorph::TransformContainerType::iterator transformIter
            = tmpMorph->m_transforms.begin();
            transformIter != tmpMorph->m_transforms.end();
            ++transformIter )
        pmorph->m_transforms.push_back( *transformIter );

    }
    else if ( it->type == "mesh" )
    {
      boost::shared_ptr<gmp::FemTransform3d> pfem(new gmp::FemTransform3d);
      boost::shared_ptr<CMesh3d> pmesh(new CMesh3d);
      pmesh->load( it->file.c_str() );
      pfem->m_sharedMesh = pmesh;
      pmorph->m_transforms.push_back(pfem);
    }
    else
    {
      std::cerr << " unhandled transform type "
      << it->type << std::endl;
    }
  } // next it

  // finally write morph file
  try
  {
    pmorph->save( params.strOut.c_str() );
  }
  catch (const char* msg)
  {
    std::cerr << " Exception caught while saving morph\n"
    << msg << std::endl;
    exit(1);
  }

  return 0;
}
コード例 #5
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) ;
}
コード例 #6
0
MRI* VolumeFilter::CreateMRIFromVolume( LayerMRI* layer )
{
    vtkImageData* image = layer->GetImageData();
    int mri_type = MRI_FLOAT;
    switch ( image->GetScalarType() )
    {
    case VTK_CHAR:
    case VTK_SIGNED_CHAR:
    case VTK_UNSIGNED_CHAR:
        mri_type = MRI_UCHAR;
        break;
    case VTK_INT:
    case VTK_UNSIGNED_INT:
        mri_type = MRI_INT;
        break;
    case VTK_LONG:
    case VTK_UNSIGNED_LONG:
        mri_type = MRI_LONG;
        break;
    case VTK_SHORT:
    case VTK_UNSIGNED_SHORT:
        mri_type = MRI_SHORT;
        break;
    default:
        break;
    }

    int* dim = image->GetDimensions();
    int zFrames = image->GetNumberOfScalarComponents();
    MRI* mri = MRIallocSequence( dim[0], dim[1], dim[2], mri_type, zFrames );
    if ( !mri )
    {
        cerr << "Can not allocate memory for MRI.\n";
        return NULL;
    }

    for ( int j = 0; j < mri->height; j++ )
    {
        for ( int k = 0; k < mri->depth; k++ )
        {
            for ( int i = 0; i < mri->width; i++ )
            {
                for ( int nFrame = 0; nFrame < mri->nframes; nFrame++ )
                {
                    switch ( mri->type )
                    {
                    case MRI_UCHAR:
                        MRIseq_vox( mri, i, j, k, nFrame ) =
                            (unsigned char)image->GetScalarComponentAsDouble(i, j, k, nFrame);
                        break;
                    case MRI_INT:
                        MRIIseq_vox( mri, i, j, k, nFrame ) =
                            (int)image->GetScalarComponentAsDouble(i, j, k, nFrame);
                        break;
                    case MRI_LONG:
                        MRILseq_vox( mri, i, j, k, nFrame ) =
                            (int)image->GetScalarComponentAsDouble(i, j, k, nFrame);
                        break;
                    case MRI_FLOAT:
                        MRIFseq_vox( mri, i, j, k, nFrame ) =
                            (int)image->GetScalarComponentAsDouble(i, j, k, nFrame);
                        break;
                    case MRI_SHORT:
                        MRISseq_vox( mri, i, j, k, nFrame ) =
                            (int)image->GetScalarComponentAsDouble(i, j, k, nFrame);
                        break;
                    default:
                        break;
                    }
                }
            }
        }
        exec_progress_callback(j, mri->height, 0, 1);
    }

    return mri;
}
コード例 #7
0
ファイル: mri_stats2seg.c プロジェクト: guo2004131/freesurfer
/*---------------------------------------------------------------*/
int main(int argc, char *argv[]) {
    int nargs,r,c,s,n,segid,err;
    double val;

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

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

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

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

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

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

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

    printf("mri_stats2seg done\n");
    return 0;
}
コード例 #8
0
int
main(int argc, char *argv[])
{
  char         *in_fname, *out_fname, **av, *xform_fname, fname[STRLEN] ;
  MRI          *mri_in, *mri_tmp ;
  int          ac, nargs, msec, minutes, seconds;
  int          input, ninputs ;
  struct timeb start ;
  TRANSFORM    *transform = NULL ;
  char         cmdline[CMD_LINE_LEN], line[STRLEN], *cp, subject[STRLEN], sdir[STRLEN], base_name[STRLEN] ;
  FILE         *fp ;

  make_cmd_version_string
    (argc, argv,
     "$Id: mri_fuse_intensity_images.c,v 1.2 2011/06/02 14:05:10 fischl Exp $",
     "$Name:  $", cmdline);

  /* rkt: check for and handle version tag */
  nargs = handle_version_option
    (argc, argv,
     "$Id: mri_fuse_intensity_images.c,v 1.2 2011/06/02 14:05:10 fischl Exp $",
     "$Name:  $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  setRandomSeed(-1L) ;
  Progname = argv[0] ;

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

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

  if (argc < 5)
    ErrorExit
      (ERROR_BADPARM,
       "usage: %s [<options>] <longitudinal time point file> <in vol> <transform file> <out vol> \n",
       Progname) ;
  in_fname = argv[2] ;
  xform_fname = argv[3] ;
  out_fname = argv[4] ;

  transform = TransformRead(xform_fname) ;
  if (transform == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not read transform from %s", Progname, xform_fname) ;
  TimerStart(&start) ;

  FileNamePath(argv[1], sdir) ;
  cp = strrchr(sdir, '/') ; 
  if (cp)
  {
    strcpy(base_name, cp+1) ;
    *cp = 0 ;  // remove last component of path, which is base subject name
  }
  ninputs = 0 ;
  fp = fopen(argv[1], "r") ;
  if (fp == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not read time point file %s", Progname, argv[1]) ;

  do
  {
    cp = fgetl(line, STRLEN-1, fp) ;
    if (cp != NULL && strlen(cp) > 0)
    {
      subjects[ninputs] = (char *)calloc(strlen(cp)+1, sizeof(char)) ;
      strcpy(subjects[ninputs], cp) ;
      ninputs++ ;
    }
  } while (cp != NULL && strlen(cp) > 0) ;
  fclose(fp) ;
  printf("processing %d timepoints in SUBJECTS_DIR %s...\n", ninputs, sdir) ;
  for (input = 0 ; input < ninputs ; input++)
  {
    sprintf(subject, "%s.long.%s", subjects[input], base_name) ;
    printf("reading subject %s - %d of %d\n", subject, input+1, ninputs) ;
    sprintf(fname, "%s/%s/mri/%s", sdir, subject, in_fname) ;
    mri_tmp = MRIread(fname) ;
    if (!mri_tmp)
      ErrorExit(ERROR_NOFILE, "%s: could not read input MR volume from %s",
                Progname, fname) ;
    MRImakePositive(mri_tmp, mri_tmp) ;
    if (input == 0)
    {
      mri_in =
        MRIallocSequence(mri_tmp->width, mri_tmp->height, mri_tmp->depth,
                         mri_tmp->type, ninputs) ;
      if (!mri_in)
        ErrorExit(ERROR_NOMEMORY,
                  "%s: could not allocate input volume %dx%dx%dx%d",
                  mri_tmp->width,mri_tmp->height,mri_tmp->depth,ninputs) ;
      MRIcopyHeader(mri_tmp, mri_in) ;
    }

    if (mask_fname)
    {
      int i ;
      MRI *mri_mask ;

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

      for (i = 1 ; i < WM_MIN_VAL ; i++)
        MRIreplaceValues(mri_mask, mri_mask, i, 0) ;
      MRImask(mri_tmp, mri_mask, mri_tmp, 0, 0) ;
      MRIfree(&mri_mask) ;
    }
    MRIcopyFrame(mri_tmp, mri_in, 0, input) ;
    MRIfree(&mri_tmp) ;
  }
  MRIaddCommandLine(mri_in, cmdline) ;

  // try to bring the images closer to each other at each voxel where they seem to come from the same distribution
  {
    MRI   *mri_frame1, *mri_frame2 ;
    double rms_after ;

    mri_frame1 = MRIcopyFrame(mri_in, NULL, 0, 0) ;
    mri_frame2 = MRIcopyFrame(mri_in, NULL, 1, 0) ;
    rms_after = MRIrmsDiff(mri_frame1, mri_frame2) ;
    printf("RMS before intensity cohering  = %2.2f\n", rms_after) ;
    MRIfree(&mri_frame1) ; MRIfree(&mri_frame2) ; 
    if (0)
      normalize_timepoints(mri_in, 2.0, cross_time_sigma) ;
    else
      normalize_timepoints_with_parzen_window(mri_in, cross_time_sigma) ;
      
    mri_frame1 = MRIcopyFrame(mri_in, NULL, 0, 0) ;
    mri_frame2 = MRIcopyFrame(mri_in, NULL, 1, 0) ;
    rms_after = MRIrmsDiff(mri_frame1, mri_frame2) ;
    MRIfree(&mri_frame1) ; MRIfree(&mri_frame2) ;
    printf("RMS after intensity cohering  = %2.2f (sigma=%2.2f)\n", rms_after, cross_time_sigma) ;
  }

  for (input = 0 ; input < ninputs ; input++)
  {
    sprintf(fname, "%s/%s.long.%s/mri/%s", sdir, subjects[input], base_name, out_fname) ;
    printf("writing normalized volume to %s...\n", fname) ;
    if (MRIwriteFrame(mri_in, fname, input)  != NO_ERROR)
      ErrorExit(ERROR_BADFILE, "%s: could not write normalized volume to %s",Progname, fname);
  }

  MRIfree(&mri_in) ;

  printf("done.\n") ;
  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  printf("normalization took %d minutes and %d seconds.\n",
         minutes, seconds) ;
  if (diag_fp)
    fclose(diag_fp) ;
  exit(0) ;
  return(0) ;
}
コード例 #9
0
int
main(int argc, char *argv[]) {
  char         *gca_fname, *in_fname, **av, *xform_fname ;
  MRI          *mri_in, *mri_tmp, *mri_orig = NULL ;
  GCA          *gca ;
  int          ac, nargs, input, ninputs ;
  TRANSFORM    *transform = NULL ;
  char         cmdline[CMD_LINE_LEN] ;
  double       ll ;

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

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

  setRandomSeed(-1L) ;
  Progname = argv[0] ;

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

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

  if (argc < 3)
    ErrorExit
    (ERROR_BADPARM,
     "usage: %s [<options>] <inbrain1> <inbrain2> ... "
     "<atlas> <transform file> ...\n",
     Progname) ;

  ninputs = (argc - 1) / 2 ;
  if (DIAG_VERBOSE_ON)
    printf("reading %d input volume%ss\n", ninputs, ninputs > 1 ? "s" : "") ;
  in_fname = argv[1] ;
  gca_fname = argv[1+ninputs] ;
  xform_fname = argv[2+ninputs] ;
  transform = TransformRead(xform_fname) ;
  if (!transform)
    ErrorExit(ERROR_NOFILE, "%s: could not read input transform from %s",
              Progname, xform_fname) ;

  if (DIAG_VERBOSE_ON)
    printf("reading atlas from '%s'...\n", gca_fname) ;
  gca = GCAread(gca_fname) ;
  if (!gca)
    ErrorExit(ERROR_NOFILE, "%s: could not read input atlas from %s",
              Progname, gca_fname) ;

  fflush(stdout) ;
  for (input = 0 ; input < ninputs ; input++) {
    in_fname = argv[1+input] ;
    if (DIAG_VERBOSE_ON)
      printf("reading input volume from %s...\n", in_fname) ;
    mri_tmp = MRIread(in_fname) ;
    if (!mri_tmp)
      ErrorExit(ERROR_NOFILE, "%s: could not read input MR volume from %s",
                Progname, in_fname) ;
    MRImakePositive(mri_tmp, mri_tmp) ;
    if (input == 0) {
      mri_in =
        MRIallocSequence(mri_tmp->width, mri_tmp->height, mri_tmp->depth,
                         mri_tmp->type, ninputs) ;
      if (!mri_in)
        ErrorExit(ERROR_NOMEMORY,
                  "%s: could not allocate input volume %dx%dx%dx%d",
                  mri_tmp->width,mri_tmp->height,mri_tmp->depth,ninputs) ;
      MRIcopyHeader(mri_tmp, mri_in) ;
    }

    MRIcopyFrame(mri_tmp, mri_in, 0, input) ;
    MRIfree(&mri_tmp) ;
  }
  MRIaddCommandLine(mri_in, cmdline) ;

  TransformInvert(transform, mri_in) ;

  if (orig_fname) {
    mri_orig = MRIread(orig_fname) ;
    if (mri_orig == NULL)
      ErrorExit(ERROR_NOFILE, "%s: could not read orig volume from %s", Progname, orig_fname) ;
  }
  ll = GCAimageLogLikelihood(gca, mri_in, transform, 1, mri_orig) ;
  printf("%2.0f\n", 10000*ll) ;

  MRIfree(&mri_in) ;

  if (gca)
    GCAfree(&gca) ;
  if (mri_in)
    MRIfree(&mri_in) ;
  exit(0) ;
  return(0) ;
}
コード例 #10
0
static RANDOM_FOREST *
train_rforest(MRI *mri_inputs[MAX_SUBJECTS][MAX_TIMEPOINTS], MRI *mri_segs[MAX_SUBJECTS][MAX_TIMEPOINTS], TRANSFORM *transforms[MAX_SUBJECTS][MAX_TIMEPOINTS], 
	      int nsubjects, GCA *gca, RFA_PARMS *parms, float wm_thresh,
	      int wmsa_whalf, int ntp) 
{
  RANDOM_FOREST  *rf ;
  int            nfeatures, x, y, z, ntraining, n, tvoxel_size, width, height, depth, xt, yt, zt ;
  double         xatlas, yatlas, zatlas ;
  MRI            *mri_in, *mri_seg, *mri_training_voxels, *mri_wmsa_possible ;
  TRANSFORM      *transform ;
  double         **training_data ;
  int            *training_classes, i, label, tlabel, nwmsa, nfuture, nnot, correct, label_time1, label_time2;

  nwmsa = nnot = nfuture = 0 ;

/*
  features are:
  t1 intensity (3 vols)
  3 priors
  # of unknown voxels in the nbhd
  # of neighboring wmsa voxels at t1
*/
  nfeatures = parms->wsize*parms->wsize*parms->wsize*parms->nvols + 5 ; 

  rf = RFalloc(parms->ntrees, nfeatures, NCLASSES, parms->max_depth, single_classifier_names, max_steps) ;
  if (rf == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not allocate random forest", Progname) ;
  rf->min_step_size = 1 ; 

  tvoxel_size=1 ;
  width = (int)ceil((float)mri_segs[0][0]->width/tvoxel_size) ;
  height = (int)ceil((float)mri_segs[0][0]->height/tvoxel_size) ;
  depth = (int)ceil((float)mri_segs[0][0]->depth/tvoxel_size) ;
  mri_wmsa_possible = MRIalloc(width, height, depth, MRI_UCHAR) ;
  GCAcopyDCToMRI(gca, mri_wmsa_possible) ;
  mri_in = mri_inputs[0][0] ;
  mri_training_voxels = MRIallocSequence(mri_in->width,mri_in->height, mri_in->depth,MRI_UCHAR,nsubjects) ;

#if 1
  // update time 1 segmentation based on labels at time1 and time2
  for (n = 0 ; n < nsubjects ; n++)
  {
    mri_seg = mri_segs[n][0] ;
    for (x = 0 ; x < mri_in->width ; x++)
      for (y = 0 ; y < mri_in->height ; y++)
	for (z = 0 ; z < mri_in->depth ; z++)
	{
	  label_time1 = MRIgetVoxVal(mri_segs[n][0], x, y, z, 0) ;
	  label_time2 = MRIgetVoxVal(mri_segs[n][1], x, y, z, 0) ;
	  if (IS_WMSA(label_time1))
	    MRIsetVoxVal(mri_segs[n][0], x, y, z, 0, label_time1) ;
	  else if (IS_WMSA(label_time2))
	    MRIsetVoxVal(mri_segs[n][0], x, y, z, 0, future_WMSA) ;
	}
  }
#endif

  // build map of spatial locations that WMSAs can possibly occur in
  for (n = 0 ; n < nsubjects ; n++)
  {
    mri_in = mri_inputs[n][1] ; transform = transforms[n][1] ; 
    for (x = 0 ; x < mri_in->width ; x++)
      for (y = 0 ; y < mri_in->height ; y++)
	for (z = 0 ; z < mri_in->depth ; z++)
	  if (is_possible_wmsa(gca, mri_in, transform, x, y, z, 0))
	  {
	    TransformSourceVoxelToAtlas(transform, mri_in, x, y, z, &xatlas, &yatlas, &zatlas) ;
	    xt = nint(xatlas/tvoxel_size) ;
	    yt = nint(yatlas/tvoxel_size) ;
	    zt = nint(zatlas/tvoxel_size) ;
	    if (xt == Gx && yt == Gy && zt == Gz)
	      DiagBreak() ;
	    MRIsetVoxVal(mri_wmsa_possible, xt, yt, zt, 0, 1) ;
	  }
  }
  for ( ; wmsa_whalf > 0 ; wmsa_whalf--)
    MRIdilate(mri_wmsa_possible, mri_wmsa_possible) ;

  // now build map of all voxels in training set
  for (nnot = nwmsa = nfuture = ntraining = n = 0 ; n < nsubjects ; n++)
  {
    mri_in = mri_inputs[n][0] ; mri_seg = mri_segs[n][0] ; transform = transforms[n][0] ;
    for (x = 0 ; x < mri_in->width ; x++)
      for (y = 0 ; y <  mri_in->height; y++)
	for (z = 0 ; z <  mri_in->depth; z++)
	{
	  label = MRIgetVoxVal(mri_seg, x, y, z, 0) ;
	  
	  TransformSourceVoxelToAtlas(transform, mri_in, x, y, z, &xatlas, &yatlas, &zatlas) ;
	  xt = nint(xatlas/tvoxel_size) ;
	  yt = nint(yatlas/tvoxel_size) ;
	  zt = nint(zatlas/tvoxel_size) ;
	  if (xt == Gx && yt == Gy && zt == Gz)
	    DiagBreak() ;
	  if ((IS_WMSA(label) == 0) &&
	      MRIgetVoxVal(mri_wmsa_possible,xt,yt, zt,0) == 0)
	    continue ;
	  if (NOT_TRAINING_LABEL(label))
	    continue ;
	  ntraining++ ;
	  
	  if (IS_FUTURE_WMSA(label))
	  {
	    label = FUTURE_WMSA;
	    nfuture++ ;
	  }
	  else if (IS_WMSA(label))
	  {
	    label = WMSA ;
	    nwmsa++ ;
	  }
	  else
	  {
	    label = NOT_WMSA ;
	    nnot++ ;
	  }
          // set label to one more than it will be for training so that 0 means this is not a training voxel
	  MRIsetVoxVal(mri_training_voxels, x, y, z, n, label+1) ;
	}
  }

  correct = MRIcountNonzero(mri_training_voxels) ;
  if (correct != ntraining)
    DiagBreak() ;
  printf("total training set size = %2.1fM\n", (float)ntraining/(1024.0f*1024.0f)) ;
  printf("initial training set found with %dK FUTURE WMSA labels, %dK WMSA labels, and %dK non (ratio=%2.1f:%2.1f)\n",
	 nfuture/1000, nwmsa/1000, nnot/1000, (float)nnot/(float)nfuture, (float)nnot/(float)nwmsa) ;

  MRIfree(&mri_wmsa_possible) ;

  if (max_wm_wmsa_ratio*(nfuture+nwmsa) < nnot)   // too many wm labels w.r.t. # of wmsas - remove some wm
  {
    int removed, total_to_remove =  nnot - (max_wm_wmsa_ratio*(nfuture+nwmsa)) ;
    double premove ;

    premove = (double)total_to_remove  / (double)nnot ;
    printf("removing %dK WM indices to reduce training set imbalance (p < %f)\n", total_to_remove/1000, premove) ;

    for (removed = n = 0 ; n < nsubjects ; n++)
      for (x = 0 ; x < mri_in->width ; x++)
	for (y = 0 ; y <  mri_in->height; y++)
	  for (z = 0 ; z <  mri_in->depth; z++)
	  {
	    label = MRIgetVoxVal(mri_training_voxels, x, y, z, n) ;
	    if (label == 1)   // a WM voxel
	    {
	      if (randomNumber(0,1) < premove)
	      {
		removed++ ;
		MRIsetVoxVal(mri_training_voxels, x, y, z, n, 0) ;  // remove it from training set
	      }
	    }
	  }
    ntraining -= removed ;
    printf("%d WM voxels removed, new training set size = %dM (ratio = %2.1f)\n",
	   removed, ntraining/(1024*1024), (double)(nnot-removed)/(double)(nwmsa+nfuture)) ;
  }

  correct = MRIcountNonzero(mri_training_voxels) ;
  if (correct != ntraining)
    DiagBreak() ;
//  if (Gx >= 0)
  {
    int whalf = (parms->wsize-1)/2 ;
    char buf[STRLEN] ;
    rf->feature_names = (char **)calloc(rf->nfeatures, sizeof(char *)) ;
    for (i = 0, x = -whalf ; x <= whalf ; x++)
      for (y = -whalf ; y <= whalf ; y++)
	for (z = -whalf ; z <= whalf ; z++)
	  for (n = 0 ; n < mri_in->nframes ; n++, i++)
	  {
	    switch (n)
	    {
	    default:
	    case 0: sprintf(buf, "T1(%d, %d, %d)", x, y, z) ; break ;
	    case 1: sprintf(buf, "T2(%d, %d, %d)", x, y, z) ; 
	      break ;
	    case 2: sprintf(buf, "FLAIR(%d, %d, %d)", x, y, z) ; 
	      if (x == 0 && y == 0 && z == 0)
		Gdiag_no = i ;
	      break ;
	    }
	    rf->feature_names[i] = (char *)calloc(strlen(buf)+1, sizeof(char)) ;
	    strcpy(rf->feature_names[i], buf) ;
	  }
    printf("FLAIR(0,0,0) = %dth feature\n", Gdiag_no) ;

    sprintf(buf, "CSF voxels in nbhd") ;
    rf->feature_names[i] = (char *)calloc(strlen(buf)+1, sizeof(char)) ;
    strcpy(rf->feature_names[i], buf) ;
    i++ ; sprintf(buf, "gm prior") ;
    rf->feature_names[i] = (char *)calloc(strlen(buf)+1, sizeof(char)) ;
    strcpy(rf->feature_names[i], buf) ;
    i++ ; sprintf(buf, "wm prior") ;
    rf->feature_names[i] = (char *)calloc(strlen(buf)+1, sizeof(char)) ;
    strcpy(rf->feature_names[i], buf) ;
    i++ ; sprintf(buf, "csf prior") ;
    rf->feature_names[i] = (char *)calloc(strlen(buf)+1, sizeof(char)) ;
    strcpy(rf->feature_names[i], buf) ;
    i++ ; sprintf(buf, "WMSA in nbhd") ;
    rf->feature_names[i] = (char *)calloc(strlen(buf)+1, sizeof(char)) ;
    strcpy(rf->feature_names[i], buf) ;

    if (Gdiag & DIAG_WRITE)
    {
      printf("writing training voxels to tv.mgz\n") ;
      MRIwrite(mri_training_voxels, "tv.mgz") ;
    }
  }

  // now build training features and classes
  training_classes = (int *)calloc(ntraining, sizeof(training_classes[0])) ;
  if (training_classes == NULL)
    ErrorExit(ERROR_NOFILE, "train_rforest: could not allocate %d-length training buffers",ntraining);
  training_data = (double **)calloc(ntraining, sizeof(training_data[0])) ;
  if (training_classes == NULL)
    ErrorExit(ERROR_NOFILE, "train_rforest: could not allocate %d-length training buffers",ntraining);
  for (i = n = 0 ; n < nsubjects ; n++)
  {
    mri_in = mri_inputs[n][0] ; mri_seg = mri_segs[n][0] ; transform = transforms[n][0] ;
    for (x = 0 ; x < mri_in->width ; x++)
      for (y = 0 ; y <  mri_in->height; y++)
	for (z = 0 ; z <  mri_in->depth; z++)
	{
	  if ((int)MRIgetVoxVal(mri_training_voxels, x, y, z, n) == 0)
	    continue ;
	  label = MRIgetVoxVal(mri_seg, x, y, z, 0) ;
	  TransformSourceVoxelToAtlas(transform, mri_in, x, y, z, &xatlas, &yatlas, &zatlas) ;
	  xt = nint(xatlas/tvoxel_size) ; yt = nint(yatlas/tvoxel_size) ; zt = nint(zatlas/tvoxel_size) ;
	  if (IS_FUTURE_WMSA(label))
	    tlabel = FUTURE_WMSA ;
	  else if (IS_WMSA(label))
	    tlabel = WMSA ;
	  else
	    tlabel= NOT_WMSA ;
	    
	  training_classes[i] =  tlabel ;
	  training_data[i] = (double *)calloc(nfeatures, sizeof(double)) ;
	  if (training_data[i] == NULL)
	    ErrorExit(ERROR_NOMEMORY, "train_rforest: could not allocate %d-len feature vector #%d",
		      nfeatures, i) ;
	  training_classes[i] = training_classes[i] ;
//	  extract_feature(mri_in, parms->wsize, x, y, z, training_data[i], xatlas, yatlas, zatlas) ;
	  extract_long_features(mri_in, mri_seg, transform, gca, parms->wsize, x, y, z, training_data[i]) ;
	  if (training_data[i][Gdiag_no] < 80 && training_classes[i] == 1)
	    DiagBreak() ;
	  i++ ;
	}
    MRIfree(&mri_in) ; MRIfree(&mri_seg) ; TransformFree(&transform) ;
  }

  if (i < ntraining)
  {
    printf("warning!!!! i (%d) < ntraining (%d)! Setting ntraining=i\n", i, ntraining) ;
    ntraining = i ;
  }
  printf("training random forest with %dK FUTURE WMSA labels, %dK WMSA labels, and %dK non (ratio=%2.1f:%2.1f)\n",
	 nfuture/1000, nwmsa/1000, nnot/1000, (float)nnot/(float)nfuture, (float)nnot/(float)nwmsa) ;
  RFtrain(rf, parms->feature_fraction, parms->training_fraction, training_classes, training_data, ntraining);
  correct = RFcomputeOutOfBagCorrect(rf, training_classes, training_data,ntraining);
  printf("out of bag accuracy: %d of %d = %2.2f%%\n", correct, ntraining,
	 100.0*correct/ntraining) ;
  if (log_file_name)
  {
      struct flock fl;
      int    fd;
      char   line[MAX_LINE_LEN] ;

      printf("writing results to train.log file %s\n", log_file_name) ;
      fd = open(log_file_name, O_WRONLY|O_APPEND|O_CREAT, S_IRWXU|S_IRWXG);
      if (fd < 0)
	ErrorExit(ERROR_NOFILE, "%s: could not open test log file %s", 
		  Progname, log_file_name);
      
      fcntl(fd, F_SETLKW, &fl);  /* F_GETLK, F_SETLK, F_SETLKW */
      sprintf(line, "%f %d %d %f\n", 
	      rf->training_fraction,
	      rf->max_depth,
	      rf->ntrees,
	       100.0*correct/ntraining) ;
      write(fd, line, (strlen(line))*sizeof(char)) ;
      fl.l_type   = F_UNLCK;  /* tell it to unlock the region */
      fcntl(fd, F_SETLK, &fl); /* set the region to unlocked */
      close(fd) ;
  }

  for (i = 0 ; i < ntraining ; i++)  // allow for augmenting with other wmsa examples
    free(training_data[i]) ;
  free(training_data) ;
  free(training_classes) ;
  MRIfree(&mri_training_voxels) ;
  return(rf) ;
}
コード例 #11
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) ;
  }
コード例 #12
0
static int
write_surface_warp_into_volume(MRI_SURFACE *mris, MRI *mri, int niter)
{
  int    vno, xvi, yvi, zvi, frame ;
  VERTEX *v ;
  double  dx, dy, dz, xv, yv, zv, xv1, yv1, zv1 ;
  MRI     *mri_weights, *mri_ctrl, *mri_frame ;
  float    wt ;

  mri_weights = MRIallocSequence(mri->width, mri->height, mri->depth, MRI_FLOAT, 1) ;
  mri_ctrl = MRIallocSequence(mri->width, mri->height, mri->depth, MRI_UCHAR, 1) ;
  MRIcopyHeader(mri, mri_weights) ; MRIcopyHeader(mri, mri_ctrl) ;
  //   build a 3 frame volume with the voxel-coords warp (dx, dy, dz) in frames 0, 1 and 2 respectively
  for (vno = 0 ; vno < mris->nvertices ; vno++)
  {
    v = &mris->vertices[vno] ;
    if (v->ripflag)
      continue ;

    MRISsurfaceRASToVoxelCached(mris, mri, v->origx, v->origy, v->origz, &xv, &yv, &zv) ;
    MRISsurfaceRASToVoxelCached(mris, mri, v->x, v->y, v->z, &xv1, &yv1, &zv1) ;
    dx = xv1-xv ; dy = yv1-yv ; dz = zv1-zv ;
    xvi = nint(xv) ; yvi = nint(yv) ; zvi = nint(zv) ;
    if (vno == Gdiag_no)
    {
      printf("surface vertex %d: inflated (%2.0f, %2.0f, %2.0f), orig (%2.0f, %2.0f, %2.0f), "
	     "dx=(%2.0f, %2.0f, %2.0f)\n", vno, xv1, yv1, zv1, xv, yv, zv, dx, dy, dz) ;
      DiagBreak() ;
    }
    if (xvi < 0 || xvi >= mri->width || yv < 0 || yv >= mri->height || zv < 0 || zv >= mri->depth)
    {
      continue ;
    }
    MRIinterpolateIntoVolumeFrame(mri, xv, yv, zv, 0, dx) ;
    MRIinterpolateIntoVolumeFrame(mri, xv, yv, zv, 1, dy) ;
    MRIinterpolateIntoVolumeFrame(mri, xv, yv, zv, 2, dz) ;
    MRIinterpolateIntoVolume(mri_weights, xv, yv, zv, 1.0) ;
  }

#if 0
  // set boundary conditions in the edge planes to be 0 warping
  for (xvi = 0 ; xvi < mri->width ; xvi++)
    for (yvi = 0 ; yvi < mri->height ; yvi++)
    {
      MRIsetVoxVal(mri_ctrl, xvi, yvi, 0, 0, CONTROL_MARKED) ;
      MRIsetVoxVal(mri, xvi, yvi, 0, 0, 0) ;
      MRIsetVoxVal(mri, xvi, yvi, 0, 1, 0) ;
      MRIsetVoxVal(mri, xvi, yvi, 0, 2, 0) ;

      MRIsetVoxVal(mri_ctrl, xvi, yvi, mri->depth-1, 0, CONTROL_MARKED) ;
      MRIsetVoxVal(mri, xvi, yvi, mri->depth-1, 0, 0) ;
      MRIsetVoxVal(mri, xvi, yvi, mri->depth-1, 1, 0) ;
      MRIsetVoxVal(mri, xvi, yvi, mri->depth-1, 2, 0) ;
    }

  for (xvi = 0 ; xvi < mri->width ; xvi++)
    for (zvi = 0 ; zvi < mri->depth ; zvi++)
    {
      MRIsetVoxVal(mri_ctrl, xvi, 0, zvi, 0, CONTROL_MARKED) ;
      MRIsetVoxVal(mri, xvi, 0, zvi, 0, 0) ;
      MRIsetVoxVal(mri, xvi, 0, zvi, 1, 0) ;
      MRIsetVoxVal(mri, xvi, 0, zvi, 2, 0) ;

      MRIsetVoxVal(mri_ctrl, xvi, mri->height-1, zvi, 0, CONTROL_MARKED) ;
      MRIsetVoxVal(mri, xvi, mri->height-1, zvi, 0, 0) ;
      MRIsetVoxVal(mri, xvi, mri->height-1, zvi, 1, 0) ;
      MRIsetVoxVal(mri, xvi, mri->height-1, zvi, 2, 0) ;
    }

  for (yvi = 0 ; yvi < mri->width ; yvi++)
    for (zvi = 0 ; zvi < mri->depth ; zvi++)
    {
      MRIsetVoxVal(mri_ctrl, 0, yvi, zvi, 0, CONTROL_MARKED) ;
      MRIsetVoxVal(mri, 0, yvi, zvi, 0, 0) ;
      MRIsetVoxVal(mri, 0, yvi, zvi, 1, 0) ;
      MRIsetVoxVal(mri, 0, yvi, zvi, 2, 0) ;

      MRIsetVoxVal(mri_ctrl, mri->width-1, yvi, zvi, 0, CONTROL_MARKED) ;
      MRIsetVoxVal(mri, mri->width-1, yvi, zvi, 0, 0) ;
      MRIsetVoxVal(mri, mri->width-1, yvi, zvi, 1, 0) ;
      MRIsetVoxVal(mri, mri->width-1, yvi, zvi, 2, 0) ;

    }
#endif

  // normalize the warp field using a weighted average of all vertices that map to every voxel
  for (xvi = 0 ; xvi < mri->width ; xvi++)
    for (yvi = 0 ; yvi < mri->height ; yvi++)
      for (zvi = 0 ; zvi < mri->depth ; zvi++)
      {
        if (xvi == Gx && yvi == Gy && zvi == Gz)
          DiagBreak() ;

        wt = MRIgetVoxVal(mri_weights, xvi, yvi, zvi, 0) ;
        dx = MRIgetVoxVal(mri, xvi, yvi, zvi, 0) ;
        dy = MRIgetVoxVal(mri, xvi, yvi, zvi, 1) ;
        dz = MRIgetVoxVal(mri, xvi, yvi, zvi, 2) ;
        if (FZERO(wt))
          continue ;

        dx /= wt ; dy /= wt ; dz /= wt ;
        MRIsetVoxVal(mri, xvi, yvi, zvi, 0, dx) ;
        MRIsetVoxVal(mri, xvi, yvi, zvi, 1, dy) ;
        MRIsetVoxVal(mri, xvi, yvi, zvi, 2, dz) ;
        MRIsetVoxVal(mri_ctrl, xvi, yvi, zvi, 0, CONTROL_MARKED) ;  // it is a control point
      }

  if (Gdiag & DIAG_WRITE)
  {
    MRIwrite(mri, "warp0.mgz") ;
    MRIwrite(mri_ctrl, "ctrl.mgz") ;
  }

  for (frame = 0 ; frame < mri->nframes ; frame++)
  {
    printf("interpolating frame %d\n", frame+1) ;
    mri_frame = MRIcopyFrame(mri, NULL, frame, 0) ;
    MRIbuildVoronoiDiagram(mri_frame, mri_ctrl, mri_frame) ;
    MRIsoapBubble(mri_frame, mri_ctrl, mri_frame, niter, mri_frame->xsize*.05) ;
#if 0
    {
      int x, y, z ;
      float val ;
      for (x  = 0 ; x < mri_frame->width ; x++)
        for (y  = 0 ; y < mri_frame->height ; y++)
          for (z  = 0 ; z < mri_frame->depth ; z++)
          {
            val = MRIgetVoxVal(mri_frame, x, y, z, 0) ;
            switch (frame)
            {
            default:
            case 0:
              val += x ;
              break ;
            case 1:
              val += y ;
              break ;
            case 2:
              val += z ;
              break ;
            }

            MRIsetVoxVal(mri_frame, x, y, z, 0, val) ;
          }
    }
#endif
    MRIcopyFrame(mri_frame, mri, 0, frame) ;
    MRIfree(&mri_frame) ;
  }
  MRIfree(&mri_weights) ;
  MRIfree(&mri_ctrl) ;
  return(NO_ERROR) ;
}
コード例 #13
0
int
main(int argc, char *argv[])
{
  char        **av, *out_name ;
  int          ac, nargs ;
  int          msec, minutes, seconds ;
  struct timeb start ;
  MRI_SURFACE  *mris ;
  GCA_MORPH    *gcam ;
  MRI          *mri = NULL ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mris_interpolate_warp.c,v 1.5 2011/10/07 12:07:26 fischl Exp $", "$Name:  $");
  if (nargs && argc - nargs == 1)
  {
    exit (0);
  }
  argc -= nargs;

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

  TimerStart(&start) ;

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

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


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

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

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

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

      VERTEX *v = &mris->vertices[Gdiag_no] ;
      MRISsurfaceRASToVoxelCached(mris, mri, v->origx, v->origy, v->origz, &xi, &yi, &zi) ;
      MRISsurfaceRASToVoxelCached(mris, mri, v->x, v->y, v->z, &xo, &yo, &zo) ;
      printf("surface vertex %d: inflated (%2.0f, %2.0f, %2.0f), orig (%2.0f, %2.0f, %2.0f)\n", Gdiag_no, xi, yi, zi, xo, yo, zo) ;
      MRIsampleVolume(mri_in, xo, yo, zo, &val) ;
      xp = nint(xi) ; yp = nint(yi) ; zp = nint(zi) ;
      gcamn = &gcam->nodes[xp][yp][zp] ;
      printf("warp = (%2.1f, %2.1f, %2.1f), orig (%2.1f %2.1f %2.1f) = %2.1f \n", 
	     gcamn->x, gcamn->y, gcamn->z,
	     gcamn->origx, gcamn->origy, gcamn->origz,val) ;
      DiagBreak() ;
    }
  }
  if (no_write == 0)
  {
    out_name = argv[3] ;
    GCAMwrite(gcam, out_name) ;
  }
  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  fprintf(stderr, "warp field calculation took %d minutes and %d seconds.\n", minutes, seconds) ;
  exit(0) ;
  return(0) ;
}
コード例 #14
0
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) ;
}
コード例 #15
0
ファイル: mri_concat.c プロジェクト: guo2004131/freesurfer
/*--------------------------------------------------*/
int main(int argc, char **argv)
{
  int nargs, nthin, nframestot=0, nr=0,nc=0,ns=0, fout;
  int r,c,s,f,outf,nframes,err,nthrep;
  double v, v1, v2, vavg, vsum;
  int inputDatatype=MRI_UCHAR;
  MATRIX *Upca=NULL,*Spca=NULL;
  MRI *Vpca=NULL;
  char *stem;

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

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

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

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

  if(maskfile)
  {
    printf("Loading mask %s\n",maskfile);
    mask = MRIread(maskfile);
    if(mask == NULL)
    {
      exit(1);
    }
  }

  printf("ninputs = %d\n",ninputs);
  if(DoCheck)
  {
    printf("Checking inputs\n");
    for(nthin = 0; nthin < ninputs; nthin++)
    {
      if(Gdiag_no > 0 || debug)
      {
        printf("Checking %2d %s\n",nthin,inlist[nthin]);
        fflush(stdout);
      }
      mritmp = MRIreadHeader(inlist[nthin],MRI_VOLUME_TYPE_UNKNOWN);
      if (mritmp == NULL)
      {
        printf("ERROR: reading %s\n",inlist[nthin]);
        exit(1);
      }
      if (nthin == 0)
      {
        nc = mritmp->width;
        nr = mritmp->height;
        ns = mritmp->depth;
      }
      if (mritmp->width != nc ||
          mritmp->height != nr ||
          mritmp->depth != ns)
      {
        printf("ERROR: dimension mismatch between %s and %s\n",
               inlist[0],inlist[nthin]);
        exit(1);
      }

      nframestot += mritmp->nframes;
      inputDatatype = mritmp->type; // used by DoKeepDatatype option
      MRIfree(&mritmp);
    }
  }
  else
  {
    printf("NOT Checking inputs, assuming nframestot = ninputs\n");
    nframestot = ninputs;
    mritmp = MRIreadHeader(inlist[0],MRI_VOLUME_TYPE_UNKNOWN);
    if (mritmp == NULL)
    {
      printf("ERROR: reading %s\n",inlist[0]);
      exit(1);
    }
    nc = mritmp->width;
    nr = mritmp->height;
    ns = mritmp->depth;
    MRIfree(&mritmp);
  }

  printf("nframestot = %d\n",nframestot);

  if (DoRMS)
  {
    if (ninputs != 1)
    {
      printf("ERROR: --rms supports only single input w/ multiple frames\n");
      exit (1);
    }
    if (nframestot == 1)
    {
      printf("ERROR: --rms input must have multiple frames\n");
      exit (1);
    }
  }

  if(ngroups != 0)
  {
    printf("Creating grouped mean matrix ngroups=%d, nper=%d\n",
           ngroups,nframestot/ngroups);
    M = GroupedMeanMatrix(ngroups,nframestot);
    if(M==NULL)
    {
      exit(1);
    }
    if(debug)
    {
      MatrixPrint(stdout,M);
    }
  }

  if(M != NULL)
  {
    if(nframestot != M->cols)
    {
      printf("ERROR: dimension mismatch between inputs (%d) and matrix (%d)\n",
             nframestot,M->rows);
      exit(1);
    }
  }

  if (DoPaired)
  {
    if (remainder(nframestot,2) != 0)
    {
      printf("ERROR: --paired-xxx specified but there are an "
             "odd number of frames\n");
      exit(1);
    }
  }

  printf("Allocing output\n");
  fflush(stdout);
  int datatype=MRI_FLOAT;
  if (DoKeepDatatype)
  {
    datatype = inputDatatype;
  }
  if (DoRMS)
  {
    // RMS always has single frame output
    mriout = MRIallocSequence(nc,nr,ns,datatype,1);
  }
  else
  {
    mriout = MRIallocSequence(nc,nr,ns,datatype,nframestot);
  }
  if (mriout == NULL)
  {
    exit(1);
  }
  printf("Done allocing\n");

  fout = 0;
  for (nthin = 0; nthin < ninputs; nthin++)
  {
    if (DoRMS) break; // MRIrms reads the input frames
    if(Gdiag_no > 0 || debug)
    {
      printf("Loading %dth input %s\n",
             nthin+1,fio_basename(inlist[nthin],NULL));
      fflush(stdout);
    }
    mritmp = MRIread(inlist[nthin]);
    if(mritmp == NULL)
    {
      printf("ERROR: loading %s\n",inlist[nthin]);
      exit(1);
    }
    if(nthin == 0)
    {
      MRIcopyHeader(mritmp, mriout);
      //mriout->nframes = nframestot;
    }
    if(DoAbs)
    {
      if(Gdiag_no > 0 || debug)
      {
        printf("Removing sign from input\n");
      }
      MRIabs(mritmp,mritmp);
    }
    if(DoPos)
    {
      if(Gdiag_no > 0 || debug)
      {
        printf("Setting input negatives to 0.\n");
      }
      MRIpos(mritmp,mritmp);
    }
    if(DoNeg)
    {
      if(Gdiag_no > 0 || debug)
      {
        printf("Setting input positives to 0.\n");
      }
      MRIneg(mritmp,mritmp);
    }
    for(f=0; f < mritmp->nframes; f++)
    {
      for(c=0; c < nc; c++)
      {
        for(r=0; r < nr; r++)
        {
          for(s=0; s < ns; s++)
          {
            v = MRIgetVoxVal(mritmp,c,r,s,f);
            MRIsetVoxVal(mriout,c,r,s,fout,v);
          }
        }
      }
      fout++;
    }
    MRIfree(&mritmp);
  }

  if(DoCombine)
  {
    // Average frames from non-zero voxels
    int nhits;
    mritmp = MRIallocSequence(nc,nr,ns,MRI_FLOAT,1);
    MRIcopyHeader(mritmp,mriout);
    for(c=0; c < nc; c++)
    {
      for(r=0; r < nr; r++)
      {
        for(s=0; s < ns; s++)
        {
          nhits = 0;
          vsum = 0;
          for(f=0; f < mriout->nframes; f++)
          {
            v = MRIgetVoxVal(mriout,c,r,s,f);
            if (v > 0)
            {
              vsum += v;
              nhits ++;
            }
          }
          if(nhits > 0 )
          {
            MRIsetVoxVal(mritmp,c,r,s,0,vsum/nhits);
          }
        } // for s
      }// for r
    } // for c
    MRIfree(&mriout);
    mriout = mritmp;
  } // do combine

  if(DoPrune)
  {
    // This computes the prune mask, applied below
    printf("Computing prune mask \n");
    PruneMask = MRIframeBinarize(mriout,FLT_MIN,NULL);
    printf("Found %d voxels in prune mask\n",MRInMask(PruneMask));
  }

  if(DoNormMean)
  {
    printf("Normalizing by mean across frames\n");
    MRInormalizeFramesMean(mriout);
  }
  if(DoNorm1)
  {
    printf("Normalizing by first across frames\n");
    MRInormalizeFramesFirst(mriout);
  }

  if(DoASL)
  {
    printf("Computing ASL matrix matrix\n");
    M = ASLinterpMatrix(mriout->nframes);
  }

  if(M != NULL)
  {
    printf("Multiplying by matrix\n");
    mritmp = fMRImatrixMultiply(mriout, M, NULL);
    if(mritmp == NULL)
    {
      exit(1);
    }
    MRIfree(&mriout);
    mriout = mritmp;
  }

  if(DoPaired)
  {
    printf("Combining pairs\n");
    mritmp = MRIcloneBySpace(mriout,-1,mriout->nframes/2);
    for (c=0; c < nc; c++)
    {
      for (r=0; r < nr; r++)
      {
        for (s=0; s < ns; s++)
        {
          fout = 0;
          for (f=0; f < mriout->nframes; f+=2)
          {
            v1 = MRIgetVoxVal(mriout,c,r,s,f);
            v2 = MRIgetVoxVal(mriout,c,r,s,f+1);
            v = 0;
            if(DoPairedAvg)
            {
              v = (v1+v2)/2.0;
            }
            if(DoPairedSum)
            {
              v = (v1+v2);
            }
            if(DoPairedDiff)
            {
              v = v1-v2;  // difference
            }
            if(DoPairedDiffNorm)
            {
              v = v1-v2; // difference
              vavg = (v1+v2)/2.0;
              if (vavg != 0.0)
              {
                v = v/vavg;
              }
            }
            if(DoPairedDiffNorm1)
            {
              v = v1-v2; // difference
              if (v1 != 0.0)
              {
                v = v/v1;
              }
              else
              {
                v = 0;
              }
            }
            if(DoPairedDiffNorm2)
            {
              v = v1-v2; // difference
              if (v2 != 0.0)
              {
                v = v/v2;
              }
              else
              {
                v = 0;
              }
            }
            MRIsetVoxVal(mritmp,c,r,s,fout,v);
            fout++;
          }
        }
      }
    }
    MRIfree(&mriout);
    mriout = mritmp;
  }
  nframes = mriout->nframes;
  printf("nframes = %d\n",nframes);

  if(DoBonfCor)
  {
    DoAdd = 1;
    AddVal = -log10(mriout->nframes);
  }

  if(DoMean)
  {
    printf("Computing mean across frames\n");
    mritmp = MRIframeMean(mriout,NULL);
    MRIfree(&mriout);
    mriout = mritmp;
  }
  if(DoMedian)
  {
    printf("Computing median across frames\n");
    mritmp = MRIframeMedian(mriout,NULL);
    MRIfree(&mriout);
    mriout = mritmp;
  }
  if(DoMeanDivN)
  {
    printf("Computing mean2 = sum/(nframes^2)\n");
    mritmp = MRIframeSum(mriout,NULL);
    MRIfree(&mriout);
    mriout = mritmp;
    MRImultiplyConst(mriout, 1.0/(nframes*nframes), mriout);
  }
  if(DoSum)
  {
    printf("Computing sum across frames\n");
    mritmp = MRIframeSum(mriout,NULL);
    MRIfree(&mriout);
    mriout = mritmp;
  }
  if(DoTAR1)
  {
    printf("Computing temoral AR1 %d\n",mriout->nframes-TAR1DOFAdjust);
    mritmp = fMRItemporalAR1(mriout,TAR1DOFAdjust,NULL,NULL);
    MRIfree(&mriout);
    mriout = mritmp;
  }

  if(DoStd || DoVar)
  {
    printf("Computing std/var across frames\n");
    if(mriout->nframes < 2)
    {
      printf("ERROR: cannot compute std from one frame\n");
      exit(1);
    }
    //mritmp = fMRIvariance(mriout, -1, 1, NULL);
    mritmp = fMRIcovariance(mriout, 0, -1, NULL, NULL);
    if(DoStd)
    {
      MRIsqrt(mritmp, mritmp);
    }
    MRIfree(&mriout);
    mriout = mritmp;
  }

  if(DoMax)
  {
    printf("Computing max across all frames \n");
    mritmp = MRIvolMax(mriout,NULL);
    MRIfree(&mriout);
    mriout = mritmp;
  }

  if(DoMaxIndex)
  {
    printf("Computing max index across all frames \n");
    mritmp = MRIvolMaxIndex(mriout,1,NULL,NULL);
    MRIfree(&mriout);
    mriout = mritmp;
  }

  if(DoConjunction)
  {
    printf("Computing conjunction across all frames \n");
    mritmp = MRIconjunct(mriout,NULL);
    MRIfree(&mriout);
    mriout = mritmp;
  }

  if(DoMin)
  {
    printf("Computing min across all frames \n");
    mritmp = MRIvolMin(mriout,NULL);
    MRIfree(&mriout);
    mriout = mritmp;
  }

  if(DoSort)
  {
    printf("Sorting \n");
    mritmp = MRIsort(mriout,mask,NULL);
    MRIfree(&mriout);
    mriout = mritmp;
  }

  if(DoVote)
  {
    printf("Voting \n");
    mritmp = MRIvote(mriout,mask,NULL);
    MRIfree(&mriout);
    mriout = mritmp;
  }

  if(DoMultiply)
  {
    printf("Multiplying by %lf\n",MultiplyVal);
    MRImultiplyConst(mriout, MultiplyVal, mriout);
  }

  if(DoAdd)
  {
    printf("Adding %lf\n",AddVal);
    MRIaddConst(mriout, AddVal, mriout);
  }

  if(DoSCM)
  {
    printf("Computing spatial correlation matrix (%d)\n",mriout->nframes);
    mritmp = fMRIspatialCorMatrix(mriout);
    if(mritmp == NULL)
    {
      exit(1);
    }
    MRIfree(&mriout);
    mriout = mritmp;
  }

  if(DoPCA)
  {
    // Saves only non-zero components
    printf("Computing PCA\n");
    if(PCAMaskFile)
    {
      printf("  PCA Mask %s\n",PCAMaskFile);
      PCAMask = MRIread(PCAMaskFile);
      if(PCAMask == NULL)
      {
        exit(1);
      }
    }
    err=MRIpca(mriout, &Upca, &Spca, &Vpca, PCAMask);
    if(err)
    {
      exit(1);
    }
    stem = IDstemFromName(out);
    sprintf(tmpstr,"%s.u.mtx",stem);
    MatrixWriteTxt(tmpstr, Upca);
    sprintf(tmpstr,"%s.stats.dat",stem);
    WritePCAStats(tmpstr,Spca);
    MRIfree(&mriout);
    mriout = Vpca;
  }

  if(NReplications > 0)
  {
    printf("NReplications %d\n",NReplications);
    mritmp = MRIallocSequence(mriout->width,
                              mriout->height,
                              mriout->depth,
                              mriout->type,
                              mriout->nframes*NReplications);
    if(mritmp == NULL)
    {
      exit(1);
    }
    printf("Done allocing\n");
    MRIcopyHeader(mriout,mritmp);
    for(c=0; c < mriout->width; c++)
    {
      for(r=0; r < mriout->height; r++)
      {
        for(s=0; s < mriout->depth; s++)
        {
          outf = 0;
          for(nthrep = 0; nthrep < NReplications; nthrep++)
          {
            for(f=0; f < mriout->nframes; f++)
            {
              v = MRIgetVoxVal(mriout,c,r,s,f);
              MRIsetVoxVal(mritmp,c,r,s,outf,v);
              outf ++;
            }
          }
        }
      }
    }
    MRIfree(&mriout);
    mriout = mritmp;
  }

  if(DoPrune)
  {
    // Apply prune mask that was computed above
    printf("Applying prune mask \n");
    MRImask(mriout, PruneMask, mriout, 0, 0);
  }

  if(DoRMS)
  {
    printf("Computing RMS across input frames\n");
    mritmp = MRIread(inlist[0]);
    MRIcopyHeader(mritmp, mriout);
    MRIrms(mritmp,mriout);
  }

  printf("Writing to %s\n",out);
  err = MRIwrite(mriout,out);
  if(err)
  {
    exit(err);
  }

  return(0);
}
コード例 #16
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) ;
}
コード例 #17
0
int
main(int argc, char *argv[])
{
  char         *gca_fname, *in_fname, *out_fname, **av, *xform_fname, fname[STRLEN] ;
  MRI          *mri_in, *mri_norm = NULL, *mri_tmp, *mri_ctrl = NULL ;
  GCA          *gca ;
  int          ac, nargs, nsamples, msec, minutes, seconds;
  int          i, struct_samples, norm_samples = 0, n, input, ninputs ;
  struct timeb start ;
  GCA_SAMPLE   *gcas, *gcas_norm = NULL, *gcas_struct ;
  TRANSFORM    *transform = NULL ;
  char         cmdline[CMD_LINE_LEN], line[STRLEN], *cp, subject[STRLEN], sdir[STRLEN], base_name[STRLEN] ;
  FILE         *fp ;

  make_cmd_version_string
    (argc, argv,
     "$Id: mri_cal_normalize.c,v 1.2.2.1 2011/08/31 00:32:41 nicks Exp $",
     "$Name: stable5 $", cmdline);

  /* rkt: check for and handle version tag */
  nargs = handle_version_option
    (argc, argv,
     "$Id: mri_cal_normalize.c,v 1.2.2.1 2011/08/31 00:32:41 nicks Exp $",
     "$Name: stable5 $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  setRandomSeed(-1L) ;
  Progname = argv[0] ;

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

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

  if (argc < 6)
    ErrorExit
      (ERROR_BADPARM,
       "usage: %s [<options>] <longitudinal time point file> <in vol> <atlas> <transform file> <out vol> \n",
       Progname) ;
  in_fname = argv[2] ;
  gca_fname = argv[3] ;
  xform_fname = argv[4] ;
  out_fname = argv[5] ;

  transform = TransformRead(xform_fname) ;
  if (transform == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not read transform from %s", Progname, xform_fname) ;
  if (read_ctrl_point_fname)
  {
    mri_ctrl = MRIread(read_ctrl_point_fname) ;
    if (mri_ctrl == NULL)
      ErrorExit(ERROR_NOFILE, "%s: could not read precomputed control points from %s", 
                Progname, read_ctrl_point_fname) ;
  }
  TimerStart(&start) ;
  printf("reading atlas from '%s'...\n", gca_fname) ;
  fflush(stdout) ;

  gca = GCAread(gca_fname) ;
  if (gca == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not open GCA %s.\n",Progname, gca_fname) ;
  GCAregularizeConditionalDensities(gca, .5) ;

  FileNamePath(argv[1], sdir) ;
  cp = strrchr(sdir, '/') ; 
  if (cp)
  {
    strcpy(base_name, cp+1) ;
    *cp = 0 ;  // remove last component of path, which is base subject name
  }
  ninputs = 0 ;
  fp = fopen(argv[1], "r") ;
  if (fp == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not read time point file %s", argv[1]) ;

  do
  {
    cp = fgetl(line, STRLEN-1, fp) ;
    if (cp != NULL && strlen(cp) > 0)
    {
      subjects[ninputs] = (char *)calloc(strlen(cp)+1, sizeof(char)) ;
      strcpy(subjects[ninputs], cp) ;
      ninputs++ ;
    }
  } while (cp != NULL && strlen(cp) > 0) ;
  fclose(fp) ;
  printf("processing %d timepoints in SUBJECTS_DIR %s...\n", ninputs, sdir) ;
  for (input = 0 ; input < ninputs ; input++)
  {
    sprintf(subject, "%s.long.%s", subjects[input], base_name) ;
    printf("reading subject %s - %d of %d\n", subject, input+1, ninputs) ;
    sprintf(fname, "%s/%s/mri/%s", sdir, subject, in_fname) ;
    mri_tmp = MRIread(fname) ;
    if (!mri_tmp)
      ErrorExit(ERROR_NOFILE, "%s: could not read input MR volume from %s",
                Progname, fname) ;
    MRImakePositive(mri_tmp, mri_tmp) ;
    if (mri_tmp && ctrl_point_fname && !mri_ctrl)
    {
      mri_ctrl = MRIallocSequence(mri_tmp->width, mri_tmp->height, 
                                  mri_tmp->depth,MRI_FLOAT, nregions*2) ; // labels and means
      MRIcopyHeader(mri_tmp, mri_ctrl) ;
    }
    if (input == 0)
    {
      mri_in =
        MRIallocSequence(mri_tmp->width, mri_tmp->height, mri_tmp->depth,
                         mri_tmp->type, ninputs) ;
      if (!mri_in)
        ErrorExit(ERROR_NOMEMORY,
                  "%s: could not allocate input volume %dx%dx%dx%d",
                  mri_tmp->width,mri_tmp->height,mri_tmp->depth,ninputs) ;
      MRIcopyHeader(mri_tmp, mri_in) ;
    }

    if (mask_fname)
    {
      int i ;
      MRI *mri_mask ;

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

      for (i = 1 ; i < WM_MIN_VAL ; i++)
        MRIreplaceValues(mri_mask, mri_mask, i, 0) ;
      MRImask(mri_tmp, mri_mask, mri_tmp, 0, 0) ;
      MRIfree(&mri_mask) ;
    }
    MRIcopyFrame(mri_tmp, mri_in, 0, input) ;
    MRIfree(&mri_tmp) ;
  }
  MRIaddCommandLine(mri_in, cmdline) ;

  GCAhistoScaleImageIntensitiesLongitudinal(gca, mri_in, 1) ;

  {
    int j ;

    gcas = GCAfindAllSamples(gca, &nsamples, NULL, 1) ;
    printf("using %d sample points...\n", nsamples) ;
    GCAcomputeSampleCoords(gca, mri_in, gcas, nsamples, transform) ;
    if (sample_fname)
      GCAtransformAndWriteSamples
        (gca, mri_in, gcas, nsamples, sample_fname, transform) ;

    for (j = 0 ; j < 1 ; j++)
    {
      for (n = 1 ; n <= nregions ; n++)
      {
        for (norm_samples = i = 0 ; i < NSTRUCTURES ; i++)
        {
          if (normalization_structures[i] == Gdiag_no)
            DiagBreak() ;
          printf("finding control points in %s....\n",
                 cma_label_to_name(normalization_structures[i])) ;
          gcas_struct = find_control_points(gca, gcas, nsamples, &struct_samples, n,
                                            normalization_structures[i], mri_in, transform, min_prior,
                                            ctl_point_pct) ;
          discard_unlikely_control_points(gca, gcas_struct, struct_samples, mri_in, transform,
                                          cma_label_to_name(normalization_structures[i])) ;
          if (mri_ctrl && ctrl_point_fname) // store the samples
            copy_ctrl_points_to_volume(gcas_struct, struct_samples, mri_ctrl, n-1) ;
          if (i)
          {
            GCA_SAMPLE *gcas_tmp ;
            gcas_tmp = gcas_concatenate(gcas_norm, gcas_struct, norm_samples, struct_samples) ;
            free(gcas_norm) ;
            norm_samples += struct_samples ;
            gcas_norm = gcas_tmp ;
          }
          else
          {
            gcas_norm = gcas_struct ; norm_samples = struct_samples ;
          }
        }
        
        printf("using %d total control points "
                 "for intensity normalization...\n", norm_samples) ;
        if (normalized_transformed_sample_fname)
          GCAtransformAndWriteSamples(gca, mri_in, gcas_norm, norm_samples,
                                      normalized_transformed_sample_fname,
                                      transform) ;
        mri_norm = GCAnormalizeSamplesAllChannels(mri_in, gca, gcas_norm, file_only ? 0 :norm_samples,
                                                  transform, ctl_point_fname, bias_sigma) ;
        if (Gdiag & DIAG_WRITE)
        {
          char fname[STRLEN] ;
          sprintf(fname, "norm%d.mgz", n) ;
          printf("writing normalized volume to %s...\n", fname) ;
          MRIwrite(mri_norm, fname) ;
          sprintf(fname, "norm_samples%d.mgz", n) ;
          GCAtransformAndWriteSamples(gca, mri_in, gcas_norm, norm_samples,
                                      fname, transform) ;
          
        }
        MRIcopy(mri_norm, mri_in) ;  /* for next pass through */
        MRIfree(&mri_norm) ;
      }
    }
  }

  // now do cross-time normalization to bring each timepoint closer to the mean at each location
  {
    MRI   *mri_frame1, *mri_frame2, *mri_tmp ;
    double rms_before, rms_after ;
    int    i ;

    mri_tmp = MRIcopy(mri_in, NULL) ;
    mri_frame1 = MRIcopyFrame(mri_in, NULL, 0, 0) ;
    mri_frame2 = MRIcopyFrame(mri_in, NULL, 1, 0) ;
    rms_before = MRIrmsDiff(mri_frame1, mri_frame2) ;
    printf("RMS before = %2.2f\n", rms_before) ;
    MRIfree(&mri_frame1) ; MRIfree(&mri_frame2) ;
    for (i = 50 ; i <= 50 ; i += 25)
    {
      MRIcopy(mri_tmp, mri_in) ;
      normalize_timepoints_with_samples(mri_in, gcas_norm, norm_samples, i) ;
      mri_frame1 = MRIcopyFrame(mri_in, NULL, 0, 0) ;
      mri_frame2 = MRIcopyFrame(mri_in, NULL, 1, 0) ;
      rms_after = MRIrmsDiff(mri_frame1, mri_frame2) ;
      MRIfree(&mri_frame1) ; MRIfree(&mri_frame2) ;
      printf("RMS after (%d) = %2.2f\n", i, rms_after) ;
    }
  }
  {
    MRI   *mri_frame1, *mri_frame2 ;
    double rms_after ;
    int    i ;

    mri_tmp = MRIcopy(mri_in, NULL) ;
    for (i = 10 ; i <= 10 ; i += 10)
    {
      MRIcopy(mri_tmp, mri_in) ;
      normalize_timepoints(mri_in, 2.0, i) ;
      mri_frame1 = MRIcopyFrame(mri_in, NULL, 0, 0) ;
      mri_frame2 = MRIcopyFrame(mri_in, NULL, 1, 0) ;
      rms_after = MRIrmsDiff(mri_frame1, mri_frame2) ;
      MRIfree(&mri_frame1) ; MRIfree(&mri_frame2) ;
      printf("RMS after intensity cohering = %2.2f\n", rms_after) ;
    }
  }

  for (input = 0 ; input < ninputs ; input++)
  {
    sprintf(fname, "%s/%s.long.%s/mri/%s", sdir, subjects[input], base_name, out_fname) ;
    printf("writing normalized volume to %s...\n", fname) ;
    if (MRIwriteFrame(mri_in, fname, input)  != NO_ERROR)
      ErrorExit(ERROR_BADFILE, "%s: could not write normalized volume to %s",Progname, fname);
  }

  if (ctrl_point_fname)
  {
    printf("writing control points to %s\n", ctrl_point_fname) ;
    MRIwrite(mri_ctrl, ctrl_point_fname) ;
    MRIfree(&mri_ctrl) ;
  }
  MRIfree(&mri_in) ;

  printf("freeing GCA...") ;
  if (gca)
    GCAfree(&gca) ;
  printf("done.\n") ;
  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  printf("normalization took %d minutes and %d seconds.\n",
         minutes, seconds) ;
  if (diag_fp)
    fclose(diag_fp) ;
  exit(0) ;
  return(0) ;
}
コード例 #18
0
ファイル: afni.c プロジェクト: guo2004131/freesurfer
/*------------------------------------------------------*/
MRI *afniRead(const char *fname, int read_volume)
{

  FILE *fp;
  char header_fname[STRLEN];
  char *c;
  MRI *mri, *header;
  int big_endian_flag;
  long brik_file_length;
  long nvoxels;
  int bytes_per_voxel;
  int i, j, k;
  int swap_flag;
  AF af;
  float scaling = 1.;
  void *pmem = 0;
  float *pf;
  short *ps;
  unsigned char *pc;

  float det;
  float xfov, yfov, zfov;
  float fMin = 0.;
  float fMax = 0.;
  float flMin = 0.;
  float flMax = 0.;
  int initialized = 0;
  int frame;
  int bytes;

  strcpy(header_fname, fname);
  c = strrchr(header_fname, '.');

  if (c == NULL)
  {
    errno = 0;
    ErrorReturn(NULL, (ERROR_BADPARM, "afniRead(): bad file name %s", fname));
  }

  if (strcmp(c, ".BRIK") != 0)
  {
    errno = 0;
    ErrorReturn(NULL, (ERROR_BADPARM, "afniRead(): bad file name %s", fname));
  }

  sprintf(c, ".HEAD");

  if ((fp = fopen(header_fname, "r")) == NULL)
  {
    errno = 0;
    ErrorReturn(NULL, (ERROR_BADFILE, "afniRead(): error opening file %s", header_fname));
  }

  // initialize AFNI structure
  AFinit(&af);

  // read header file
  if (!readAFNIHeader(fp, &af))
    return (NULL);

  printAFNIHeader(&af);

  // well, we don't have time
  if (af.numtypes != 1) // should be the same as af.dataset_rank[1] = subbricks
  {
    errno = 0;
    // ErrorReturn(NULL, (ERROR_UNSUPPORTED, "afniRead(): nframes = %d (only 1 frame supported)", af.numtypes));
    printf("INFO: number of frames dataset_rank[1] = %d : numtypes = %d \n",
           af.dataset_rank[1], af.numtypes);
  }
  // byteorder_string : required field
  if (strcmp(af.byteorder_string, "MSB_FIRST") == 0)
    big_endian_flag = 1;
  else if (strcmp(af.byteorder_string, "LSB_FIRST") == 0)
    big_endian_flag = 0;
  else
  {
    errno = 0;
    ErrorReturn(NULL, (ERROR_BADPARM, "read_afni_header(): unrecognized byte order string %s",
                       af.byteorder_string));
  }
  // brick_types : required field
  if (af.brick_types[0] == 2 // int
      || af.brick_types[0] > 3 )// 4 = double, 5 = complex, 6 = rgb
  {
    errno = 0;
    ErrorReturn(NULL,
                (ERROR_BADPARM,
                 "afniRead(): unsupported data type %d, Must be 0 (byte), 1(short), or 3(float)",
                 af.brick_types[0]));
  }
  //////////////////////////////////////////////////////////////////////////////////
  // now we allocate space for MRI
  // dataset_dimensions : required field
  header = MRIallocHeader(af.dataset_dimensions[0],
                          af.dataset_dimensions[1],
                          af.dataset_dimensions[2],
                          MRI_UCHAR,
                          af.dataset_rank[1]
                          );
  // set number of frames
  header->nframes = af.dataset_rank[1];

  // direction cosines (use orient_specific)
  // orient_specific : required field
  header->x_r = afni_orientations[af.orient_specific[0]][0];
  header->x_a = afni_orientations[af.orient_specific[0]][1];
  header->x_s = afni_orientations[af.orient_specific[0]][2];
  header->y_r = afni_orientations[af.orient_specific[1]][0];
  header->y_a = afni_orientations[af.orient_specific[1]][1];
  header->y_s = afni_orientations[af.orient_specific[1]][2];
  header->z_r = afni_orientations[af.orient_specific[2]][0];
  header->z_a = afni_orientations[af.orient_specific[2]][1];
  header->z_s = afni_orientations[af.orient_specific[2]][2];

  /* --- quick determinant check --- */
  det = + header->x_r * (header->y_a * header->z_s - header->z_a * header->y_s)
        - header->x_a * (header->y_r * header->z_s - header->z_r * header->y_s)
        + header->x_s * (header->y_r * header->z_a - header->z_r * header->y_a);

  if (det == 0)
  {
    MRIfree(&header);
    errno = 0;
    ErrorReturn(NULL,
                (ERROR_BADPARM,
                 "read_afni_header(): error in orientations %d, %d, %d (direction cosine matrix has determinant zero)",
                 af.orient_specific[0], af.orient_specific[1], af.orient_specific[2]));
  }
  // sizes use delta
  // delta : required field
  header->xsize = af.delta[0];
  header->ysize = af.delta[1];
  header->zsize = af.delta[2];

  // uses origin
  // origin : required field
  header->c_r = header->x_r * (header->xsize * (header->width-1.0)/2.0 + af.origin[0]) +
                header->y_r * (header->ysize * (header->height-1.0)/2.0 + af.origin[1]) +
                header->z_r * (header->zsize * (header->depth-1.0)/2.0 + af.origin[2]);

  header->c_a = header->x_a * (header->xsize * (header->width-1.0)/2.0 + af.origin[0]) +
                header->y_a * (header->ysize * (header->height-1.0)/2.0 + af.origin[1]) +
                header->z_a * (header->zsize * (header->depth-1.0)/2.0 + af.origin[2]);

  header->c_s = header->x_s * (header->xsize * (header->width-1.0)/2.0 + af.origin[0]) +
                header->y_s * (header->ysize * (header->height-1.0)/2.0 + af.origin[1]) +
                header->z_s * (header->zsize * (header->depth-1.0)/2.0 + af.origin[2]);

  header->ras_good_flag = 1;

  if (header->xsize < 0)
    header->xsize = -header->xsize;

  if (header->ysize < 0)
    header->ysize = -header->ysize;

  if (header->zsize < 0)
    header->zsize = -header->zsize;

  header->imnr0 = 1;
  header->imnr1 = header->depth;

  header->ps = header->xsize;
  header->thick = header->zsize;

  header->xend = (header->width  / 2.0) * header->xsize;
  header->xstart = -header->xend;
  header->yend = (header->height / 2.0) * header->ysize;
  header->ystart = -header->yend;
  header->zend = (header->depth  / 2.0) * header->zsize;
  header->zstart = -header->zend;

  xfov = header->xend - header->xstart;
  yfov = header->yend - header->ystart;
  zfov = header->zend - header->zstart;

  header->fov = ( xfov > yfov ? (xfov > zfov ? xfov : zfov ) : (yfov > zfov ? yfov : zfov ) );

#if (BYTE_ORDER==LITTLE_ENDIAN)
  //#ifdef Linux
  swap_flag = big_endian_flag;
#else
  swap_flag = !big_endian_flag;
#endif

  if ((fp = fopen(fname, "r")) == NULL)
  {
    MRIfree(&header);
    errno = 0;
    ErrorReturn(NULL, (ERROR_BADFILE, "afniRead(): error opening file %s", header_fname));
  }

  fseek(fp, 0, SEEK_END);
  brik_file_length = ftell(fp);
  fseek(fp, 0, SEEK_SET);

  // number of voxels consecutive

  nvoxels = header->width * header->height * header->depth * header->nframes;

  if (brik_file_length % nvoxels)
  {
    fclose(fp);
    MRIfree(&header);
    errno = 0;
    ErrorReturn(NULL, (ERROR_BADFILE, "afniRead(): BRIK file length (%d) is not divisible by the number of voxels (%d)", brik_file_length, nvoxels));
  }
  // bytes_per_voxel = brik_file_length / nvoxels; // this assumes one frame
  bytes_per_voxel = af.brick_types[0] + 1; // 0(byte)-> 1, 1(short) -> 2, 3(float)->4

  bytes = header->width*header->height*header->depth*bytes_per_voxel;

  // this check is for nframes = 1 case which is the one we are supporting
  if (bytes_per_voxel != brik_file_length/nvoxels)
  {
    fclose(fp);
    MRIfree(&header);
    errno = 0;
    ErrorReturn(NULL,
                (ERROR_UNSUPPORTED,
                 "afniRead(): type info stored in header does not agree with the file size: %d != %d/%d",
                 bytes_per_voxel, brik_file_length/nvoxels));
  }

  // if brick_float_facs != 0 then we scale values to be float
  if (af.numfacs != 0 && af.brick_float_facs[0] != 0.)
  {
    header->type = MRI_FLOAT;
    scaling = af.brick_float_facs[0];
  }
  else
  {
    if (bytes_per_voxel == 1)
      header->type = MRI_UCHAR;
    else if (bytes_per_voxel == 2)
      header->type = MRI_SHORT;
    else if (bytes_per_voxel == 4)
      header->type = MRI_FLOAT;
    else
    {
      fclose(fp);
      MRIfree(&header);
      errno = 0;
      ErrorReturn(NULL, (ERROR_UNSUPPORTED, "afniRead(): don't know what to do with %d bytes per voxel", bytes_per_voxel));
    }
  }

  ///////////////////////////////////////////////////////////////////////
  if (read_volume)
  {
    // mri = MRIalloc(header->width, header->height, header->depth, header->type);
    mri = MRIallocSequence(header->width, header->height, header->depth,
                           header->type, header->nframes) ;
    MRIcopyHeader(header, mri);

    for (frame = 0; frame < header->nframes; ++frame)
    {
      initialized = 0;
      for (k = 0;k < mri->depth;k++)
      {
        for (j = 0;j < mri->height;j++)
        {
          if (af.brick_float_facs[frame])
            scaling = af.brick_float_facs[frame];
          else
            scaling = 1.;
          {
            pmem = (void *) malloc(bytes_per_voxel*mri->width);
            if (pmem)
            {
              if (fread(pmem, bytes_per_voxel, mri->width, fp) != mri->width)
              {
                fclose(fp);
                MRIfree(&header);
                errno = 0;
                ErrorReturn(NULL, (ERROR_BADFILE, "afniRead(): error reading from file %s", fname));
              }
              // swap bytes
              if (swap_flag)
              {
                if (bytes_per_voxel == 2) // short
                {
                  swab(pmem, pmem, mri->width * 2);
                }
                else if (bytes_per_voxel == 4) // float
                {
                  pf = (float *) pmem;
                  for (i = 0;i < mri->width;i++, pf++)
                    *pf = swapFloat(*pf);
                }
              }
              // now scaling
              if (bytes_per_voxel == 1) // byte
              {
                pc = (unsigned char *) pmem;
                for (i=0; i < mri->width; i++)
                {
                  if (scaling == 1.)
                    MRIseq_vox(mri, i, j, k, frame) = *pc;
                  else
                    MRIFseq_vox(mri, i, j, k, frame) = ((float) (*pc))*scaling;
                  ++pc;
                }
                findMinMaxByte((unsigned char *) pmem, mri->width, &flMin, &flMax);
              }
              if (bytes_per_voxel == 2) // short
              {
                ps = (short *) pmem;
                for (i=0; i < mri->width; i++)
                {
                  // if (*ps != 0)
                  //   printf("%d ", *ps);
                  if (scaling == 1.)
                    MRISseq_vox(mri, i, j, k, frame) = *ps;
                  else
                    MRIFseq_vox(mri, i, j, k, frame) = ((float) (*ps))*scaling;
                  ++ps;
                }
                findMinMaxShort((short *) pmem, mri->width, &flMin, &flMax);
              }
              else if (bytes_per_voxel == 4) // float
              {
                pf = (float *) pmem;
                for (i=0; i < mri->width; i++)
                {

                  MRIFseq_vox(mri, i, j, k, frame) = (*pf)*scaling;
                  ++pf;
                }
                findMinMaxFloat((float *) pmem, mri->width, &flMin, &flMax);
              }
              free(pmem);
              //
              if (initialized == 0)
              {
                fMin = flMin;
                fMax = flMax;
                initialized = 1;
              }
              else
              {
                if (flMin < fMin)
                  fMin = flMin;
                if (flMax > fMax)
                  fMax = flMax;
                // printf("\n fmin =%f, fmax = %f, local min = %f, max = %f\n", fMin, fMax, flMin, flMax);
              }
            }
            else
            {
              fclose(fp);
              MRIfree(&header);
              errno = 0;
              ErrorReturn(NULL,
                          (ERROR_BADFILE, "afniRead(): could not allocate memory for reading %s", fname));
            }
          }
        } // height
      } // depth
      // valid only for nframs == 1
      {
        printf("BRICK_STATS min = %f <--> actual min = %f\n",
               af.brick_stats[0+2*frame], fMin*scaling);
        printf("BRICK_STATS max = %f <--> actual max = %f\n",
               af.brick_stats[1+2*frame], fMax*scaling);
      }
    } // nframes
  }
  else // not reading volume
    mri = MRIcopy(header, NULL);

  strcpy(mri->fname, fname);

  fclose(fp);

  MRIfree(&header);
  AFclean(&af);

  return(mri);

} /* end afniRead() */
コード例 #19
0
ファイル: mri_volsynth.c プロジェクト: ewong718/freesurfer
/*---------------------------------------------------------------*/
int main(int argc, char **argv)
{
  int c,r,s,f;
  double val,rval;
  FILE *fp;
  MRI *mritmp;

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

  /* assign default geometry */
  cdircos[0] = 1.0;
  cdircos[1] = 0.0;
  cdircos[2] = 0.0;
  rdircos[0] = 0.0;
  rdircos[1] = 1.0;
  rdircos[2] = 0.0;
  sdircos[0] = 0.0;
  sdircos[1] = 0.0;
  sdircos[2] = 1.0;
  res[0] = 1.0;
  res[1] = 1.0;
  res[2] = 1.0;
  cras[0] = 0.0;
  cras[1] = 0.0;
  cras[2] = 0.0;
  res[3] = 2.0; /* TR */

  if (argc == 0) usage_exit();

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

  if(tempid != NULL) {
    printf("INFO: reading template header\n");
    if(! DoCurv) mritemp = MRIreadHeader(tempid,tempfmtid);
    else         mritemp = MRIread(tempid);
    if (mritemp == NULL) {
      printf("ERROR: reading %s header\n",tempid);
      exit(1);
    }
    if(NewVoxSizeSpeced){
      dim[0] = round(mritemp->width*mritemp->xsize/res[0]);
      dim[1] = round(mritemp->height*mritemp->ysize/res[1]);
      dim[2] = round(mritemp->depth*mritemp->zsize/res[2]);
      dim[3] = mritemp->nframes;
      res[3] = mritemp->tr;
      dimSpeced = 1;
    }
    if(dimSpeced){
      mritmp = MRIallocSequence(dim[0],dim[1],dim[2],MRI_FLOAT,dim[3]);
      MRIcopyHeader(mritemp,mritmp);
      MRIfree(&mritemp);
      mritemp = mritmp;
    }
    if(resSpeced){
      mritemp->xsize = res[0];
      mritemp->ysize = res[1];
      mritemp->zsize = res[2];
      mritemp->tr    = res[3];
    }

    dim[0] = mritemp->width;
    dim[1] = mritemp->height;
    dim[2] = mritemp->depth;
    if (nframes > 0) dim[3] = nframes;
    else             dim[3] = mritemp->nframes;
    mritemp->nframes = dim[3];
  }

  if(mritemp) {
    if(SpikeTP >= mritemp->nframes){
      printf("ERROR: SpikeTP = %d >= mritemp->nframes = %d\n",
             SpikeTP,mritemp->nframes);
      exit(1);
    }
  }

  printf("Synthesizing\n");
  srand48(seed);
  if (strcmp(pdfname,"gaussian")==0)
    mri = MRIrandn(dim[0], dim[1], dim[2], dim[3], gausmean, gausstd, NULL);
  else if (strcmp(pdfname,"uniform")==0)
    mri = MRIdrand48(dim[0], dim[1], dim[2], dim[3], 0, 1, NULL);
  else if (strcmp(pdfname,"const")==0)
    mri = MRIconst(dim[0], dim[1], dim[2], dim[3], ValueA, NULL);
  else if (strcmp(pdfname,"sphere")==0) {
    if(voxradius < 0)
      voxradius =
        sqrt( pow(dim[0]/2.0,2)+pow(dim[1]/2.0,2)+pow(dim[2]/2.0,2) )/2.0;
    printf("voxradius = %lf\n",voxradius);
    mri = MRIsphereMask(dim[0], dim[1], dim[2], dim[3],
                        dim[0]/2.0, dim[1]/2.0, dim[2]/2.0,
                        voxradius, ValueA, NULL);
  } else if (strcmp(pdfname,"delta")==0) {
    mri = MRIconst(dim[0], dim[1], dim[2], dim[3], delta_off_value, NULL);
    if (delta_crsf_speced == 0) {
      delta_crsf[0] = dim[0]/2;
      delta_crsf[1] = dim[1]/2;
      delta_crsf[2] = dim[2]/2;
      delta_crsf[3] = dim[3]/2;
    }
    printf("delta set to %g at %d %d %d %d\n",delta_value,delta_crsf[0],
           delta_crsf[1],delta_crsf[2],delta_crsf[3]);
    MRIFseq_vox(mri,
                delta_crsf[0],
                delta_crsf[1],
                delta_crsf[2],
                delta_crsf[3]) = delta_value;
  } else if (strcmp(pdfname,"chi2")==0) {
    rfs = RFspecInit(seed,NULL);
    rfs->name = strcpyalloc("chi2");
    rfs->params[0] = dendof;
    mri = MRIconst(dim[0], dim[1], dim[2], dim[3], 0, NULL);
    printf("Synthesizing chi2 with dof=%d\n",dendof);
    RFsynth(mri,rfs,NULL);
  } else if (strcmp(pdfname,"z")==0) {
    printf("Synthesizing z \n");
    rfs = RFspecInit(seed,NULL);
    rfs->name = strcpyalloc("gaussian");
    rfs->params[0] = 0; // mean
    rfs->params[1] = 1; // std
    mri = MRIconst(dim[0], dim[1], dim[2], dim[3], 0, NULL);
    RFsynth(mri,rfs,NULL);
  } else if (strcmp(pdfname,"t")==0) {
    printf("Synthesizing t with dof=%d\n",dendof);
    rfs = RFspecInit(seed,NULL);
    rfs->name = strcpyalloc("t");
    rfs->params[0] = dendof;
    mri = MRIconst(dim[0], dim[1], dim[2], dim[3], 0, NULL);
    RFsynth(mri,rfs,NULL);
  } else if (strcmp(pdfname,"tr")==0) {
    printf("Synthesizing t with dof=%d as ratio of z/sqrt(chi2)\n",dendof);
    rfs = RFspecInit(seed,NULL);
    // numerator
    rfs->name = strcpyalloc("gaussian");
    rfs->params[0] = 0; // mean
    rfs->params[1] = 1; // std
    mri = MRIconst(dim[0], dim[1], dim[2], dim[3], 0, NULL);
    RFsynth(mri,rfs,NULL);
    // denominator
    rfs->name = strcpyalloc("chi2");
    rfs->params[0] = dendof;
    mri2 = MRIconst(dim[0], dim[1], dim[2], dim[3], 0, NULL);
    RFsynth(mri2,rfs,NULL);
    fMRIsqrt(mri2,mri2); // sqrt of chi2
    mri = MRIdivide(mri,mri2,mri);
    MRIscalarMul(mri, mri, sqrt(dendof)) ;
    MRIfree(&mri2);
  } else if (strcmp(pdfname,"F")==0) {
    printf("Synthesizing F with num=%d den=%d\n",numdof,dendof);
    rfs = RFspecInit(seed,NULL);
    rfs->name = strcpyalloc("F");
    rfs->params[0] = numdof;
    rfs->params[1] = dendof;
    mri = MRIconst(dim[0], dim[1], dim[2], dim[3], 0, NULL);
    RFsynth(mri,rfs,NULL);
  } else if (strcmp(pdfname,"Fr")==0) {
    printf("Synthesizing F with num=%d den=%d as ratio of two chi2\n",
           numdof,dendof);
    rfs = RFspecInit(seed,NULL);
    rfs->name = strcpyalloc("chi2");
    // numerator
    rfs->params[0] = numdof;
    mri = MRIconst(dim[0], dim[1], dim[2], dim[3], 0, NULL);
    RFsynth(mri,rfs,NULL);
    // denominator
    rfs->params[0] = dendof;
    mri2 = MRIconst(dim[0], dim[1], dim[2], dim[3], 0, NULL);
    RFsynth(mri2,rfs,NULL);
    mri = MRIdivide(mri,mri2,mri);
    MRIscalarMul(mri, mri, (double)dendof/numdof) ;
    MRIfree(&mri2);
  } else if (strcmp(pdfname,"voxcrs")==0) {
    // three frames. 1st=col, 2nd=row, 3rd=slice
    printf("Filling with vox CRS\n");
    mri = MRIconst(dim[0], dim[1], dim[2], 3, 0, NULL);
    for(c=0; c < mri->width; c ++){
      for(r=0; r < mri->height; r ++){
        for(s=0; s < mri->depth; s ++){
          MRIsetVoxVal(mri,c,r,s,0,c);
          MRIsetVoxVal(mri,c,r,s,1,r);
          MRIsetVoxVal(mri,c,r,s,2,s);
        }
      }
    }
  } else if (strcmp(pdfname,"boundingbox")==0) {
    printf("Setting bounding box \n");
    if(mritemp == NULL)
      mritemp = MRIconst(dim[0], dim[1], dim[2], dim[3], 0, NULL);
    mri = MRIsetBoundingBox(mritemp,&boundingbox,ValueA,ValueB);
    if(!mri) exit(1);
  } 
  else if (strcmp(pdfname,"checker")==0) {
    printf("Checker \n");
    mri=MRIchecker(mritemp,NULL);
    if(!mri) exit(1);
  } 
  else if (strcmp(pdfname,"sliceno")==0) {
    printf("SliceNo \n");
    if(mritemp == NULL){
      printf("ERROR: need --temp with sliceno\n");
      exit(1);
    }
    mri=MRIsliceNo(mritemp,NULL);
    if(!mri) exit(1);
  } 
  else if (strcmp(pdfname,"indexno")==0) {
    printf("IndexNo \n");
    if(mritemp == NULL){
      printf("ERROR: need --temp with indexno\n");
      exit(1);
    }
    mri=MRIindexNo(mritemp,NULL);
    if(!mri) exit(1);
  } 
  else if (strcmp(pdfname,"crs")==0) {
    printf("CRS \n");
    if(mritemp == NULL){
      printf("ERROR: need --temp with crs\n");
      exit(1);
    }
    mri=MRIcrs(mritemp,NULL);
    if(!mri) exit(1);
  } 
  else {
    printf("ERROR: pdf %s unrecognized, must be gaussian, uniform,\n"
	   "const, delta, checker\n", pdfname);
    exit(1);
  }
  if (tempid != NULL) {
    MRIcopyHeader(mritemp,mri);
    mri->type = MRI_FLOAT;
    // Override
    if(nframes > 0) mri->nframes = nframes;
    if(TR > 0) mri->tr = TR;
  } else {
    if(mri == NULL) {
      usage_exit();
    }
    mri->xsize = res[0];
    mri->ysize = res[1];
    mri->zsize = res[2];
    mri->tr    = res[3];
    mri->x_r = cdircos[0];
    mri->x_a = cdircos[1];
    mri->x_s = cdircos[2];
    mri->y_r = rdircos[0];
    mri->y_a = rdircos[1];
    mri->y_s = rdircos[2];
    mri->z_r = sdircos[0];
    mri->z_a = sdircos[1];
    mri->z_s = sdircos[2];
    if(!usep0){
      mri->c_r = cras[0];
      mri->c_a = cras[1];
      mri->c_s = cras[2];
    } 
    else MRIp0ToCRAS(mri, p0[0], p0[1], p0[2]);
  }

  if (gstd > 0) {
    if(!UseFFT){
      printf("Smoothing\n");
      MRIgaussianSmooth(mri, gstd, gmnnorm, mri); /* gmnnorm = 1 = normalize */
    }
    else {
      printf("Smoothing with FFT \n");
      mri2 = MRIcopy(mri,NULL);
      mri = MRI_fft_gaussian(mri2, mri,
                             gstd, gmnnorm); /* gmnnorm = 1 = normalize */
    }
    if (rescale) {
      printf("Rescaling\n");
      if (strcmp(pdfname,"z")==0)     RFrescale(mri,rfs,NULL,mri);
      if (strcmp(pdfname,"chi2")==0)  RFrescale(mri,rfs,NULL,mri);
      if (strcmp(pdfname,"t")==0)     RFrescale(mri,rfs,NULL,mri);
      if (strcmp(pdfname,"tr")==0)    RFrescale(mri,rfs,NULL,mri);
      if (strcmp(pdfname,"F")==0)     RFrescale(mri,rfs,NULL,mri);
      if (strcmp(pdfname,"Fr")==0)    RFrescale(mri,rfs,NULL,mri);
    }
  }

  if(DoHSC){
    // This multiplies each frame by a random number
    // between HSCMin HSCMax to simulate heteroscedastisity
    printf("Applying HSC %lf %lf\n",HSCMin,HSCMax);
    for(f=0; f < mri->nframes; f++){
      rval = (HSCMax-HSCMin)*drand48() + HSCMin;
      if(debug) printf("%3d %lf\n",f,rval);
      for(c=0; c < mri->width; c ++){
	for(r=0; r < mri->height; r ++){
	  for(s=0; s < mri->depth; s ++){
	    val = MRIgetVoxVal(mri,c,r,s,f);
	    MRIsetVoxVal(mri,c,r,s,f,rval*val);
	  }
        }
      }
    }
  }

  if(AddOffset) {
    printf("Adding offset\n");
    offset = MRIread(tempid);
    if(offset == NULL) exit(1);
    if(OffsetFrame == -1) OffsetFrame = nint(offset->nframes/2);
    printf("Offset frame %d\n",OffsetFrame);
    mritmp = fMRIframe(offset, OffsetFrame, NULL);
    if(mritmp == NULL) exit(1);
    MRIfree(&offset);
    offset = mritmp;
    fMRIaddOffset(mri, offset, NULL, mri);
  }

  if(SpikeTP > 0){
    printf("Spiking time point %d\n",SpikeTP);
    for(c=0; c < mri->width; c ++){
      for(r=0; r < mri->height; r ++){
        for(s=0; s < mri->depth; s ++){
          MRIsetVoxVal(mri,c,r,s,SpikeTP,1e9);
        }
      }
    }
  }

  if(DoAbs){
    printf("Computing absolute value\n");
    MRIabs(mri,mri);
  }

  if(!NoOutput){
    printf("Saving\n");
    if(!DoCurv)  MRIwriteAnyFormat(mri,volid,volfmt,-1,NULL);
    else {
      printf("Saving in curv format\n");
      MRIScopyMRI(surf, mri, 0, "curv");
      MRISwriteCurvature(surf,volid);
    }
  }

  if(sum2file){
    val = MRIsum2All(mri);
    fp = fopen(sum2file,"w");
    if(fp == NULL){
      printf("ERROR: opening %s\n",sum2file);
      exit(1);
    }
    printf("sum2all: %20.10lf\n",val);
    printf("vrf: %20.10lf\n",1/val);
    fprintf(fp,"%20.10lf\n",val);
  }

  return(0);
}
コード例 #20
0
ファイル: mri_mcsim.c プロジェクト: guo2004131/freesurfer
/*---------------------------------------------------------------*/
int main(int argc, char *argv[]) {
  int nargs, n, err;
  char tmpstr[2000], *signstr=NULL,*SUBJECTS_DIR, fname[2000];
  //char *OutDir = NULL;
  RFS *rfs;
  int nSmoothsPrev, nSmoothsDelta;
  MRI *z, *zabs=NULL, *sig=NULL, *p=NULL;
  int FreeMask = 0;
  int nthSign, nthFWHM, nthThresh;
  double sigmax, zmax, threshadj, csize, csizeavg, searchspace,avgvtxarea;
  int csizen;
  int nClusters, cmax,rmax,smax;
  SURFCLUSTERSUM *SurfClustList;
  struct timeb  mytimer;
  LABEL *clabel;
  FILE *fp, *fpLog=NULL;

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

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

  if(LogFile){
    fpLog = fopen(LogFile,"w");
    if(fpLog == NULL){
      printf("ERROR: opening %s\n",LogFile);
      exit(1);
    }
    dump_options(fpLog);
  } 

  if(SynthSeed < 0) SynthSeed = PDFtodSeed();
  srand48(SynthSeed);

  SUBJECTS_DIR = getenv("SUBJECTS_DIR");

  // Create output directory
  printf("Creating %s\n",OutTop);
  err = fio_mkdirp(OutTop,0777);
  if(err) exit(1);
  for(nthFWHM=0; nthFWHM < nFWHMList; nthFWHM++){
    for(nthThresh = 0; nthThresh < nThreshList; nthThresh++){
      for(nthSign = 0; nthSign < nSignList; nthSign++){
	if(SignList[nthSign] ==  0) signstr = "abs"; 
	if(SignList[nthSign] == +1) signstr = "pos"; 
	if(SignList[nthSign] == -1) signstr = "neg"; 
	sprintf(tmpstr,"%s/fwhm%02d/%s/th%02d",
		OutTop,(int)round(FWHMList[nthFWHM]),
		signstr,(int)round(10*ThreshList[nthThresh]));
	sprintf(fname,"%s/%s.csd",tmpstr,csdbase);
	if(fio_FileExistsReadable(fname)){
	  printf("ERROR: output file %s exists\n",fname);
	  if(fpLog) fprintf(fpLog,"ERROR: output file %s exists\n",fname);
          exit(1);
	}
	err = fio_mkdirp(tmpstr,0777);
	if(err) exit(1);
      }
    }
  }

  // Load the target surface
  sprintf(tmpstr,"%s/%s/surf/%s.%s",SUBJECTS_DIR,subject,hemi,surfname);
  printf("Loading %s\n",tmpstr);
  surf = MRISread(tmpstr);
  if(!surf) return(1);

  // Handle masking
  if(LabelFile){
    printf("Loading label file %s\n",LabelFile);
    sprintf(tmpstr,"%s/%s/label/%s.%s.label",
	    SUBJECTS_DIR,subject,hemi,LabelFile);
    if(!fio_FileExistsReadable(tmpstr)){
      printf(" Cannot find label file %s\n",tmpstr);
      sprintf(tmpstr,"%s",LabelFile);
      printf(" Trying label file %s\n",tmpstr);
      if(!fio_FileExistsReadable(tmpstr)){
	printf("  ERROR: cannot read or find label file %s\n",LabelFile);
	exit(1);
      }
    }
    printf("Loading %s\n",tmpstr);
    clabel = LabelRead(NULL, tmpstr);
    mask = MRISlabel2Mask(surf, clabel, NULL);
    FreeMask = 1;
  }
  if(MaskFile){
    printf("Loading %s\n",MaskFile);
    mask = MRIread(MaskFile);
    if(mask == NULL) exit(1);
  }
  if(mask && SaveMask){
    sprintf(tmpstr,"%s/mask.mgh",OutTop);
    printf("Saving mask to %s\n",tmpstr);
    err = MRIwrite(mask,tmpstr);
    if(err) exit(1);
  }

  // Compute search space
  searchspace = 0;
  nmask = 0;
  for(n=0; n < surf->nvertices; n++){
    if(mask && MRIgetVoxVal(mask,n,0,0,0) < 0.5) continue;
    searchspace += surf->vertices[n].area;
    nmask++;
  }
  printf("Found %d voxels in mask\n",nmask);
  if(surf->group_avg_surface_area > 0)
    searchspace *= (surf->group_avg_surface_area/surf->total_area);
  printf("search space %g mm2\n",searchspace);
  avgvtxarea = searchspace/nmask;
  printf("average vertex area %g mm2\n",avgvtxarea);

  // Determine how many iterations are needed for each FWHM
  nSmoothsList = (int *) calloc(sizeof(int),nFWHMList);
  for(nthFWHM=0; nthFWHM < nFWHMList; nthFWHM++){
    nSmoothsList[nthFWHM] = MRISfwhm2niters(FWHMList[nthFWHM], surf);
    printf("%2d %5.1f  %4d\n",nthFWHM,FWHMList[nthFWHM],nSmoothsList[nthFWHM]);
    if(fpLog) fprintf(fpLog,"%2d %5.1f  %4d\n",nthFWHM,FWHMList[nthFWHM],nSmoothsList[nthFWHM]);
  }
  printf("\n");

  // Allocate the CSDs
  for(nthFWHM=0; nthFWHM < nFWHMList; nthFWHM++){
    for(nthThresh = 0; nthThresh < nThreshList; nthThresh++){
      for(nthSign = 0; nthSign < nSignList; nthSign++){
	csd = CSDalloc();
	sprintf(csd->simtype,"%s","null-z");
	sprintf(csd->anattype,"%s","surface");
	sprintf(csd->subject,"%s",subject);
	sprintf(csd->hemi,"%s",hemi);
	sprintf(csd->contrast,"%s","NA");
	csd->seed = SynthSeed;
	csd->nreps = nRepetitions;
	csd->thresh = ThreshList[nthThresh];
	csd->threshsign = SignList[nthSign];
	csd->nullfwhm = FWHMList[nthFWHM];
	csd->varfwhm = -1;
	csd->searchspace = searchspace;
	CSDallocData(csd);
	csdList[nthFWHM][nthThresh][nthSign] = csd;
      }
    }
  }

  // Alloc the z map
  z = MRIallocSequence(surf->nvertices, 1,1, MRI_FLOAT, 1);

  // Set up the random field specification
  rfs = RFspecInit(SynthSeed,NULL);
  rfs->name = strcpyalloc("gaussian");
  rfs->params[0] = 0;
  rfs->params[1] = 1;

  printf("Thresholds (%d): ",nThreshList);
  for(n=0; n < nThreshList; n++) printf("%5.2f ",ThreshList[n]);
  printf("\n");
  printf("Signs (%d): ",nSignList);
  for(n=0; n < nSignList; n++)  printf("%2d ",SignList[n]);
  printf("\n");
  printf("FWHM (%d): ",nFWHMList);
  for(n=0; n < nFWHMList; n++) printf("%5.2f ",FWHMList[n]);
  printf("\n");

  // Start the simulation loop
  printf("\n\nStarting Simulation over %d Repetitions\n",nRepetitions);
  if(fpLog) fprintf(fpLog,"\n\nStarting Simulation over %d Repetitions\n",nRepetitions);
  TimerStart(&mytimer) ;
  for(nthRep = 0; nthRep < nRepetitions; nthRep++){
    msecTime = TimerStop(&mytimer) ;
    printf("%5d %7.1f ",nthRep,(msecTime/1000.0)/60);
    if(fpLog) {
      fprintf(fpLog,"%5d %7.1f ",nthRep,(msecTime/1000.0)/60);
      fflush(fpLog);
    }
    // Synthesize an unsmoothed z map
    RFsynth(z,rfs,mask); 
    nSmoothsPrev = 0;
    
    // Loop through FWHMs
    for(nthFWHM=0; nthFWHM < nFWHMList; nthFWHM++){
      printf("%d ",nthFWHM);
      if(fpLog) {
	fprintf(fpLog,"%d ",nthFWHM);
	fflush(fpLog);
      }
      nSmoothsDelta = nSmoothsList[nthFWHM] - nSmoothsPrev;
      nSmoothsPrev = nSmoothsList[nthFWHM];
      // Incrementally smooth z
      MRISsmoothMRI(surf, z, nSmoothsDelta, mask, z); // smooth z
      // Rescale
      RFrescale(z,rfs,mask,z);
      // Slightly tortured way to get the right p-values because
      //   RFstat2P() computes one-sided, but I handle sidedness
      //   during thresholding.
      // First, use zabs to get a two-sided pval bet 0 and 0.5
      zabs = MRIabs(z,zabs);
      p = RFstat2P(zabs,rfs,mask,0,p);
      // Next, mult pvals by 2 to get two-sided bet 0 and 1
      MRIscalarMul(p,p,2.0);
      sig = MRIlog10(p,NULL,sig,1); // sig = -log10(p)
      for(nthThresh = 0; nthThresh < nThreshList; nthThresh++){
	for(nthSign = 0; nthSign < nSignList; nthSign++){
	  csd = csdList[nthFWHM][nthThresh][nthSign];

	  // If test is not ABS then apply the sign
	  if(csd->threshsign != 0) MRIsetSign(sig,z,0);
	  // Get the max stats
	  sigmax = MRIframeMax(sig,0,mask,csd->threshsign,
			       &cmax,&rmax,&smax);
	  zmax = MRIgetVoxVal(z,cmax,rmax,smax,0);
	  if(csd->threshsign == 0){
	    zmax = fabs(zmax);
	    sigmax = fabs(sigmax);
	  }
	  // Mask
	  if(mask) MRImask(sig,mask,sig,0.0,0.0);

	  // Surface clustering
	  MRIScopyMRI(surf, sig, 0, "val");
	  if(csd->threshsign == 0) threshadj = csd->thresh;
	  else threshadj = csd->thresh - log10(2.0); // one-sided test
	  SurfClustList = sclustMapSurfClusters(surf,threshadj,-1,csd->threshsign,
						0,&nClusters,NULL);
	  // Actual area of cluster with max area
	  csize  = sclustMaxClusterArea(SurfClustList, nClusters);
	  // Number of vertices of cluster with max number of vertices. 
	  // Note: this may be a different cluster from above!
	  csizen = sclustMaxClusterCount(SurfClustList, nClusters);
	  // Area of this cluster based on average vertex area. This just scales
	  // the number of vertices.
	  csizeavg = csizen * avgvtxarea;
	  if(UseAvgVtxArea) csize = csizeavg;
	  // Store results
	  csd->nClusters[nthRep] = nClusters;
	  csd->MaxClusterSize[nthRep] = csize;
	  csd->MaxSig[nthRep] = sigmax;
	  csd->MaxStat[nthRep] = zmax;
	} // Sign
      } // Thresh
    } // FWHM
    printf("\n");
    if(fpLog) fprintf(fpLog,"\n");
    if(SaveEachIter || fio_FileExistsReadable(SaveFile)) SaveOutput();
    if(fio_FileExistsReadable(StopFile)) {
      printf("Found stop file %s\n",StopFile);
      goto finish;
    }
  } // Simulation Repetition

 finish:

  SaveOutput();

  msecTime = TimerStop(&mytimer) ;
  printf("Total Sim Time %g min (%g per rep)\n",
	 msecTime/(1000*60.0),(msecTime/(1000*60.0))/nthRep);
  if(fpLog) fprintf(fpLog,"Total Sim Time %g min (%g per rep)\n",
		    msecTime/(1000*60.0),(msecTime/(1000*60.0))/nthRep);

  if(DoneFile){
    fp = fopen(DoneFile,"w");
    fprintf(fp,"%g\n",msecTime/(1000*60.0));
    fclose(fp);
  }
  printf("mri_mcsim done\n");
  if(fpLog){
    fprintf(fpLog,"mri_mcsim done\n");
    fclose(fpLog);
  }
  exit(0);
}
コード例 #21
0
int
main(int argc, char *argv[]) {
  char         *ref_fname, *in_fname, *out_fname, fname[STRLEN], **av ;
  MRI          *mri_ref, *mri_in, *mri_orig, *mri_in_red, *mri_ref_red,
  *mri_in_tmp, *mri_ref_tmp, *mri_ref_orig, *mri_in_orig ;
  int          ac, nargs, i, msec, minutes, seconds ;
  struct timeb start ;
  MATRIX       *m_L ;

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

  parms.mri_crop = NULL ;
  parms.l_intensity = 1.0f ;
  parms.niterations = 100 ;
  parms.levels = -1 ;   /* use default */
  parms.dt = 1e-6 ;  /* was 5e-6 */
  parms.tol = INTEGRATION_TOL*5 ;

  parms.dt = 5e-6 ;  /* was 5e-6 */
  parms.tol = 1e-3 ;
  parms.momentum = 0.8 ;
  parms.max_levels = MAX_LEVELS ;
  parms.factor = 1.0 ;
  parms.niterations = 25 ;
  Progname = argv[0] ;


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

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

  if (argc < 4)
    ErrorExit(ERROR_BADPARM,
              "usage: %s <in brain> <template> <output file name>\n",
              Progname) ;

  in_fname = argv[1] ;
  ref_fname = argv[2] ;
  if (xform_mean_fname) {
    int   sno, nsubjects ;
    FILE  *fp ;

    parms.m_xform_mean = MatrixAsciiRead(xform_mean_fname, NULL) ;
    if (!parms.m_xform_mean)
      ErrorExit(Gerror, "%s: could not read parameter means from %s",
                Progname, xform_mean_fname) ;

    fp = fopen(xform_covariance_fname, "r") ;
    if (!fp)
      ErrorExit(ERROR_NOFILE, "%s: could not read covariances from %s",
                Progname, xform_covariance_fname) ;

    fscanf(fp, "nsubjects=%d", &nsubjects) ;
    printf("reading %d transforms...\n", nsubjects) ;

    parms.m_xforms = (MATRIX **)calloc(nsubjects, sizeof(MATRIX *)) ;
    if (!parms.m_xforms)
      ErrorExit(ERROR_NOMEMORY, "%s: could not allocate array of %d xforms",
                Progname, nsubjects) ;
    for (sno = 0 ; sno < nsubjects ; sno++) {
      parms.m_xforms[sno] = MatrixAsciiReadFrom(fp, NULL) ;
      if (!parms.m_xforms[sno])
        ErrorExit(ERROR_NOMEMORY, "%s: could not allocate %dth xform",
                  Progname, sno) ;

    }
    parms.m_xform_covariance = MatrixAsciiReadFrom(fp, NULL) ;
    if (!parms.m_xform_covariance)
      ErrorExit(Gerror, "%s: could not read parameter covariance from %s",
                Progname, xform_covariance_fname) ;
    fclose(fp) ;
    parms.l_priors = l_priors ;
    parms.nxforms = nsubjects ;
  }
  out_fname = argv[3] ;
  FileNameOnly(out_fname, fname) ;
  FileNameRemoveExtension(fname, fname) ;
  strcpy(parms.base_name, fname) ;
  fprintf(stderr, "logging results to %s.log\n", parms.base_name) ;

  TimerStart(&start) ;
  fprintf(stderr, "reading '%s'...\n", ref_fname) ;
  fflush(stderr) ;
  mri_ref = MRIread(ref_fname) ;
  if (!mri_ref)
    ErrorExit(ERROR_NOFILE, "%s: could not open reference volume %s.\n",
              Progname, ref_fname) ;
  if (mri_ref->type != MRI_UCHAR) {
    MRI *mri_tmp ;

    mri_tmp = MRIchangeType(mri_ref, MRI_UCHAR, 0.0, 0.999, FALSE) ;
    MRIfree(&mri_ref) ;
    mri_ref = mri_tmp ;
  }

  if (var_fname)  /* read in a volume of standard deviations */
  {
    MRI *mri_var, *mri_tmp ;

    fprintf(stderr, "reading '%s'...\n", var_fname) ;
    mri_var = MRIread(var_fname) ;
    if (!mri_var)
      ErrorExit(ERROR_NOFILE, "%s: could not open variance volume %s.\n",
                Progname, var_fname) ;
    mri_tmp = MRIconcatenateFrames(mri_ref, mri_var, NULL) ;
    MRIfree(&mri_var) ;
    MRIfree(&mri_ref) ;
    mri_ref = mri_tmp ;
  }
  fprintf(stderr, "reading '%s'...\n", in_fname) ;
  fflush(stderr) ;
  mri_orig = mri_in = MRIread(in_fname) ;
  if (!mri_in)
    ErrorExit(ERROR_NOFILE, "%s: could not open input volume %s.\n",
              Progname, in_fname) ;
  if (mri_in->type != MRI_UCHAR) {
    MRI *mri_tmp ;

    mri_orig = mri_tmp = MRIchangeType(mri_in, MRI_UCHAR, 0.0, 0.999, FALSE) ;
    MRIfree(&mri_in) ;
    mri_in = mri_tmp ;
  }

  /* make sure they are the same size */
  if (mri_in->width  != mri_ref->width ||
      mri_in->height != mri_ref->height  ||
      mri_in->depth  != mri_ref->depth) {
    int  width, height, depth ;
    MRI  *mri_tmp ;

    width = MAX(mri_in->width, mri_ref->width) ;
    height = MAX(mri_in->height, mri_ref->height) ;
    depth = MAX(mri_in->depth, mri_ref->depth) ;
    mri_tmp = MRIalloc(width, height, depth, MRI_UCHAR) ;
    MRIextractInto(mri_in, mri_tmp, 0, 0, 0,
                   mri_in->width, mri_in->height, mri_in->depth, 0, 0, 0) ;
#if 0
    MRIfree(&mri_in) ;
#else
    parms.mri_in = mri_in ;
#endif
    mri_in = mri_orig = mri_tmp ;

    mri_tmp = MRIallocSequence(width, height,depth,MRI_UCHAR,mri_ref->nframes);
    MRIextractInto(mri_ref, mri_tmp, 0, 0, 0,
                   mri_ref->width, mri_ref->height, mri_ref->depth, 0, 0, 0) ;
#if 0
    MRIfree(&mri_ref) ;
#else
    parms.mri_in = mri_in ;
#endif
    mri_ref = mri_tmp ;
  }


  if (!FZERO(tx) || !FZERO(ty) || !FZERO(tz)) {
    MRI *mri_tmp ;

    fprintf(stderr, "translating second volume by (%2.1f, %2.1f, %2.1f)\n",
            tx, ty, tz) ;
    mri_tmp = MRItranslate(mri_in, NULL, tx, ty, tz) ;
    MRIfree(&mri_in) ;
    mri_in = mri_tmp ;
  }

  if (!FZERO(rzrot)) {
    MRI *mri_tmp ;

    fprintf(stderr,
            "rotating second volume by %2.1f degrees around Z axis\n",
            (float)DEGREES(rzrot)) ;
    mri_tmp = MRIrotateZ_I(mri_in, NULL, rzrot) ;
    MRIfree(&mri_in) ;
    mri_in = mri_tmp ;
  }
  if (!FZERO(rxrot)) {
    MRI *mri_tmp ;

    fprintf(stderr,
            "rotating second volume by %2.1f degrees around X axis\n",
            (float)DEGREES(rxrot)) ;
    mri_tmp = MRIrotateX_I(mri_in, NULL, rxrot) ;
    MRIfree(&mri_in) ;
    mri_in = mri_tmp ;
  }
  if (!FZERO(ryrot)) {
    MRI *mri_tmp ;

    fprintf(stderr,
            "rotating second volume by %2.1f degrees around Y axis\n",
            (float)DEGREES(ryrot)) ;
    mri_tmp = MRIrotateY_I(mri_in, NULL, ryrot) ;
    MRIfree(&mri_in) ;
    mri_in = mri_tmp ;
  }

  if (!transform_loaded)   /* wasn't preloaded */
    parms.lta = LTAalloc(1, mri_in) ;

  if (!FZERO(blur_sigma)) {
    MRI *mri_kernel, *mri_tmp ;

    mri_kernel = MRIgaussian1d(blur_sigma, 100) ;
    mri_tmp = MRIconvolveGaussian(mri_in, NULL, mri_kernel) ;
    mri_in = mri_tmp ;
    MRIfree(&mri_kernel) ;
  }
  MRIscaleMeanIntensities(mri_in, mri_ref, mri_in);

  mri_ref_orig = mri_ref ;
  mri_in_orig = mri_in ;
  if (nreductions > 0) {
    mri_in_red = mri_in_tmp = MRIcopy(mri_in, NULL) ;
    mri_ref_red = mri_ref_tmp = MRIcopy(mri_ref, NULL) ;
    for (i = 0 ; i < nreductions ; i++) {
      mri_in_red = MRIreduceByte(mri_in_tmp, NULL) ;
      mri_ref_red = MRIreduceMeanAndStdByte(mri_ref_tmp,NULL);
      MRIfree(&mri_in_tmp);
      MRIfree(&mri_ref_tmp) ;
      mri_in_tmp = mri_in_red ;
      mri_ref_tmp = mri_ref_red ;
    }
    mri_in = mri_in_red ;
    mri_ref = mri_ref_red ;
  }
  /* for diagnostics */
  if (full_res) {
    parms.mri_ref = mri_ref ;
    parms.mri_in = mri_in ;
  } else {
    parms.mri_ref = mri_ref_orig ;
    parms.mri_in = mri_in_orig ;
  }

  m_L = initialize_transform(mri_in, mri_ref, &parms) ;

  if (use_gradient) {
    MRI  *mri_in_mag, *mri_ref_mag, *mri_grad, *mri_mag ;

    printf("computing gradient magnitude of input image...\n") ;
    mri_mag = MRIalloc(mri_in->width, mri_in->height, mri_in->depth,MRI_FLOAT);
    MRIcopyHeader(mri_in, mri_mag) ;
    mri_grad = MRIsobel(mri_in, NULL, mri_mag) ;
    MRIfree(&mri_grad) ;

    /* convert it to ubytes */
    MRIvalScale(mri_mag, mri_mag, 0.0f, 255.0f) ;
    mri_in_mag = MRIclone(mri_in, NULL) ;
    MRIcopy(mri_mag, mri_in_mag) ;
    MRIfree(&mri_mag) ;

    /* now compute gradient of ref image */
    printf("computing gradient magnitude of reference image...\n") ;
    mri_mag = MRIalloc(mri_ref->width, mri_ref->height, mri_ref->depth,MRI_FLOAT);
    MRIcopyHeader(mri_ref, mri_mag) ;
    mri_grad = MRIsobel(mri_ref, NULL, mri_mag) ;
    MRIfree(&mri_grad) ;

    /* convert it to ubytes */
    MRIvalScale(mri_mag, mri_mag, 0.0f, 255.0f) ;
    mri_ref_mag = MRIclone(mri_ref, NULL) ;
    MRIcopy(mri_mag, mri_ref_mag) ;
    MRIfree(&mri_mag) ;

    register_mri(mri_in_mag, mri_ref_mag, &parms, m_L) ;
    MRIfree(&mri_in_mag) ;
    MRIfree(&mri_ref_mag) ;
  }
  register_mri(mri_in, mri_ref, &parms, m_L) ;
  if (check_crop_flag)  /* not working yet! */
  {
    printf("searching for cropped regions in the input image...\n") ;
    parms.mri_crop = find_cropping(mri_orig, mri_ref, &parms) ;
    MRIwrite(parms.mri_crop, "crop.mgh") ;
    register_mri(mri_in, mri_ref, &parms, m_L) ;
  }

  if (voxel_coords) {
    printf("transforming xform to voxel coordinates...\n") ;
    MRIrasXformToVoxelXform(mri_in_orig, mri_ref_orig,
                            parms.lta->xforms[0].m_L,
                            parms.lta->xforms[0].m_L);
    if (Gdiag & DIAG_WRITE) {
      MRI *mri_tmp ;

      mri_tmp = MRIlinearTransform(mri_in_orig, NULL,parms.lta->xforms[0].m_L);
      MRIwriteImageViews(mri_tmp, "morphed", IMAGE_SIZE) ;
      MRIfree(&mri_tmp) ;
    }
  }
  // save src and target info in lta
  getVolGeom(mri_in_orig, &parms.lta->xforms[0].src);
  getVolGeom(mri_ref_orig, &parms.lta->xforms[0].dst);
  fprintf(stderr, "writing output transformation to %s...\n", out_fname) ;
  if (invert_flag) {
    MATRIX *m_tmp ;

    m_tmp = MatrixInverse(parms.lta->xforms[0].m_L, NULL) ;
    MatrixFree(&parms.lta->xforms[0].m_L) ;
    // change src and dst
    getVolGeom(mri_in_orig, &parms.lta->xforms[0].dst);
    getVolGeom(mri_ref_orig, &parms.lta->xforms[0].src);
    parms.lta->xforms[0].m_L = m_tmp ;
  }
  //
  LTAwriteEx(parms.lta, out_fname) ;
  //
  if (mri_ref)
    MRIfree(&mri_ref) ;
  if (mri_in)
    MRIfree(&mri_in) ;
  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  fprintf(stderr, "registration took %d minutes and %d seconds.\n",
          minutes, seconds) ;
  exit(0) ;
  return(0) ;
}