BoundingBoxType::Pointer SBImageUtils::GetBoundingBox(ImageType::Pointer image)
{
	ConstIteratorType constIterator(image, image->GetLargestPossibleRegion());
	
	IteratorType iterator(image, image->GetLargestPossibleRegion());
	
	PointSetType::Pointer  pointSet = PointSetType::New();
	PointsContainerPointer  points = pointSet->GetPoints();
	int pointCounter=0;
	
	for (iterator.GoToBegin(), constIterator.GoToBegin(); !iterator.IsAtEnd(); ++iterator, ++constIterator) {
		
		if(constIterator.Value() == 0)
		{
			ImageType::IndexType index = constIterator.GetIndex();
			PointType point;
			point[0] = index[0];
			point[1] = index[1];
			points->InsertElement(pointCounter, point);
			pointCounter++;
		}
	}
	
	BoundingBoxType::Pointer boundingBox = BoundingBoxType::New();
	boundingBox->SetPoints(points);
	boundingBox->ComputeBoundingBox();
	
	return boundingBox;
}
Example #2
0
void Form::on_btnOpen_clicked()
{
  QString fileName = QFileDialog::getOpenFileName(this, "Open File", ".", "Image Files (*.jpg *.jpeg *.bmp *.png)");

  std::cout << "Got filename: " << fileName.toStdString() << std::endl;
  if(fileName.toStdString().empty())
    {
    std::cout << "Filename was empty." << std::endl;
    return;
    }

  /*
  typedef itk::RGBPixel<unsigned char> RGBPixelType;
  typedef itk::Image<RGBPixelType> RGBImageType;
  
  typedef itk::ImageFileReader<RGBImageType> ReaderType;
  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName(fileName.toStdString());
  reader->Update();
  
  RGBImageType::Pointer itkimage = reader->GetOutput();
  */
  
  //typedef itk::VectorImage<unsigned char, 2> ImageType;
  typedef itk::VectorImage<char, 2> ImageType;
  
  typedef itk::ImageFileReader<ImageType> ReaderType;
  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName(fileName.toStdString());
  reader->Update();
  
  ImageType::Pointer itkimage = reader->GetOutput();
  
  QImage image(itkimage->GetLargestPossibleRegion().GetSize()[0], itkimage->GetLargestPossibleRegion().GetSize()[1], QImage::Format_RGB32);
  itk::ImageRegionIterator<ImageType> imageIterator(itkimage, itkimage->GetLargestPossibleRegion());
  QColor black(0,0,0);
  while(!imageIterator.IsAtEnd())
    {
    ImageType::PixelType pixel = imageIterator.Get();
    
    //QRgb qtPixel(pixel[0], pixel[1], pixel[2]);
    //image.setPixel(imageIterator.GetIndex()[0], imageIterator.GetIndex()[1], QColor(pixel[0], pixel[1], pixel[2]).rgb());
    image.setPixel(imageIterator.GetIndex()[0], imageIterator.GetIndex()[1], black.rgb());
    ++imageIterator;
    }

  
  
  //QPixmap image;
  //image.loadFromData(itkimage->GetBufferPointer());
  
  QGraphicsScene* scene = new QGraphicsScene();
  
  //scene->addPixmap(image);
  scene->addPixmap(QPixmap::fromImage(image));
  
  this->graphicsView->setScene(scene);
  
}
Example #3
0
// ------------------------------------------------------------------------
void buildOutput(const SeriesTransform::List &series, ImageType::Pointer &outputImage,
		ImageType::Pointer &outputLabel, const unsigned int & timestep)
{
	// get the output parameters
	unsigned int slices = series.size();
	unsigned int timeSteps = series.front().images.size();
	ImageType::Pointer ref = series.front().images.front();




	
	ImageType::SpacingType spacing = ref->GetSpacing();
	spacing[2] = series.front().sliceThickness;
	ImageType::DirectionType direction = ref->GetDirection();
	ImageType::PointType origin = ref->GetOrigin();
	ImageType::RegionType region = ref->GetLargestPossibleRegion();
	region.SetSize(2,slices);


	// create the outputs
	outputImage->SetSpacing(spacing);
	outputImage->SetDirection(direction);
	outputImage->SetOrigin(origin);
	outputImage->SetRegions(region);
	outputImage->Allocate();
	

	outputLabel->SetSpacing(spacing);
	outputLabel->SetDirection(direction);
	outputLabel->SetOrigin(origin);
	outputLabel->SetRegions(region);
	outputLabel->Allocate();

	itk::ImageRegionIterator<ImageType> outLIt(outputLabel, outputLabel->GetLargestPossibleRegion());
	itk::ImageRegionIterator<ImageType> outImIt(outputImage, outputImage->GetLargestPossibleRegion());



	// loop through the slices
	for(unsigned int i = 0; i < slices; i++)
	{
		ImageType::Pointer im = series[i].images[timestep];
		ImageType::Pointer label = series[i].labelImages[timestep];

		itk::ImageRegionConstIterator<ImageType> imIt(im, im->GetLargestPossibleRegion());
		itk::ImageRegionConstIterator<ImageType> lIt(label, label->GetLargestPossibleRegion());

		while(!imIt.IsAtEnd())
		{
			outLIt.Set(lIt.Get());
			outImIt.Set(imIt.Get());

			++imIt; ++lIt;
			++outLIt; ++outImIt;
		}
	}
}
void Vector()
{
  std::cout << "Vector()" << std::endl;
  
  std::vector<float> vec(patchRadius*patchRadius);

  ImageType::Pointer image = ImageType::New();
  CreateImage(image);

  itk::Index<2> center = {{imageSize/2, imageSize/2}};
  itk::ImageRegion<2> centerRegion = GetRegionInRadiusAroundPixel(center, patchRadius);
  std::vector<float> centerDescriptor = MakeDescriptor(centerRegion, image);

  std::vector<std::vector<float> > allDescriptors;

  {
  itk::ImageRegionIterator<ImageType> imageIterator(image, image->GetLargestPossibleRegion());

  while(!imageIterator.IsAtEnd())
    {
    itk::ImageRegion<2> region = GetRegionInRadiusAroundPixel(imageIterator.GetIndex(), patchRadius);
    if(image->GetLargestPossibleRegion().IsInside(region))
      {
      allDescriptors.push_back(MakeDescriptor(region, image));
      }

    ++imageIterator;
    }
  }

  std::cout << "There are " << allDescriptors.size() << " descriptors." << std::endl;
  std::cout << "There are " << allDescriptors[0].size() << " elements per descriptor." << std::endl;
  itk::TimeProbe clock1;

  clock1.Start();
  float totalDifference = 0.0f;
  for(unsigned int outerLoop = 0; outerLoop < numberOfOuterLoops; ++outerLoop)
    {
    for(unsigned int i = 0; i < allDescriptors.size(); ++i)
      {
      totalDifference += Difference(centerDescriptor, allDescriptors[i]);
      }
    }

  clock1.Stop();
  std::cout << "Total time: " << clock1.GetTotal() << std::endl;
  std::cout << "Total difference: " << totalDifference << std::endl;
}
Example #5
0
void setup_snapshot_image(string basename, ImageType::Pointer model)
{
   ImageType::SpacingType spacing = model->GetSpacing();
   spacing[0] /= constants::SnapshotImageZoom;
   spacing[1] /= constants::SnapshotImageZoom;
   spacing[2] /= constants::SnapshotImageZoom;

   g_snapshot_image = ImageType::New();
   g_snapshot_image->SetSpacing( spacing );
   g_snapshot_image->SetOrigin( model->GetOrigin() );

   ImageType::RegionType const& region = model->GetLargestPossibleRegion();
   ImageType::RegionType::SizeType size = region.GetSize();

   // size is in pixels
   ImageType::SizeType doubled_size(size);
   doubled_size[0] *= constants::SnapshotImageZoom;
   doubled_size[1] *= constants::SnapshotImageZoom;
   doubled_size[2] *= constants::SnapshotImageZoom;
   g_snapshot_image->SetRegions( doubled_size );

   g_snapshot_image->Allocate();

   s_snapshot_basename = basename;
}
int main(int, char* [] )
{
  typedef itk::Image<unsigned char, 2> ImageType;
  ImageType::Pointer image = ImageType::New();
  CreateImage(image.GetPointer());

  const unsigned int numberOfIterations = 1e5;

  // Create a list of the indices in the image
  itk::ImageRegionConstIteratorWithIndex<ImageType> imageIterator(image, image->GetLargestPossibleRegion());
  std::vector<itk::Index<2> > indices;

  while(!imageIterator.IsAtEnd())
  {
    indices.push_back(imageIterator.GetIndex());
    ++imageIterator;
  }

  unsigned int total = 0; // To make sure the loop isn't optimized away
  for(unsigned int i = 0; i < numberOfIterations; ++i)
  {
//    total += Iterator(image.GetPointer()); // 1.4s
    total += GetPixel(image.GetPointer(), indices); // 5.9s
  }

  std::cout << "total " << total << std::endl; // To make sure the loop isn't optimized away

  return 0;
}
  /*
   * random a voxel. define plane through this voxel. reslice at the plane. compare the pixel vaues of the voxel
   * in the volume with the pixel value in the resliced image.
   * there are some indice shifting problems which causes the test to fail for oblique planes. seems like the chosen
   * worldcoordinate is not corrresponding to the index in the 2D image. and so the pixel values are not the same as
   * expected.
   */
  static void PixelvalueBasedTest()
  {
    /* setup itk image */
    typedef itk::Image<unsigned short, 3> ImageType;

    typedef itk::ImageRegionConstIterator< ImageType > ImageIterator;

    ImageType::Pointer image = ImageType::New();

    ImageType::IndexType start;
    start[0] = start[1] = start[2] = 0;

    ImageType::SizeType size;
    size[0] = size[1] = size[2] = 32;

    ImageType::RegionType imgRegion;
    imgRegion.SetSize(size);
    imgRegion.SetIndex(start);

    image->SetRegions(imgRegion);
    image->SetSpacing(1.0);
    image->Allocate();


    ImageIterator imageIterator( image, image->GetLargestPossibleRegion() );
    imageIterator.GoToBegin();


    unsigned short pixelValue = 0;

    //fill the image with distinct values
    while ( !imageIterator.IsAtEnd() )
    {
      image->SetPixel(imageIterator.GetIndex(), pixelValue);
      ++imageIterator;
      ++pixelValue;
    }
    /* end setup itk image */



    mitk::Image::Pointer imageInMitk;
    CastToMitkImage(image, imageInMitk);



    /*mitk::ImageWriter::Pointer writer = mitk::ImageWriter::New();
    writer->SetInput(imageInMitk);
    std::string file = "C:\\Users\\schroedt\\Desktop\\cube.nrrd";
    writer->SetFileName(file);
    writer->Update();*/

                PixelvalueBasedTestByPlane(imageInMitk, mitk::PlaneGeometry::Frontal);
                PixelvalueBasedTestByPlane(imageInMitk, mitk::PlaneGeometry::Sagittal);
                PixelvalueBasedTestByPlane(imageInMitk, mitk::PlaneGeometry::Axial);

  }
int main(int argc, char *argv[])
{
  // Verify arguments
  if(argc < 6)
    {
    std::cerr << "Required: outputFilename sizeX sizeY components value" << std::endl;
    return EXIT_FAILURE;
    }

  // Parse arguments
  std::string outputFilename = argv[1];

  std::stringstream ss;
  ss << argv[2] << " " << argv[3] << " " << argv[4];

  itk::Size<2> size = {{0,0}};
  unsigned int components = 0;
  float value = 0.0f;
  ss >> size[0] >> size[1] >> components >> value;


  // Output arguments
  std::cout << "outputFilename " << outputFilename << std::endl;
  std::cout << "size " << size << std::endl;
  std::cout << "value " << value << std::endl;

  ImageType::Pointer image = ImageType::New();
  itk::Index<2> index = {{0,0}};

  itk::ImageRegion<2> region(index, size);

  image->SetRegions(region);
  image->SetNumberOfComponentsPerPixel(components);
  image->Allocate();

  typename itk::ImageRegionIterator<ImageType> imageIterator(image, image->GetLargestPossibleRegion());

  ImageType::PixelType pixel;
  pixel.SetSize(components);
  pixel.Fill(value);
  
  while(!imageIterator.IsAtEnd())
    {
    imageIterator.Set(pixel);

    ++imageIterator;
    }

  // Write the result
  typedef  itk::ImageFileWriter<ImageType> WriterType;
  WriterType::Pointer writer = WriterType::New();
  writer->SetFileName(outputFilename);
  writer->SetInput(image);
  writer->Update();

  return EXIT_SUCCESS;
}
Example #9
0
// ------------------------------------------------------------------------
void createOutput(const ImageType::Pointer &input, ImageType::Pointer &output)
{
	output->SetDirection(input->GetDirection());
	output->SetSpacing(input->GetSpacing());
	output->SetRegions(input->GetLargestPossibleRegion());
	output->SetOrigin(input->GetOrigin());
	output->Allocate();
	output->FillBuffer(0);
}
void ITKImage()
{
  std::cout << "ITKImage()" << std::endl;
  
  ImageType::Pointer image = ImageType::New();
  CreateImage(image);

  itk::Index<2> center = {{imageSize/2, imageSize/2}};
  itk::ImageRegion<2> centerRegion = GetRegionInRadiusAroundPixel(center, patchRadius);

  std::vector<itk::ImageRegion<2> > allRegions;

  {
  itk::ImageRegionIterator<ImageType> imageIterator(image, image->GetLargestPossibleRegion());

  while(!imageIterator.IsAtEnd())
    {
    itk::ImageRegion<2> region = GetRegionInRadiusAroundPixel(imageIterator.GetIndex(), patchRadius);
    if(image->GetLargestPossibleRegion().IsInside(region))
      {
      allRegions.push_back(region);
      }
    ++imageIterator;
    }
  }

  itk::TimeProbe clock1;

  clock1.Start();

  float totalDifference = 0.0f;
  for(unsigned int outerLoop = 0; outerLoop < numberOfOuterLoops; ++outerLoop)
    {
    for(size_t regionId = 0; regionId < allRegions.size(); ++regionId)
      {
      totalDifference += Difference(allRegions[regionId], centerRegion, image);
      }
    }

  clock1.Stop();
  std::cout << "Total time: " << clock1.GetTotal() << std::endl;
  std::cout << "Total difference: " << totalDifference << std::endl;
  
}
Example #11
0
// ------------------------------------------------------------------------
void buildShortAxisVolume(const SeriesTransform::Map &transforms, 
		const unsigned int seriesNumber, ImageType::Pointer &saVolume)
{
	// get the short axis transforms
	SeriesTransform::Map::const_iterator mapIt = transforms.begin();
	std::vector<SeriesTransform> saSlices;
	while(mapIt != transforms.end())
	{
		if(mapIt->second.series == seriesNumber)
		{
			unsigned int sliceNum = mapIt->second.slice;

			if(saSlices.size() < (sliceNum+1))
				saSlices.resize(sliceNum+1);

			saSlices[sliceNum] = mapIt->second;
		}
		
		++mapIt;
	}


	// get the dimensions of the output image
	ImageType::Pointer reference = saSlices[0].images[0];
	unsigned int x,y,z;
	x = reference->GetLargestPossibleRegion().GetSize()[0];
	y = reference->GetLargestPossibleRegion().GetSize()[1];
	z = saSlices.size();

	ImageType::RegionType region;
	ImageType::SizeType size;
	ImageType::IndexType index;
	size[0] = x;
	size[1] = y;
	size[2] = z;

	index.Fill(0);

	region.SetSize(size);
	region.SetIndex(index);
	
	// get the other parts
	ImageType::SpacingType spacing = reference->GetSpacing();
	spacing[2] = saSlices[0].sliceThickness;
	ImageType::DirectionType direction = reference->GetDirection();
	ImageType::PointType origin = reference->GetOrigin();


	saVolume->SetOrigin(origin);
	saVolume->SetDirection(direction);
	saVolume->SetSpacing(spacing);
	saVolume->SetRegions(region);
	saVolume->Allocate();
	saVolume->FillBuffer(0);
	
}
Example #12
0
int main(int argc, char* *argv)
{


	     GetPot   cl(argc, argv);
	     if( cl.size() == 1 || cl.search(2, "--help", "-h") )
	      {
	          std::cout << "Not enough arguments" << std::endl;
	          return -1;
	      }

	const string image_n = cl.follow("NoFile", 1, "-i");

	typedef itk::Image<float, 3> ImageType;
	typedef itk::ImageFileReader<ImageType> ReaderType;

	ReaderType::Pointer reader = ReaderType::New();

	reader->SetFileName(image_n.c_str());
	reader-> Update();
	ImageType::Pointer image = reader->GetOutput();

 	typedef itk::ImageRegionIterator<ImageType> ImageIterator;
	ImageIterator it(image, image->GetLargestPossibleRegion());

	for (it.GoToBegin(); !it.IsAtEnd(); ++it)
	{
	 	if (it.Get() < -5 )
		{
		 it.Set(1.0);
		  std::cout << it.GetIndex() << std::endl;
		}
		else if (it.Get() > 5 )
		{
		 it.Set(1.0);
		  std::cout << it.GetIndex() << std::endl;
		}
		else 
		{
			it.Set(0.0);
		}
	}	

	typedef itk::ImageFileWriter<ImageType> WriterType;
	WriterType::Pointer writer = WriterType::New();
	writer->SetFileName("Trace_mask.nii.gz");
	writer->SetInput(image);
	writer->Update();

	return 0;
}
ComposeImageFilter::ImageType::IndexType ComposeImageFilter::ComputeImageIndex(long int N, ImageType::Pointer image)
{
	ImageType::IndexType index;
	ImageType::SizeType size = image->GetLargestPossibleRegion().GetSize();

	    std::div_t div_1, div_2;
	    long int temp1=size[0]*size[1];

	    div_1 = div(N,temp1);
	    index[2]=div_1.quot;

	    long int temp2=size[0];
	    div_2 = div(div_1.rem, temp2);
	    index[1]=div_2.quot;
	    index[0]=div_2.rem;
	    return index;

}
//get number of slices
int CTImageTreeItem::getNumberOfSlices() const {
	ImageType::Pointer itkImage = peekITKImage();
	if (itkImage.IsNotNull()) {
		ImageType::RegionType imageRegion = itkImage->GetLargestPossibleRegion();
		return static_cast<uint>(imageRegion.GetSize(2));
	} else {
		int num = m_fnList.size();
		if (num > 1) 
			return num;
		else {
			std::string t;
			itk::ExposeMetaData( m_dict, getNumberOfFramesTag(), t );
			std::istringstream buffer(t);
			buffer >> num;
			return num;
		}  
	}
}
bool VolumeProcess:: RunFillingZeroOnBouandary(int Bx,int By,int Bz)
{
	ImageType::Pointer tempImg = ImageType::New();
	tempImg->SetRegions( m_outputImage->GetLargestPossibleRegion() );
	tempImg->Allocate();
	tempImg->FillBuffer(0);

	ImageType::RegionType fullRegion = m_outputImage->GetBufferedRegion();

	int numColumns = fullRegion.GetSize(0);
	int numRows = fullRegion.GetSize(1);
	int numStacks = fullRegion.GetSize(2);
	int i, j,k; 

	itk::ImageRegionIteratorWithIndex< ImageType > itr( m_outputImage, fullRegion );

	for(itr.GoToBegin(); !itr.IsAtEnd(); ++itr)
	{
		
		ImageType::IndexType index = itr.GetIndex();
	    ImageType::PixelType pix = m_outputImage->GetPixel(index);
        i = index[0];
		j = index[1];
		k = index[2];
		if (i < Bx || i > numColumns -Bx || j < By || j > numRows-By ||k <Bz ||k > numStacks-Bz )
		    tempImg->SetPixel(itr.GetIndex(), 0);
		else 
			tempImg->SetPixel(itr.GetIndex(), pix);
     }
		//Copy temp img back to image 
	itk::ImageRegionIterator< ImageType > itr1( tempImg, tempImg->GetLargestPossibleRegion());
	itk::ImageRegionIterator< ImageType > itr2( m_outputImage, m_outputImage->GetLargestPossibleRegion());
	for(itr1.GoToBegin(), itr2.GoToBegin() ; !itr1.IsAtEnd(); ++itr1, ++itr2)
	{
	  itr2.Set( itr1.Get() );
	}

	if(debug)
		std::cerr << "RunFillingZero Done" << std::endl;

	return true;
  
}
Example #16
0
std::vector<cleaver::AbstractScalarField*>
NRRDTools::loadNRRDFiles(std::vector<std::string> files,
  double sigma) {
  std::vector<cleaver::AbstractScalarField*> fields;
  size_t num = 0;
  for (auto file : files) {
    // read file using ITK
    if (file.find(".nrrd") != std::string::npos) {
      itk::NrrdImageIOFactory::RegisterOneFactory();
    } else if (file.find(".mha") != std::string::npos) {
      itk::MetaImageIOFactory::RegisterOneFactory();
    }
    ReaderType::Pointer reader = ReaderType::New();
    reader->SetFileName(file);
    reader->Update();
    //do some blurring
    GaussianBlurType::Pointer blur = GaussianBlurType::New();
    blur->SetInput(reader->GetOutput());
    blur->SetVariance(sigma * sigma);
    blur->Update();
    ImageType::Pointer img = blur->GetOutput();
    //convert the image to a cleaver "abstract field"
    auto region = img->GetLargestPossibleRegion();
    auto numPixel = region.GetNumberOfPixels();
    float *data = new float[numPixel];
    auto x = region.GetSize()[0], y = region.GetSize()[1], z = region.GetSize()[2];
    fields.push_back(new cleaver::FloatField(data, x, y, z));
    auto beg = file.find_last_of("/") + 1;
    auto name = file.substr(beg, file.size() - beg);
    fields[num]->setName(name);
    itk::ImageRegionConstIterator<ImageType> imageIterator(img, region);
    size_t pixel = 0;
    while (!imageIterator.IsAtEnd()) {
      // Get the value of the current pixel
      float val = static_cast<float>(imageIterator.Get());
      ((cleaver::FloatField*)fields[num])->data()[pixel++] = val;
      ++imageIterator;
    }
    ((cleaver::FloatField*)fields[num])->setScale(cleaver::vec3(1., 1., 1.));
    num++;
  }
  return fields;
}
Example #17
0
void TestUpsample()
{
  typedef itk::Image<unsigned char, 2> ImageType;
  ImageType::Pointer image = ImageType::New();

  itk::Index<2> corner = {{0,0}};
  itk::Size<2> size = {{100,100}};
  itk::ImageRegion<2> region(corner, size);

  image->SetRegions(region);
  image->Allocate();

  ImageType::Pointer upsampled = ImageType::New();

  ITKHelpers::Upsample(image.GetPointer(), 2, upsampled.GetPointer());

  std::cout << "TestUpsample() output size: "
            << upsampled->GetLargestPossibleRegion().GetSize() << std::endl;
}
Example #18
0
// ------------------------------------------------------------------------
void getImageBounds(const ImageType::Pointer &image, BoundsType &bounds)
{
	// get the image size
	ImageType::SizeType size = image->GetLargestPossibleRegion().GetSize();
	
	typedef ImageType::IndexType IndexType;
	IndexType ind1, ind2, ind3, ind4;
	ind1.Fill(0); ind2.Fill(0); ind3.Fill(0); ind4.Fill(0);

	ind2[0] = size[0]-1;
	ind3[1] = size[1]-1;
	ind4[0] = size[0]-1;
	ind4[1] = size[1]-1;

	image->TransformIndexToPhysicalPoint(ind1, bounds.corners[0]);
	image->TransformIndexToPhysicalPoint(ind2, bounds.corners[1]);
	image->TransformIndexToPhysicalPoint(ind3, bounds.corners[2]);
	image->TransformIndexToPhysicalPoint(ind4, bounds.corners[3]);

}
int main (int argc, char *argv[])
	{
	const unsigned int ImageDimension = 2;
	    GetPot cl (argc, const_cast<char**>(argv));
	    if( cl.size() == 1 || cl.search (2,"--help","-h") )
	    {
	        std::cout << "Not Enough Arguments" << std::endl;
	        std::cout << "Generate the Gradient Table" << std::endl;
	        std::cout << "Usage:  return -1" << std::endl;
	    }

	    const string image_n = cl.follow("NoFile",1, "-i");
	    const string out_n   = cl.follow("NoFile",1, "-o");

	    typedef itk::DiffusionTensor3D<float> DiffusionTensorType;
	    typedef itk::Image<DiffusionTensorType, 3> ImageType;
	    typedef itk::ImageFileReader<ImageType> ReaderType;
	    ReaderType::Pointer reader = ReaderType::New();

	    reader->SetFileName(image_n);
	    reader->Update();

	    ImageType::Pointer image = reader->GetOutput();

	    typedef itk::ImageRegionIterator<ImageType> TensorIterator;
	    TensorIterator itImg(image, image->GetLargestPossibleRegion());

	    std::ofstream  file;
	    file.open(out_n);

	    for(itImg.GoToBegin(); !itImg.IsAtEnd(); ++itImg)
	    {
	    	file << itImg.Get() << std::endl;
	    }

	    file.close();



		return 0;
	}
Example #20
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;
	}
}
Example #21
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;
	}
}
Example #22
0
void TestHistogramOfGradients()
{
  typedef itk::Image<float, 2> ImageType;
  ImageType::Pointer image = ImageType::New();

  itk::Index<2> corner = {{0,0}};
  itk::Size<2> size = {{100,100}};
  itk::ImageRegion<2> region(corner, size);

  image->SetRegions(region);
  image->Allocate();

  std::vector<float> histogram =
         ITKHelpers::HistogramOfGradients(image.GetPointer(),
                                          image->GetLargestPossibleRegion(), 10);

  for(unsigned int i = 0; i < histogram.size(); ++i)
  {
    std::cout << histogram[i] << " ";
  }
  std::cout << std::endl;
}
Example #23
0
int main(int argc, char *argv[])
{
  if(argc < 3)
    {
    std::cerr << "Required: inputFilename outputFilename" << std::endl;
    return EXIT_FAILURE;
    }

  std::string inputFilename = argv[1];
  std::string outputFilename = argv[2];

  typedef itk::ImageFileReader<ImageType> ReaderType;
  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName(inputFilename.c_str());
  reader->Update();

  ImageType::Pointer output = ImageType::New();
  output->SetNumberOfComponentsPerPixel(reader->GetOutput()->GetNumberOfComponentsPerPixel());
  output->SetRegions(reader->GetOutput()->GetLargestPossibleRegion());
  output->Allocate();
  
  itk::ImageRegionIterator<ImageType> outputIterator(output, output->GetLargestPossibleRegion());

  while(!outputIterator.IsAtEnd())
    {
    outputIterator.Set(reader->GetOutput()->GetPixel(outputIterator.GetIndex()));

    ++outputIterator;
    }

  typedef  itk::ImageFileWriter<ImageType> WriterType;
  WriterType::Pointer writer = WriterType::New();
  writer->SetFileName(outputFilename);
  writer->SetInput(output);
  writer->Update();

  return EXIT_SUCCESS;
}
Example #24
0
bool TestComputeGradientsInRegion()
{
  itk::Index<2> imageCorner = {{0,0}};
  itk::Size<2> imageSize = {{100,100}};
  itk::ImageRegion<2> imageRegion(imageCorner, imageSize);

  typedef itk::Image<unsigned char, 2> ImageType;
  ImageType::Pointer image = ImageType::New();
  image->SetRegions(imageRegion);
  image->Allocate();

  itk::ImageRegionIterator<ImageType> imageIterator(image, image->GetLargestPossibleRegion());

  while(!imageIterator.IsAtEnd())
  {
    imageIterator.Set(rand() % 255);

    ++imageIterator;
  }

  ITKHelpers::WriteImage(image.GetPointer(), "Image.mha");

  itk::Index<2> regionCorner = {{50,50}};
  itk::Size<2> regionSize = {{10,10}};
  itk::ImageRegion<2> region(regionCorner, regionSize);

  typedef itk::Image<itk::CovariantVector<float, 2>, 2> GradientImageType;
  GradientImageType::Pointer gradientImage = GradientImageType::New();

  std::cout << "Computing gradients..." << std::endl;
  ITKHelpers::ComputeGradientsInRegion(image.GetPointer(), region, gradientImage.GetPointer());

  std::cout << "Writing..." << std::endl;
  ITKHelpers::WriteImage(gradientImage.GetPointer(), "GradientImage.mha");

  return true;
}
ImageType::Pointer SBImageUtils::ResizeImage(ImageType::Pointer input, uint width, uint height)
{
	ResampleImageFilterType::Pointer resample = ResampleImageFilterType::New();
	
	ImageType::SizeType outputSize;
	outputSize.Fill(width);
	
	ImageType::SizeType inputSize = input->GetLargestPossibleRegion().GetSize();
	
	ImageType::SpacingType outputSpacing;
	outputSpacing[0] = input->GetSpacing()[0] * (static_cast<double>(inputSize[0]) / static_cast<double>(outputSize[0]));
	outputSpacing[1] = input->GetSpacing()[1] * (static_cast<double>(inputSize[1]) / static_cast<double>(outputSize[1]));
	
	//default will be white
	resample->SetDefaultPixelValue(0xFFFF);
	
	resample->SetInput(input);
	resample->SetSize(outputSize);
	resample->SetOutputSpacing(outputSpacing);
	resample->SetTransform(TransformType::New());
	resample->UpdateLargestPossibleRegion();
	
	return resample->GetOutput();
}
  void NrrdQBallImageReader
    ::GenerateData()
  {
    if ( m_FileName == "")
    {
      throw itk::ImageFileReaderException(__FILE__, __LINE__, "Sorry, the filename of the vessel tree to be read is empty!");
    }
    else
    {
      try
      {
        const std::string& locale = "C";
        const std::string& currLocale = setlocale( LC_ALL, NULL );

        if ( locale.compare(currLocale)!=0 )
        {
          try
          {
            setlocale(LC_ALL, locale.c_str());
          }
          catch(...)
          {
            MITK_INFO << "Could not set locale " << locale;
          }
        }

        typedef itk::VectorImage<float,3> ImageType;
        itk::NrrdImageIO::Pointer io = itk::NrrdImageIO::New();
        typedef itk::ImageFileReader<ImageType> FileReaderType;
        FileReaderType::Pointer reader = FileReaderType::New();
        reader->SetImageIO(io);
        reader->SetFileName(this->m_FileName);
        reader->Update();
        ImageType::Pointer img = reader->GetOutput();

        typedef itk::Image<itk::Vector<float,QBALL_ODFSIZE>,3> VecImgType;
        VecImgType::Pointer vecImg = VecImgType::New();
        vecImg->SetSpacing( img->GetSpacing() );   // Set the image spacing
        vecImg->SetOrigin( img->GetOrigin() );     // Set the image origin
        vecImg->SetDirection( img->GetDirection() );  // Set the image direction
        vecImg->SetLargestPossibleRegion( img->GetLargestPossibleRegion());
        vecImg->SetBufferedRegion( img->GetLargestPossibleRegion() );
        vecImg->Allocate();

        itk::ImageRegionIterator<VecImgType> ot (vecImg, vecImg->GetLargestPossibleRegion() );
        ot = ot.Begin();

        itk::ImageRegionIterator<ImageType> it (img, img->GetLargestPossibleRegion() );

        typedef ImageType::PixelType  VarPixType;
        typedef VecImgType::PixelType FixPixType;

        for (it = it.Begin(); !it.IsAtEnd(); ++it)
        {
          VarPixType vec = it.Get();
          FixPixType fixVec(vec.GetDataPointer());
          ot.Set(fixVec);
          ++ot;
        }

        this->GetOutput()->InitializeByItk(vecImg.GetPointer());
        this->GetOutput()->SetVolume(vecImg->GetBufferPointer());

        try
        {
          setlocale(LC_ALL, currLocale.c_str());
        }
        catch(...)
        {
          MITK_INFO << "Could not reset locale " << currLocale;
        }
      }
      catch(std::exception& e)
      {
        throw itk::ImageFileReaderException(__FILE__, __LINE__, e.what());
      }
      catch(...)
      {
        throw itk::ImageFileReaderException(__FILE__, __LINE__, "Sorry, an error occurred while reading the requested vessel tree file!");
      }
    }
  }
int main(int argc, char* *argv)
{


	     GetPot   cl(argc, argv);
	     if( cl.size() == 1 || cl.search(2, "--help", "-h") )
	      {
	          std::cout << "Not enough arguments" << std::endl;
	          return -1;
	      }

	const string image_n = cl.follow("NoFile", 1, "-i");
	const string maskImage_n  =  cl.follow("NoFile", 1, "-m");

	typedef itk::Image<float, 3> ImageType;
	typedef itk::ImageFileReader<ImageType> ReaderType;

	ReaderType::Pointer reader = ReaderType::New();

	reader->SetFileName(maskImage_n.c_str());
	reader-> Update();
	ImageType::Pointer maskimage = reader->GetOutput();

 	typedef itk::ImageRegionIterator<ImageType> ImageIterator;
	ImageIterator it(maskimage, maskimage->GetLargestPossibleRegion());

	typedef itk::DiffusionTensor3D<float> DiffusionTensorType;
	typedef itk::Image<DiffusionTensorType, 3> TensorImageType;
	typedef itk::ImageFileReader<TensorImageType> TensorImageReaderType;
	TensorImageReaderType::Pointer tensorReader = TensorImageReaderType::New();

	tensorReader->SetFileName(image_n.c_str());
	tensorReader->Update();
	TensorImageType::Pointer tensorImage = tensorReader->GetOutput();

	typedef itk::ImageRegionIterator<TensorImageType> TensorIterator;
	TensorIterator itT(tensorImage, tensorImage->GetLargestPossibleRegion());
	
	typedef DiffusionTensorType::EigenValuesArrayType EigenArrayType;

	ImageType::Pointer Eig1 = ImageType::New();
	ImageType::Pointer Eig2 = ImageType::New();
	ImageType::Pointer Eig3 = ImageType::New();

	CopyImage cpImage;
	cpImage.CopyScalarImage(maskimage, Eig1);
	cpImage.CopyScalarImage(maskimage, Eig2);
	cpImage.CopyScalarImage(maskimage, Eig3);

	TensorImageType::Pointer tensorProb = TensorImageType::New();
	cpImage.CopyTensorImage(tensorImage, tensorProb);

	DiffusionTensorType D_Identity;
	
	vnl_matrix<float> ZeroD_mat; ZeroD_mat.set_size(3,3);
 	ZeroD_mat.set_identity();

	TensorUtilities utils;
	D_Identity = utils.ConvertMat2DT(ZeroD_mat);

	//tensorProb->FillBuffer(D_Identity);
	
	for (it.GoToBegin(), itT.GoToBegin(); !it.IsAtEnd(), !itT.IsAtEnd(); ++it, ++itT)
	{
		if (it.Get() != 0)
		{
			EigenArrayType eig;
			DiffusionTensorType D = itT.Get();
			D.ComputeEigenValues(eig);
			
			if ( (eig[0] < 0) || (eig[1] < 0 ) || (eig[2] < 0) || eig[0] > 5 || (eig[1] > 5) || (eig[2] > 5))
			{
				tensorProb->SetPixel(itT.GetIndex(), D);	
				std::cout << eig << std::endl;	
			}			
			
		
		}
	}	

	typedef itk::ImageFileWriter<TensorImageType> TensorImageWriter;
	TensorImageWriter::Pointer tensorWriter = TensorImageWriter::New();
	tensorWriter->SetFileName("TensorImage_Prob.nii.gz");
	tensorWriter->SetInput(tensorProb);
	tensorWriter->Update();
	
	return 0;
}
Example #28
0
  std::vector<itk::SmartPointer<BaseData> > NrrdTensorImageReader::Read()
  {
    std::vector<itk::SmartPointer<mitk::BaseData> > result;
    std::string location = GetInputLocation();

    if ( location == "")
    {
      throw itk::ImageFileReaderException(__FILE__, __LINE__, "Sorry, the filename is empty!");
    }
    else
    {
      try
      {
        mitk::LocaleSwitch localeSwitch("C");

        try
        {
          std::string fname3 = mitk::IOUtil::GetTempPath()+"/temp_dti.nii.gz";

          int c = 0;
          while( itksys::SystemTools::FileExists(fname3) )
          {
            fname3 = mitk::IOUtil::GetTempPath()+"/temp_dti_" + boost::lexical_cast<std::string>(c) + ".nii.gz";
            ++c;
          }

          itksys::SystemTools::CopyAFile(location.c_str(), fname3.c_str());

          typedef itk::VectorImage<float,3> ImageType;
          itk::NiftiImageIO::Pointer io = itk::NiftiImageIO::New();
          typedef itk::ImageFileReader<ImageType> FileReaderType;
          FileReaderType::Pointer reader = FileReaderType::New();
          reader->SetImageIO(io);
          reader->SetFileName(fname3);
          reader->Update();
          ImageType::Pointer img = reader->GetOutput();

          TensorImage::ItkTensorImageType::Pointer vecImg = TensorImage::ItkTensorImageType::New();
          vecImg->SetSpacing( img->GetSpacing() );   // Set the image spacing
          vecImg->SetOrigin( img->GetOrigin() );     // Set the image origin
          vecImg->SetDirection( img->GetDirection() );  // Set the image direction
          vecImg->SetRegions( img->GetLargestPossibleRegion());
          vecImg->Allocate();

          itk::ImageRegionIterator<TensorImage::ItkTensorImageType> ot (vecImg, vecImg->GetLargestPossibleRegion() );
          ot.GoToBegin();

          itk::ImageRegionIterator<ImageType> it (img, img->GetLargestPossibleRegion() );
          it.GoToBegin();

          typedef ImageType::PixelType  VarPixType;
          typedef TensorImage::PixelType FixPixType;
          int numComponents = img->GetNumberOfComponentsPerPixel();

          if (numComponents==6)
          {
            MITK_INFO << "Trying to load dti as 6-comp nifti ...";
            while (!it.IsAtEnd())
            {
              VarPixType vec = it.Get();
              FixPixType fixVec(vec.GetDataPointer());

              TensorImage::PixelType tensor;
              tensor.SetElement(0, vec.GetElement(0));
              tensor.SetElement(1, vec.GetElement(1));
              tensor.SetElement(2, vec.GetElement(2));
              tensor.SetElement(3, vec.GetElement(3));
              tensor.SetElement(4, vec.GetElement(4));
              tensor.SetElement(5, vec.GetElement(5));

              fixVec = tensor;

              ot.Set(fixVec);
              ++ot;
              ++it;
            }
          }
          else if(numComponents==9)
          {
            MITK_INFO << "Trying to load dti as 9-comp nifti ...";
            while (!it.IsAtEnd())
            {
              VarPixType vec = it.Get();
              TensorImage::PixelType tensor;
              tensor.SetElement(0, vec.GetElement(0));
              tensor.SetElement(1, vec.GetElement(1));
              tensor.SetElement(2, vec.GetElement(2));
              tensor.SetElement(3, vec.GetElement(4));
              tensor.SetElement(4, vec.GetElement(5));
              tensor.SetElement(5, vec.GetElement(8));

              FixPixType fixVec(tensor);
              ot.Set(fixVec);
              ++ot;
              ++it;
            }
          }
          else if (numComponents==1)
          {
            MITK_INFO << "Trying to load dti as 4D nifti ...";
            typedef itk::Image<float,4> ImageType;
            typedef itk::ImageFileReader<ImageType> FileReaderType;
            FileReaderType::Pointer reader = FileReaderType::New();
            reader->SetImageIO(io);
            reader->SetFileName(fname3);
            reader->Update();
            ImageType::Pointer img = reader->GetOutput();

            itk::Size<4> size = img->GetLargestPossibleRegion().GetSize();

            while (!ot.IsAtEnd())
            {
              TensorImage::PixelType tensor;
              ImageType::IndexType idx;
              idx[0] = ot.GetIndex()[0]; idx[1] = ot.GetIndex()[1]; idx[2] = ot.GetIndex()[2];

              if (size[3]==6)
              {
                for (unsigned int te=0; te<size[3]; te++)
                {
                  idx[3] = te;
                  tensor.SetElement(te, img->GetPixel(idx));
                }
              }
              else if (size[3]==9)
              {
                idx[3] = 0;
                tensor.SetElement(0, img->GetPixel(idx));
                idx[3] = 1;
                tensor.SetElement(1, img->GetPixel(idx));
                idx[3] = 2;
                tensor.SetElement(2, img->GetPixel(idx));
                idx[3] = 4;
                tensor.SetElement(3, img->GetPixel(idx));
                idx[3] = 5;
                tensor.SetElement(4, img->GetPixel(idx));
                idx[3] = 8;
                tensor.SetElement(5, img->GetPixel(idx));
              }
              else
                throw itk::ImageFileReaderException(__FILE__, __LINE__, "Unknown number of components for DTI file. Should be 6 or 9!");

              FixPixType fixVec(tensor);
              ot.Set(fixVec);
              ++ot;
            }
          }
          OutputType::Pointer resultImage = OutputType::New();
          resultImage->InitializeByItk( vecImg.GetPointer() );
          resultImage->SetVolume( vecImg->GetBufferPointer() );
          result.push_back( resultImage.GetPointer() );
        }
        catch(...)
        {
          MITK_INFO << "Trying to load dti as nrrd ...";

          typedef itk::VectorImage<float,3> ImageType;
          itk::NrrdImageIO::Pointer io = itk::NrrdImageIO::New();
          typedef itk::ImageFileReader<ImageType> FileReaderType;
          FileReaderType::Pointer reader = FileReaderType::New();
          reader->SetImageIO(io);
          reader->SetFileName(location);
          reader->Update();
          ImageType::Pointer img = reader->GetOutput();

          TensorImage::ItkTensorImageType::Pointer vecImg = TensorImage::ItkTensorImageType::New();
          vecImg->SetSpacing( img->GetSpacing() );   // Set the image spacing
          vecImg->SetOrigin( img->GetOrigin() );     // Set the image origin
          vecImg->SetDirection( img->GetDirection() );  // Set the image direction
          vecImg->SetRegions( img->GetLargestPossibleRegion());
          vecImg->Allocate();

          itk::ImageRegionIterator<TensorImage::ItkTensorImageType> ot (vecImg, vecImg->GetLargestPossibleRegion() );
          ot.GoToBegin();

          itk::ImageRegionIterator<ImageType> it (img, img->GetLargestPossibleRegion() );
          it.GoToBegin();

          typedef ImageType::PixelType  VarPixType;
          typedef TensorImage::PixelType FixPixType;
          int numComponents = img->GetNumberOfComponentsPerPixel();

          itk::MetaDataDictionary imgMetaDictionary = img->GetMetaDataDictionary();
          std::vector<std::string> imgMetaKeys = imgMetaDictionary.GetKeys();
          std::vector<std::string>::const_iterator itKey = imgMetaKeys.begin();
          std::string metaString;

          bool readFrame = false;
          double xx, xy, xz, yx, yy, yz, zx, zy, zz;
          MeasurementFrameType measFrame;
          measFrame.SetIdentity();
          MeasurementFrameType measFrameTransp;
          measFrameTransp.SetIdentity();

          for (; itKey != imgMetaKeys.end(); itKey ++)
          {
            itk::ExposeMetaData<std::string> (imgMetaDictionary, *itKey, metaString);
            if (itKey->find("measurement frame") != std::string::npos)
            {
              sscanf(metaString.c_str(), " ( %lf , %lf , %lf ) ( %lf , %lf , %lf ) ( %lf , %lf , %lf ) \n", &xx, &xy, &xz, &yx, &yy, &yz, &zx, &zy, &zz);

              if (xx>10e-10 || xy>10e-10 || xz>10e-10 ||
                yx>10e-10 || yy>10e-10 || yz>10e-10 ||
                zx>10e-10 || zy>10e-10 || zz>10e-10 )
              {
                readFrame = true;

                measFrame(0,0) = xx;
                measFrame(0,1) = xy;
                measFrame(0,2) = xz;
                measFrame(1,0) = yx;
                measFrame(1,1) = yy;
                measFrame(1,2) = yz;
                measFrame(2,0) = zx;
                measFrame(2,1) = zy;
                measFrame(2,2) = zz;

                measFrameTransp = measFrame.GetTranspose();
              }
            }
          }

          if (numComponents==6)
          {
            while (!it.IsAtEnd())
            {
              // T'=RTR'
              VarPixType vec = it.Get();
              FixPixType fixVec(vec.GetDataPointer());

              if(readFrame)
              {
                TensorImage::PixelType tensor;
                tensor.SetElement(0, vec.GetElement(0));
                tensor.SetElement(1, vec.GetElement(1));
                tensor.SetElement(2, vec.GetElement(2));
                tensor.SetElement(3, vec.GetElement(3));
                tensor.SetElement(4, vec.GetElement(4));
                tensor.SetElement(5, vec.GetElement(5));

                tensor = ConvertMatrixTypeToFixedArrayType(tensor.PreMultiply(measFrame));
                tensor = ConvertMatrixTypeToFixedArrayType(tensor.PostMultiply(measFrameTransp));
                fixVec = tensor;
              }

              ot.Set(fixVec);
              ++ot;
              ++it;
            }
          }
          else if(numComponents==9)
          {
            while (!it.IsAtEnd())
            {
              VarPixType vec = it.Get();
              TensorImage::PixelType tensor;
              tensor.SetElement(0, vec.GetElement(0));
              tensor.SetElement(1, vec.GetElement(1));
              tensor.SetElement(2, vec.GetElement(2));
              tensor.SetElement(3, vec.GetElement(4));
              tensor.SetElement(4, vec.GetElement(5));
              tensor.SetElement(5, vec.GetElement(8));

              if(readFrame)
              {
                tensor = ConvertMatrixTypeToFixedArrayType(tensor.PreMultiply(measFrame));
                tensor = ConvertMatrixTypeToFixedArrayType(tensor.PostMultiply(measFrameTransp));
              }

              FixPixType fixVec(tensor);
              ot.Set(fixVec);
              ++ot;
              ++it;
            }
          }
          else if (numComponents==1)
          {
            typedef itk::Image<float,4> ImageType;
            itk::NrrdImageIO::Pointer io = itk::NrrdImageIO::New();
            typedef itk::ImageFileReader<ImageType> FileReaderType;
            FileReaderType::Pointer reader = FileReaderType::New();
            reader->SetImageIO(io);
            reader->SetFileName(location);
            reader->Update();
            ImageType::Pointer img = reader->GetOutput();

            itk::Size<4> size = img->GetLargestPossibleRegion().GetSize();

            while (!ot.IsAtEnd())
            {
              TensorImage::PixelType tensor;
              ImageType::IndexType idx;
              idx[0] = ot.GetIndex()[0]; idx[1] = ot.GetIndex()[1]; idx[2] = ot.GetIndex()[2];

              if (size[3]==6)
              {
                for (unsigned int te=0; te<size[3]; te++)
                {
                  idx[3] = te;
                  tensor.SetElement(te, img->GetPixel(idx));
                }
              }
              else if (size[3]==9)
              {
                idx[3] = 0;
                tensor.SetElement(0, img->GetPixel(idx));
                idx[3] = 1;
                tensor.SetElement(1, img->GetPixel(idx));
                idx[3] = 2;
                tensor.SetElement(2, img->GetPixel(idx));
                idx[3] = 4;
                tensor.SetElement(3, img->GetPixel(idx));
                idx[3] = 5;
                tensor.SetElement(4, img->GetPixel(idx));
                idx[3] = 8;
                tensor.SetElement(5, img->GetPixel(idx));
              }
              else
                throw itk::ImageFileReaderException(__FILE__, __LINE__, "Unknown number of komponents for DTI file. Should be 6 or 9!");

              if(readFrame)
              {
                tensor = ConvertMatrixTypeToFixedArrayType(tensor.PreMultiply(measFrame));
                tensor = ConvertMatrixTypeToFixedArrayType(tensor.PostMultiply(measFrameTransp));
              }
              FixPixType fixVec(tensor);
              ot.Set(fixVec);
              ++ot;
            }
          }
          else
          {
            throw itk::ImageFileReaderException(__FILE__, __LINE__, "Image has wrong number of pixel components!");
          }

          OutputType::Pointer resultImage = OutputType::New();
          resultImage->InitializeByItk( vecImg.GetPointer() );
          resultImage->SetVolume( vecImg->GetBufferPointer() );
          result.push_back( resultImage.GetPointer() );
        }

      }
      catch(std::exception& e)
      {
        throw itk::ImageFileReaderException(__FILE__, __LINE__, e.what());
      }
      catch(...)
      {
        throw itk::ImageFileReaderException(__FILE__, __LINE__, "Sorry, an error occurred while reading the requested DTI file!");
      }
    }

    return result;
  }
int main(int argc, char ** argv)
{
	std::string folderName = argv[1];
	std::string filter = argv[2];

	typedef utils::Directory Directory;
	Directory::FilenamesType filenames = Directory::GetFiles(folderName, ".nrrd");

	Directory::FilenamesType goodFilenames;
	filterFilenames(filenames, filter, goodFilenames);

	// load the images
	std::vector<ImageType::Pointer> imageList;
	for(unsigned int i = 0; i < goodFilenames.size(); i++)
	{
		std::cout << goodFilenames[i] << std::endl;

		typedef itk::ImageFileReader<ImageType> ReaderType;

		ReaderType::Pointer reader = ReaderType::New();
		reader->SetFileName(goodFilenames[i]);
		reader->SetImageIO(itk::NrrdImageIO::New());
		reader->Update();

		imageList.push_back(reader->GetOutput());

	}

	std::sort(imageList.begin(), imageList.end(), imageSort);

	ImageType::Pointer outputImage = ImageType::New();
	ImageType::RegionType outputRegion;
	ImageType::SizeType outputSize = imageList.front()->GetLargestPossibleRegion().GetSize();
	outputSize[2] = imageList.size(); 
	ImageType::IndexType outputIndex;
	outputIndex.Fill(0);
	outputRegion.SetSize(outputSize);
	outputRegion.SetIndex(outputIndex);

	// compute the spacing 
	double meanSpacing = 0.0;
	for(unsigned int i = 1; i < imageList.size(); i++)
	{
		ImageType::Pointer im1 = imageList[i-1];
		ImageType::Pointer im2 = imageList[i];

		meanSpacing += (im1->GetOrigin()-im2->GetOrigin()).GetNorm();
	}

	meanSpacing /= (double) (imageList.size()-1);
	ImageType::SpacingType spacing = imageList.front()->GetSpacing();
	spacing[2] = meanSpacing;

	outputImage->SetRegions(outputRegion);
	outputImage->SetSpacing(spacing);
	outputImage->SetOrigin(imageList.front()->GetOrigin());
	outputImage->SetDirection(imageList.front()->GetDirection());
	outputImage->Allocate();

	itk::ImageRegionIterator<ImageType> outIt(outputImage, outputImage->GetLargestPossibleRegion());
	outIt.GoToBegin();

	while(!outIt.IsAtEnd())
	{
		ImageType::IndexType index = outIt.GetIndex();
		ImageType::IndexType testIndex = index;
		testIndex[2] = 0;

		outIt.Set(imageList[index[2]]->GetPixel(testIndex));


		++outIt;
	}

	std::string stackFilename = folderName + "/stack.nrrd";


	typedef itk::ImageFileWriter<ImageType> WriterType;
	WriterType::Pointer writer = WriterType::New();
	writer->SetInput(outputImage);
	writer->SetFileName(stackFilename);
	writer->SetImageIO(itk::NrrdImageIO::New());
	writer->Update();

	return 0;

}
Example #30
0
int
main(int argc, char* argv[])
{
	boost::filesystem::path inputFile;
	boost::filesystem::path outputFile;

	Algorithm algorithm;
	std::string algorithmName;

	po::options_description desc("Allowed options");
	desc.add_options()
		("help", "produce help message")
		("input,i", po::value<boost::filesystem::path>(&inputFile), "input file")
		("algorithm,a", po::value<std::string>(&algorithmName)->default_value("itk-implementation"), "itk-implementation")
		("output,o", po::value<boost::filesystem::path>(&outputFile), "output mask file")
		;

	po::variables_map vm;
	po::store(po::parse_command_line(argc, argv, desc), vm);
	po::notify(vm);

	algorithm = getAlgorithmFromString(algorithmName);

	if (vm.count("help")) {
		std::cout << desc << "\n";
		return 1;
	}

	if (vm.count("input") == 0) {
		std::cout << "Missing input filename\n" << desc << "\n";
		return 1;
	}

	if (vm.count("output") == 0) {
		std::cout << "Missing output filename\n" << desc << "\n";
		return 1;
	}

	typedef itk::ImageFileReader<ImageType>  ImageReaderType;

	BOOST_LOG_TRIVIAL(info) << "Loading inputs ...";
	ImageReaderType::Pointer imageReader = ImageReaderType::New();
	imageReader->SetFileName(inputFile.string());
	imageReader->Update();

	ImageType::Pointer image = imageReader->GetOutput();

	LabeledImageType::Pointer outputImage;

	switch (algorithm) {
	case Algorithm::ItkImplementation: {
		BOOST_LOG_TRIVIAL(info) << "Running ITK version of watershed transformation ...";
			WatershedFilterType::Pointer filter = WatershedFilterType::New();
			filter->SetInput(image);
			filter->MarkWatershedLineOff();

			boost::timer::cpu_timer computationTimer;
			computationTimer.start();
			filter->Update();
			BOOST_LOG_TRIVIAL(info) << "Computation time: " << computationTimer.format(9, "%w");

			outputImage = filter->GetOutput();
		}
		break;
	default:
		BOOST_LOG_TRIVIAL(info) << "Allocating output ...";
		outputImage = LabeledImageType::New();
		outputImage->SetRegions(image->GetLargestPossibleRegion());
		outputImage->Allocate();
		outputImage->SetSpacing(image->GetSpacing());
		BOOST_LOG_TRIVIAL(info) << "Running CUDA version of watershed transformation (topographical distance)...";
		boost::timer::cpu_timer computationTimer;
		computationTimer.start();
		watershedTransformation2(
			cugip::const_view(*(image.GetPointer())),
			cugip::view(*(outputImage.GetPointer())),
			Options()
			);
		BOOST_LOG_TRIVIAL(info) << "Computation time: " << computationTimer.format(9, "%w");
		//BOOST_LOG_TRIVIAL(error) << "Unknown algorithm";
	}

	BOOST_LOG_TRIVIAL(info) << "Saving output `" << outputFile << "` ...";
	WriterType::Pointer writer = WriterType::New();
	writer->SetFileName(outputFile.string());
	writer->SetInput(outputImage);
	try {
		writer->Update();
	} catch (itk::ExceptionObject & error) {
		std::cerr << "Error: " << error << std::endl;
		return EXIT_FAILURE;
	}

	return 0;
}