Пример #1
0
 void PlutoCore::initialize() {
     const int radius = 3;
     const int size = 7;
     
     RealImage2::RegionType region;
     region.SetIndex(0, -radius);
     region.SetIndex(1, -radius);
     region.SetSize(0, size);
     region.SetSize(1, size);
     
     _particles.resize(_images.size());
     for (int i = 0; i < _images.size(); i++) {
         // set up each particle per image
         _particles[i] = _initialParticles;
         
         // interpolator creation
         typedef itk::LinearInterpolateImageFunction<RealImage2> InterpolatorType;
         InterpolatorType::Pointer interp = InterpolatorType::New();
         interp->SetInputImage(_images[i]);
         
         Gradient2InterpolatorType::Pointer gradientInterp = Gradient2InterpolatorType::New();
         gradientInterp->SetInputImage(_gradientImages[i]);
         
         // sampler initialization
         RealSamples2& samples = _samples[i];
         samples.setSampleRegion(region);
         samples.addInterpolator(interp);
         samples.addGradientInterpolator(gradientInterp);
         samples.addParticles(&_particles[i][0], _particles[i].size());
         samples.allocateValues();
         samples.allocateGradients();
         samples.sampleValues();
         samples.sampleGradients();
     }
 }
Пример #2
0
// ------------------------------------------------------------------------
void createLabelImage(const SeriesTransform &series,
	   const ImageType::Pointer &reference,
	   const LevelSetType::Pointer &levelSet,
	   const std::vector<int> &roiOffset,
	   ImageType::Pointer &label,
	   unsigned int instance)
{
	// initialise the label image
	createOutput(series.images[instance], label);


	// create the level set interpolator
	typedef itk::LinearInterpolateImageFunction<LevelSetType> InterpolatorType;
	InterpolatorType::Pointer interpolator = InterpolatorType::New();
	interpolator->SetInputImage(levelSet);


	// iterate through the output 
	itk::ImageRegionIterator<ImageType> it(label, label->GetLargestPossibleRegion());
	it.GoToBegin();

	while(!it.IsAtEnd())
	{
		ImageType::IndexType index = it.GetIndex();
		ImageType::PointType p1, p2;

		// get the point in the level set space
		label->TransformIndexToPhysicalPoint(index, p1);
		transformPointToPatient(reference, series, roiOffset, p1, p2);

		// interpolate the level set value
		if(interpolator->IsInsideBuffer(p2))
		{
			float val = interpolator->Evaluate(p2);
			if(val >= 0) it.Set(1);
		}

		++it;
	}
}
Пример #3
0
int main (int argc, char **argv)
{
  int verbose=0,clobber=0;
  int order=2;
  
  static struct option long_options[] = {
    {"verbose", no_argument,       &verbose, 1},
    {"quiet",   no_argument,       &verbose, 0},
    {"clobber", no_argument,       &clobber, 1},
    {"order", required_argument,       0, 'o'},
    {0, 0, 0, 0}
  };
  
  for (;;) {
    /* getopt_long stores the option index here. */
    int option_index = 0;

    int c = getopt_long (argc, argv, "vo:", long_options, &option_index);

    /* Detect the end of the options. */
    if (c == -1) break;

    switch (c)
    {
      case 0:
        break;
      case 'o':
        order=atoi(optarg);break;
      case 'v':
        cout << "Version: 0.1" << endl;
        return 0;
      case '?':
        /* getopt_long already printed an error message. */
      default:
        show_usage (argv[0]);
        return 1;
    }
  }

  if((argc - optind) < 3) {
    show_usage (argv[0]);
    return 1;
  }
  std::string in_volume=argv[optind];
  std::string in_obj=argv[optind+1];
  std::string out_csv=argv[optind+2];
  
  
  if (!clobber && !access(out_csv.c_str(), F_OK))
  {
    cerr << out_csv.c_str() << " Exists!" << endl;
    return 1;
  }
  
  try
  {
    
    itk::ObjectFactoryBase::RegisterFactory(itk::MincImageIOFactory::New());
    itk::ImageFileReader<minc::image3d >::Pointer reader = itk::ImageFileReader<minc::image3d >::New();
    
    //initializing the reader
    reader->SetFileName(in_volume.c_str());
    reader->Update();
    
    minc::image3d::Pointer in=reader->GetOutput();
    
    std::cout<<"Building BSpline interpolator , order="<<order<<std::endl;
    InterpolatorType::Pointer interpolator = InterpolatorType::New();
    interpolator->SetSplineOrder(order);
    interpolator->SetInputImage(in);
    
    std::ofstream output(out_csv.c_str());
    
    VIO_File_formats         format;
    object_struct        **object_list;
    int n_objects=0;
    
    //bicpl sucks!
    if( input_graphics_file( (char*)in_obj.c_str(), &format, &n_objects,
        &object_list ) != VIO_OK )
    {
      std::cerr << " Error reading "<<in_obj.c_str() << std::endl;
      return 1;
    }
    
    //const int segment_length=10;
    
    std::vector<minc::tag_point> lines;
    std::vector<int> line_index;
    std::cout<<"Processing "<<n_objects<<" objects"<<std::endl;
    output<<"x,y,z,v"<<std::endl;
    for(int i=0;i< n_objects;i++ )
    {
      if( get_object_type( object_list[i] ) == POLYGONS )
      {
        polygons_struct      *polygons;
        polygons = get_polygons_ptr(object_list[i]);
        
        /*object_struct * lobj= create_object( LINES );
        lines_struct * lines = get_lines_ptr(lobj);
        
        initialize_lines( lines, WHITE );
        lines->n_points = polygons->n_items*segment_length;
        ALLOC( lines->points, lines->n_points );*/
        
        for(int pnt=0;pnt< polygons->n_points;pnt++ )
        {
          VIO_Point p_=polygons->points[pnt];//seeding point 
          minc::tag_point p_orig,p;
          p_orig[0]=p_.coords[0];p_orig[1]=p_.coords[1];p_orig[2]=p_.coords[2];
          //line_index.push_back(lines.size());
          //lines.push_back(p_orig);
          p=p_orig;
          
          double _in=interpolator->Evaluate(p);
          
/*          polygons->points[pnt].coords[0]=p[0];
          polygons->points[pnt].coords[1]=p[1];
          polygons->points[pnt].coords[2]=p[2];*/
          //int size = GET_OBJECT_SIZE( *polygons, poly );
          //if(size<3) continue; //?
          
/*          p1=polygons->points[POINT_INDEX( polygons->end_indices, poly, 0 )];
          p2=polygons->points[POINT_INDEX( polygons->end_indices, poly, 1 )];
          p3=polygons->points[POINT_INDEX( polygons->end_indices, poly, 2 )];*/
          /*
          std::cout<<poly<<"\t"<<POINT_INDEX( polygons->end_indices, poly, 0 )<<" "
              <<POINT_INDEX( polygons->end_indices, poly, 1 )<<" "
              <<POINT_INDEX( polygons->end_indices, poly, 2 )<<std::endl;*/
          //std::cout<<poly<<"\t"<<p1.coords[0]<<" "<<p1.coords[1]<<" "<<p1.coords[2]<<std::endl;
          //center
          output<<p[0]<<","<<p[1]<<","<<p[2]<<","<<
                _in<<std::endl;
        }
      }
    } 
    //int status = output_graphics_file( (char*)out_objf.c_str(), format,n_objects, object_list );
    //free up memory
    delete_object_list( n_objects, object_list );
    //return( status != OK );
    /*
    //outputting lines
    FILE *fp=fopen(out_objf.c_str(),"w");

  // IL want to write in binary

    fprintf(fp,"L 0.1 %d\n",lines.size());

  //WRITING cordinates

    for (int i=0;i<lines.size();i++) {
      fprintf(fp,"%f %f %f\n",lines[i][0],lines[i][1],lines[i][2]);
    }

    fprintf(fp,"%d\n1 ",line_index.size()); //1 color per line

    for (int i=0;i<line_index.size();i++) { //random colors
      fprintf(fp,"%f %f %f 1.0\n",rand()/(double)RAND_MAX,rand()/(double)RAND_MAX,rand()/(double)RAND_MAX);
    }

    for (int i=0;i<line_index.size();i++) {
      
      if(i<(line_index.size()-1))
        fprintf(fp,"%d ",line_index[i+1]);
      else
        fprintf(fp,"%d ",lines.size());//last line lasts untill the end
    }

    fprintf(fp,"\n");

    for (int i=0;i<line_index.size();i++) 
    {
      int end=i<(line_index.size()-1)?line_index[i+1]:lines.size();
      for(int j=line_index[i];j<end;j++)
        fprintf(fp," %d",j);
      
      fprintf(fp,"\n");
    }
    fclose(fp);*/
    
  } catch (const minc::generic_error & err) {
    cerr << "Got an error at:" << err.file () << ":" << err.line () << endl;
    return 1;
  }
  return 0;
};
//calculate segmentation values
bool CTImageTreeItem::internalGetSegmentationValues( SegmentationValues &values) const {
	
	//get ITK image
	ImageType::Pointer image = getITKImage();
	if (image.IsNull()) 
		return false;

	//get buffered region of the image
	ImageType::RegionType ctregion = image->GetBufferedRegion();
	//define an iterator for the binary segment
	typedef itk::ImageRegionConstIteratorWithIndex< BinaryImageType > BinaryIteratorType;
	//get binary segment
	BinaryImageTreeItem::ImageType::Pointer segment = values.m_segment->getITKImage();
	if (segment.IsNull()) 
		return false;

/*	typedef itk::ImageFileWriter< ImageType >  WriterType;
	WriterType::Pointer writer = WriterType::New();
	writer->SetFileName( "test.dcm" );

	writer->SetInput( image );
		try 
		{
			writer->Update();
		}
		catch( itk::ExceptionObject & excep )
		{
			std::cerr << "Exception catched !" << std::endl;
			std::cerr << excep << std::endl;
		}
*/
	//create a binary iterator for the segment and its buffered region
	BinaryIteratorType binIter( segment, segment->GetBufferedRegion() );
	ImageType::PointType point;
  
	//The Accumulators Framework is framework for performing incremental calculations
	using namespace boost::accumulators;
	//http://boost-sandbox.sourceforge.net/libs/accumulators/doc/html/accumulators/user_s_guide.html#accumulators.user_s_guide.the_accumulators_framework
	accumulator_set<double,features<tag::count, tag::min, tag::mean, tag::max, tag::variance> > acc;  
  
	//check selected accuracy
	if (values.m_accuracy == SegmentationValues::SimpleAccuracy) {
		ImageType::IndexType index;
		//iterate over the pixel of the binary segment
		for(binIter.GoToBegin(); !binIter.IsAtEnd(); ++binIter) {
			//if actual value = 255
			if (binIter.Value() == BinaryPixelOn) {
				//transforms the index to a physical point in the binary segment
				segment->TransformIndexToPhysicalPoint(binIter.GetIndex(),point);
				//transform that point to an index of the CT image
				image->TransformPhysicalPointToIndex(point, index);
				//check if that index is inside the CT region
				if (ctregion.IsInside(index)) {
					//get the pixel value at the index
					int t = image->GetPixel(index);
					//check if pixel value != -2048
					if (isRealHUvalue(t)) {
						//accumulate pixel value
						acc( t );
					}
				}
			}
		}
	//check selected accuracy
	} else if (values.m_accuracy == SegmentationValues::PreventDoubleSamplingAccuracy) {
		ImageType::IndexType index;
		//definition for a set of indices, which can be compared
		typedef std::set< ImageType::IndexType, IndexCompareFunctor > IndexSetType;
		IndexSetType indexSet;
		//iterate over the pixel of the binary segment
		for(binIter.GoToBegin(); !binIter.IsAtEnd(); ++binIter) {
			//if actual value = 255
			if (binIter.Value() == BinaryPixelOn) {
				//transforms the index to a physical point in the binary segment
				segment->TransformIndexToPhysicalPoint(binIter.GetIndex(),point);
				//transform that point to an index of the CT image
				image->TransformPhysicalPointToIndex(point, index);
				//check if that index is inside the CT region
				if (ctregion.IsInside(index)) {

					std::pair<IndexSetType::iterator,IndexSetType::iterator> ret;
					//
					ret = indexSet.equal_range(index);
					//If x does not match any key in the container, the range returned has a length of zero, 
					//with both iterators pointing to the nearest value greater than x, if any, 
					//or to set::end if x is greater than all the elements in the container.
					if (ret.first == ret.second) {
						indexSet.insert(ret.first, index);
						//get the pixel value at the index
						int t = image->GetPixel(index);
						//check if pixel value != -2048
						if (isRealHUvalue(t)) {
							//accumulate pixel value
							acc( t );
						}
					}
				}
			}
		}
	//check selected accuracy
	} else if (values.m_accuracy == SegmentationValues::InterpolatedAccuracy) {
		//define an interpolate function
		typedef  itk::LinearInterpolateImageFunction< CTImageType > InterpolatorType;
		InterpolatorType::Pointer interpolator = InterpolatorType::New();
		//set input to the interpolator
		interpolator->SetInputImage( image );
		InterpolatorType::ContinuousIndexType index;
		//iterate over the pixel of the binary segment
		for(binIter.GoToBegin(); !binIter.IsAtEnd(); ++binIter) {
			//if actual value = 255
			if (binIter.Value() == BinaryPixelOn) {
				//transforms the index to a physical point in the binary segment
				segment->TransformIndexToPhysicalPoint(binIter.GetIndex(),point);
				//transform that point to an index of the CT image
				image->TransformPhysicalPointToContinuousIndex(point, index);
				//check if the index is inside the buffer of the interpolator
				if (interpolator->IsInsideBuffer(index)) {
					//Returns the linearly interpolated image intensity
					int t = interpolator->EvaluateAtContinuousIndex(index);
					//check if pixel value != -2048
					if (isRealHUvalue(t)) {
						//accumulate pixel value
						acc( t );
					}
				}
			}
		}  
	}
	//set sample count, min, mean, max and standard deviation
	//from the accumulated intensities
	values.m_sampleCount = count( acc );
	values.m_min = min( acc );
	values.m_mean = mean( acc );
	values.m_max = max( acc );
	values.m_stddev = std::sqrt( variance( acc ) );
	//set the image modification time
	values.m_mtime = segment->GetMTime();
	const_cast<CTImageTreeItem*>(this)->m_segmentationValueCache[ values.m_segment ] = values;
	return values.m_sampleCount > 0;
}