Ejemplo n.º 1
0
// ------------------------------------------------------------------------
void OpenCVValve::ConvertImage(const ImageType::Pointer &input, MatPtr &mat)
{
	// cast the image to uchar 
	typedef itk::Image<unsigned char, 2> OutputImageType;
	typedef itk::RescaleIntensityImageFilter<ImageType, OutputImageType> CasterType;
	CasterType::Pointer caster = CasterType::New();
	caster->SetOutputMaximum(255);
	caster->SetOutputMinimum(0);
	caster->SetInput(input);
	caster->Update();


	OutputImageType::Pointer output = caster->GetOutput();


	typedef itk::ImageFileWriter<OutputImageType> WriterType;
	WriterType::Pointer writer = WriterType::New();
	writer->SetImageIO(itk::PNGImageIO::New());
	writer->SetInput(output);
	writer->SetFileName("test.png");
	writer->Update();



	ImageType::SizeType size = input->GetLargestPossibleRegion().GetSize();
	unsigned int rows = size[1];
	unsigned int cols = size[0];

	mat = new MatType(rows,cols, CV_8UC1);


	itk::ImageRegionConstIterator<OutputImageType> it(output, output->GetLargestPossibleRegion());
	it.GoToBegin();
	while(!it.IsAtEnd())
	{
		OutputImageType::IndexType index = it.GetIndex();
		unsigned char val = it.Get();
		mat->at<unsigned char>(cv::Point(index[0], index[1])) = val;
		++it;
	}
}
void itk::ConnectomicsNetworkToConnectivityMatrixImageFilter::GenerateData()
{

  this->AllocateOutputs();

  OutputImageType::Pointer output = this->GetOutput();

  if(m_InputNetwork.IsNull())
  {
    MITK_ERROR << "Failed to generate data, no valid network was set.";
    return;
  }

  typedef mitk::ConnectomicsNetwork::NetworkType NetworkType;
  typedef boost::graph_traits< NetworkType >::vertex_descriptor DescriptorType;
  typedef boost::graph_traits< NetworkType >::vertex_iterator IteratorType;

  // prepare connectivity matrix for data
  std::vector< std::vector< int > > connectivityMatrix;
  int numberOfVertices = m_InputNetwork->GetNumberOfVertices();

  connectivityMatrix.resize( numberOfVertices );
  for( int index(0); index < numberOfVertices; index++ )
  {
    connectivityMatrix[ index ].resize( numberOfVertices );
  }

  // Create LabelToIndex translation
  std::map< std::string, DescriptorType > labelToIndexMap;

  NetworkType boostGraph = *(m_InputNetwork->GetBoostGraph());

  // translate index to label
  IteratorType iterator, end;
  boost::tie(iterator, end) = boost::vertices( boostGraph );

  for ( ; iterator != end; ++iterator)
  {
    labelToIndexMap.insert(
      std::pair< std::string, DescriptorType >(
      boostGraph[ *iterator ].label, *iterator )
      );
  }

  std::vector< std::string > indexToLabel;

  // translate index to label
  indexToLabel.resize( numberOfVertices );

  boost::tie(iterator, end) = boost::vertices( boostGraph );

  for ( ; iterator != end; ++iterator)
  {
    indexToLabel[ *iterator ] = boostGraph[ *iterator ].label;
  }

  //translate label to position
  std::vector< std::string > positionToLabelVector;
  positionToLabelVector = indexToLabel;

  std::sort ( positionToLabelVector.begin(), positionToLabelVector.end() );

  for( int outerLoop( 0 ); outerLoop < numberOfVertices; outerLoop++  )
  {
    DescriptorType fromVertexDescriptor = labelToIndexMap.find( positionToLabelVector[ outerLoop ] )->second;
    for( int innerLoop( outerLoop + 1 ); innerLoop < numberOfVertices; innerLoop++  )
    {
      DescriptorType toVertexDescriptor = labelToIndexMap.find( positionToLabelVector[ innerLoop ] )->second;


      int weight( 0 );

      if( boost::edge(toVertexDescriptor, fromVertexDescriptor, boostGraph ).second )
      {
        weight = m_InputNetwork->GetEdge( fromVertexDescriptor , toVertexDescriptor ).weight;;
      }
      connectivityMatrix[outerLoop][innerLoop] = weight;
      connectivityMatrix[innerLoop][outerLoop] = weight;
    }
  }


  OutputImageType::SpacingType spacing;
  spacing[0] = 1.0;
  spacing[1] = 1.0;
  OutputImageType::PointType origin;
  origin[0] = 0.0;
  origin[1] = 0.0;
  OutputImageType::IndexType index;
  index[0] = 0.0;
  index[1] = 0.0;
  OutputImageType::SizeType size;
  size[0] = numberOfVertices;
  size[1] = numberOfVertices;
  OutputImageType::RegionType region;
  region.SetIndex( index );
  region.SetSize( size );

  output->SetSpacing( spacing );   // Set the image spacing
  output->SetOrigin( origin );     // Set the image origin
  output->SetRegions( region );
  output->Allocate();
  output->FillBuffer(0);


  itk::ImageRegionIterator< OutputImageType > it_connect(output, output->GetLargestPossibleRegion());

  int counter( 0 );

  double rescaleFactor( 1.0 );
  double rescaleMax( 255.0 );

  if( m_RescaleConnectivity )
  {
    rescaleFactor = rescaleMax / m_InputNetwork->GetMaximumWeight();
  }

  // Colour pixels according to connectivity
  if(  m_BinaryConnectivity )
  {
    // binary connectivity
    while( !it_connect.IsAtEnd() )
    {
      if( connectivityMatrix[ ( counter - counter % numberOfVertices ) / numberOfVertices][ counter % numberOfVertices ] )
      {
        it_connect.Set( 1 );
      }
      else
      {
        it_connect.Set( 0 );
      }
      ++it_connect;
      counter++;
    }
  }
  else
  {
    // if desired rescale to the 0-255 range
    while( !it_connect.IsAtEnd() )
    {
      it_connect.Set( ( unsigned short ) rescaleFactor *
        connectivityMatrix[ ( counter - counter % numberOfVertices ) / numberOfVertices][ counter % numberOfVertices ]
      );
      ++it_connect;
      counter++;
    }
  }

}
int main(int argc, char** argv) {

    if (argc < 5) {
        std::cerr << "From the 3 images representing fiber orientation estimate angles and calculate angle homogeneity in the neighborhoods." << std::endl;
        std::cerr << "Usage: CalculateEntropyFiberAngles coordx_image coordy_image coordz_image out_image neigborhood_radius" << std::endl;
        return EXIT_FAILURE;
    }

    //parsing parameters
    int c = 1;
    const char* imagex_filename = argv[c++];
    const char* imagey_filename = argv[c++];
    const char* imagez_filename = argv[c++];
    const char* output_filename = argv[c++];
    int neighborhood_radius = atoi(argv[c++]);


    const unsigned int Dimension = 3;

    std::cout << "Input x: " << imagex_filename << std::endl;
    std::cout << "Input y: " << imagey_filename << std::endl;
    std::cout << "Input z: " << imagez_filename << std::endl;
    std::cout << "Output: " << output_filename << std::endl;
    std::cout << "Neighborhood radius: " << neighborhood_radius << std::endl;



    //main program
    typedef float InputPixelType;
    typedef float OutputPixelType;
    typedef itk::Image< InputPixelType, Dimension > InputImageType;
    typedef itk::Image< OutputPixelType, Dimension > OutputImageType;
    typedef itk::ImageFileReader< InputImageType > ReaderType;
    typedef itk::ImageFileWriter< OutputImageType > WriterType;
    ReaderType::Pointer readerx = ReaderType::New();
    ReaderType::Pointer readery = ReaderType::New();
    ReaderType::Pointer readerz = ReaderType::New();
    WriterType::Pointer writer = WriterType::New();
    readerx->SetFileName(imagex_filename);
    readery->SetFileName(imagex_filename);
    readerz->SetFileName(imagex_filename);
    writer->SetFileName(output_filename);



    std::cout<<"Reading X"<<std::endl;
    readerx->Update();
    std::cout<<"Reading Y"<<std::endl;
    readery->Update();
    std::cout<<"Reading Z"<<std::endl;
    readerz->Update();

    
    const InputImageType * inputx = readerx->GetOutput();
    const InputImageType * inputy = readery->GetOutput();
    const InputImageType * inputz = readerz->GetOutput();


    //create the output image
    OutputImageType::Pointer image = OutputImageType::New();
    image->SetRegions(inputx->GetLargestPossibleRegion());
    image->SetSpacing(inputx->GetSpacing());
    image->SetOrigin(inputx->GetOrigin());
    image->Allocate();
    image->FillBuffer(0);

    
    InputImageType::SizeType radius;
    radius[0] = neighborhood_radius;
    radius[1] = neighborhood_radius;
    radius[2] = neighborhood_radius;
    
    itk::ConstNeighborhoodIterator<InputImageType> 
            iteratorx(radius, inputx, image->GetRequestedRegion());
    itk::ConstNeighborhoodIterator<InputImageType> 
            iteratory(radius, inputy, image->GetRequestedRegion());
    itk::ConstNeighborhoodIterator<InputImageType> 
            iteratorz(radius, inputz, image->GetRequestedRegion());

    itk::ImageRegionIterator<OutputImageType>  it( image, image->GetRequestedRegion() );
    
    iteratorx.GoToBegin();
    iteratory.GoToBegin();
    iteratorz.GoToBegin();
    it.GoToBegin();
  
    const unsigned int nneighbors = (neighborhood_radius*2+1)*(neighborhood_radius*2+1)*(neighborhood_radius*2+1);
    Eigen::MatrixXf neighbors( nneighbors-1, 3 ); //to store the vectors
    Eigen::Vector3f central_vector;
    
    int c_id = (int) (nneighbors / 2); // get offset of center pixel
    
    
    //check image size for the progress indicator
    OutputImageType::RegionType region = image->GetLargestPossibleRegion();
    OutputImageType::SizeType size = region.GetSize();
    const unsigned long int npixels = size[0]*size[1]*size[2];
    
    unsigned long int k = 0;
    while ( ! iteratorx.IsAtEnd() )
    {
        if(k%10000 == 0)
        {
            std::cout<<"Processed "<<k<<"/"<<npixels<<"\r"<<std::flush;
        }
            
        k++;
            
        unsigned int j = 0;
        for (unsigned int i = 0; i < nneighbors; ++i)
        {    
            if(i!=c_id) //exclude the center
            {
                neighbors(j, 0) = iteratorx.GetPixel(i);  
                neighbors(j, 1) = iteratory.GetPixel(i);  
                neighbors(j, 2) = iteratorz.GetPixel(i);  
                j++;
            }
            else
            {
                central_vector(0) = iteratorx.GetPixel(i);  
                central_vector(1) = iteratory.GetPixel(i);  
                central_vector(2) = iteratorz.GetPixel(i);                  
            }
        }
        
        // calculate the angles 
        Eigen::VectorXf dp = neighbors*central_vector;
        
        const float variance = ((dp.array()-dp.mean()).pow(2)).mean();
        it.Set(variance);        
        
        ++iteratorx;
        ++iteratory;
        ++iteratorz;
        ++it;
    }    
    std::cout<<std::endl;
    
    //  The output of the resampling filter is connected to a writer and the
    //  execution of the pipeline is triggered by a writer update.
    try {
        writer->SetInput(image);
        writer->Update();
    } catch (itk::ExceptionObject & excep) {
        std::cerr << "Exception caught !" << std::endl;
        std::cerr << excep << std::endl;
    }

    

    
    return EXIT_SUCCESS;
}