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(); } }
// ------------------------------------------------------------------------ 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; } }
int main (int argc, char **argv) { int verbose=0, clobber=0,skip_grid=0; int order=2; std::string like_f,xfm_f,output_f,input_f; double uniformize=0.0; int invert=0; char *history = time_stamp(argc, argv); static struct option long_options[] = { {"verbose", no_argument, &verbose, 1}, {"quiet", no_argument, &verbose, 0}, {"clobber", no_argument, &clobber, 1}, {"like", required_argument, 0, 'l'}, {"transform", required_argument, 0, 't'}, {"order", required_argument, 0, 'o'}, {"uniformize", required_argument, 0, 'u'}, {"invert_transform", no_argument, &invert, 1}, {0, 0, 0, 0} }; for (;;) { /* getopt_long stores the option index here. */ int option_index = 0; int c = getopt_long (argc, argv, "vqcl:t:o:u:", long_options, &option_index); /* Detect the end of the options. */ if (c == -1) break; switch (c) { case 0: break; case 'v': cout << "Version: 0.1" << endl; return 0; case 'l': like_f=optarg; break; case 't': xfm_f=optarg; break; case 'o': order=atoi(optarg);break; case 'u': uniformize=atof(optarg);break; case '?': /* getopt_long already printed an error message. */ default: show_usage (argv[0]); return 1; } } if ((argc - optind) < 2) { show_usage(argv[0]); return 1; } input_f=argv[optind]; output_f=argv[optind+1]; if (!clobber && !access (output_f.c_str (), F_OK)) { std::cerr << output_f.c_str () << " Exists!" << std::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(input_f.c_str()); reader->Update(); minc::image3d::Pointer in=reader->GetOutput(); FilterType::Pointer filter = FilterType::New(); //creating coordinate transformation objects TransformType::Pointer transform = TransformType::New(); if(!xfm_f.empty()) { //reading a minc style xfm file transform->OpenXfm(xfm_f.c_str()); if(!invert) transform->Invert(); //should be inverted by default to walk through target space filter->SetTransform( transform ); } //creating the interpolator InterpolatorType::Pointer interpolator = InterpolatorType::New(); interpolator->SetSplineOrder(order); filter->SetInterpolator( interpolator ); filter->SetDefaultPixelValue( 0 ); //this is for processing using batch system filter->SetNumberOfThreads(1); if(!like_f.empty()) { itk::ImageFileReader<minc::image3d >::Pointer reader = itk::ImageFileReader<minc::image3d >::New(); reader->SetFileName(like_f.c_str()); reader->Update(); if(uniformize!=0.0) { generate_uniform_sampling(filter,reader->GetOutput(),uniformize); } else { filter->SetOutputParametersFromImage(reader->GetOutput()); filter->SetOutputDirection(reader->GetOutput()->GetDirection()); } } else { if(uniformize!=0.0) { generate_uniform_sampling(filter,in,uniformize); } else { //we are using original sampling filter->SetOutputParametersFromImage(in); filter->SetOutputDirection(in->GetDirection()); } } filter->SetInput(in); filter->Update(); //copy the metadate information, for some reason it is not preserved //filter->GetOutput()->SetMetaDataDictionary(reader->GetOutput()->GetMetaDataDictionary()); minc::image3d::Pointer out=filter->GetOutput(); minc::copy_metadata(out,in); minc::append_history(out,history); free(history); //generic file writer itk::ImageFileWriter< minc::image3d >::Pointer writer = itk::ImageFileWriter<minc::image3d >::New(); writer->SetFileName(output_f.c_str()); writer->SetInput( out ); //writer->UseInputMetaDataDictionaryOn(); writer->Update(); return 0; } catch (const minc::generic_error & err) { cerr << "Got an error at:" << err.file () << ":" << err.line () << endl; return 1; } catch( itk::ExceptionObject & err ) { std::cerr << "ExceptionObject caught !" << std::endl; std::cerr << err << std::endl; return 2; } return 0; };
int main( int argc, char *argv[] ) { string input_name; string output_dir; if (argc == 3) { input_name = argv[1]; output_dir = argv[2]; } const unsigned int Dimension = 3; const unsigned int OutDimension = 2; typedef short InputPixelType; typedef int FilterPixelType; typedef itk::Image< InputPixelType, Dimension > InputImageType; typedef itk::Image< FilterPixelType, Dimension > FilterImageType; typedef itk::Image< FilterPixelType, OutDimension > OutFilterImageType; InputImageType::Pointer image; itk::MetaDataDictionary dict; if (input_name.size() && output_dir.size()) { if (boost::filesystem::is_regular_file( input_name )) { typedef itk::ImageFileReader< InputImageType > ReaderType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( input_name ); try { reader->Update(); } catch( itk::ExceptionObject & err ) { std::cerr << "ERROR: ExceptionObject caught !" << std::endl; std::cerr << err << std::endl; return EXIT_FAILURE; } image = reader->GetOutput(); dict = reader->GetMetaDataDictionary(); } else if (boost::filesystem::is_directory( input_name )) { itkBasic::SeriesReader sreader( input_name ); sreader.readSeriesData( 2 ); try { itkBasic::ReaderType::Pointer imageReader = itkBasic::ReaderType::New(); itkBasic::FileNamesContainer fc; sreader.getSeriesFileNames(0, fc); image = itkBasic::getDicomSerie( fc, imageReader, 1 ); dict = *((*imageReader->GetMetaDataDictionaryArray())[0]); } catch( itk::ExceptionObject & err ) { std::cerr << "ERROR: ExceptionObject caught !" << std::endl; std::cerr << err << std::endl; return EXIT_FAILURE; } } } if (!image) { std::cerr << argv[0] << ": input output" << std::endl; exit(1); } typedef itk::SigmoidImageFilter< InputImageType, FilterImageType > SigmoidCasterType; SigmoidCasterType::Pointer sigmoidcaster = SigmoidCasterType::New(); sigmoidcaster->SetInput( image ); sigmoidcaster->SetOutputMaximum( 4000 ); sigmoidcaster->SetOutputMinimum( 1000 ); typedef itk::AccumulateImageFilter< FilterImageType, FilterImageType > AccumulateFilter; AccumulateFilter::Pointer accumulator = AccumulateFilter::New(); accumulator->SetAccumulateDimension(1); accumulator->SetInput( sigmoidcaster->GetOutput() ); typedef itk::ExtractImageFilter< FilterImageType, OutFilterImageType > ExtractFilter; ExtractFilter::Pointer extractor = ExtractFilter::New(); extractor->SetInput( accumulator->GetOutput() ); FilterImageType::Pointer accuOut = accumulator->GetOutput(); accuOut->UpdateOutputInformation(); FilterImageType::RegionType extractRegion = accuOut->GetLargestPossibleRegion(); extractRegion.SetSize(1,0); extractor->SetExtractionRegion( extractRegion ); typedef itk::ResampleImageFilter<OutFilterImageType, OutFilterImageType > ResampleFilter; ResampleFilter::Pointer resampler = ResampleFilter::New(); resampler->SetInput( extractor->GetOutput() ); typedef itk::BSplineInterpolateImageFunction< OutFilterImageType > InterpolatorType; InterpolatorType::Pointer interpolator = InterpolatorType::New(); interpolator->SetSplineOrder(3); resampler->SetInterpolator( interpolator ); OutFilterImageType::Pointer exOut = extractor->GetOutput(); exOut->UpdateOutputInformation(); typedef itk::CenteredRigid2DTransform< double > TransformType; TransformType::Pointer transform = TransformType::New(); transform->SetIdentity(); OutFilterImageType::PointType exOutCenter = exOut->GetOrigin(); exOutCenter[0] += (exOut->GetLargestPossibleRegion().GetSize()[0]-1) * exOut->GetSpacing()[0] *.5; exOutCenter[1] += (exOut->GetLargestPossibleRegion().GetSize()[1]-1) * exOut->GetSpacing()[1] *.5; transform->SetCenter( exOutCenter ); transform->SetAngleInDegrees( 180 ); resampler->SetTransform( transform ); resampler->SetOutputParametersFromImage( exOut ); OutFilterImageType::SpacingType resampleSpacing = exOut->GetSpacing(); resampleSpacing.Fill( std::min( resampleSpacing[0], resampleSpacing[1] ) ); OutFilterImageType::SizeType resampleSize; resampleSize[0] = exOut->GetLargestPossibleRegion().GetSize()[0] * exOut->GetSpacing()[0] / resampleSpacing[0]; resampleSize[1] = exOut->GetLargestPossibleRegion().GetSize()[1] * exOut->GetSpacing()[1] / resampleSpacing[1]; resampler->SetSize( resampleSize ); resampler->SetOutputSpacing( resampleSpacing ); OutFilterImageType::Pointer result = resampler->GetOutput(); sigmoidcaster->SetBeta( -500 ); sigmoidcaster->SetAlpha( 5 ); result->Update(); int outDicomIndex = 0; itk::EncapsulateMetaData( dict, "0008|0008", string("DERIVED\\SECONDARY\\AXIAL")); boost::filesystem::path outpath = output_dir; outpath = outpath / "IM%06d"; std::vector< itk::MetaDataDictionary* > dictArray; dictArray.push_back(&dict); itkBasic::writeDicomSeries( itkBasic::ImageRescale(itkBasic::ImageSharp(result, 0.5), -1000, 4000), outpath.string(), &dictArray, outDicomIndex); // itkBasic::ImageSave( itkBasic::ImageSharp(result, 0.5), boost::str( boost::format("%s.%s.png") % output_name % "lung" ), 1, 0); // Auto Level sigmoidcaster->SetBeta( 1000 ); sigmoidcaster->SetAlpha( 300 ); result->Update(); itkBasic::writeDicomSeries( itkBasic::ImageRescale(itkBasic::ImageSharp(result, 0.5), -1000, 4000), outpath.string(), &dictArray, outDicomIndex); // itkBasic::ImageSave( itkBasic::ImageSharp(result, 0.5), boost::str( boost::format("%s.%s.png") % output_name % "bone" ), 1, 0); // Auto Level sigmoidcaster->SetBeta( 0 ); sigmoidcaster->SetAlpha( 2000 ); result->Update(); itkBasic::writeDicomSeries( itkBasic::ImageRescale(itkBasic::ImageSharp(result, 0.5), -1000, 4000), outpath.string(), &dictArray, outDicomIndex); // itkBasic::ImageSave( itkBasic::ImageSharp(result, 0.5), boost::str( boost::format("%s.%s.png") % output_name % "normal" ), 1, 0); // Auto Level }
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; }