Exemplo n.º 1
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
}
Exemplo n.º 2
0
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;
};
Exemplo n.º 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;
};