int main(int argc, char** argv) {
	if(argc != 3){
		std::cout << "Usage: Test2DImage inputFilename outputFilename"; 
		return 1;
	}
	typedef signed int InputPixelType;
	const unsigned int Dimension = 2;
	typedef itk::Image<InputPixelType, Dimension> InputImageType;
	typedef itk::RGBPixel<unsigned char> RGBPixelType;
	typedef itk::Image<RGBPixelType, 2> RGBImageType;
	typedef itk::ImageFileReader<InputImageType> ReaderType;
	typedef itk::ImageFileWriter<RGBImageType> WriterType;
	typedef itk::GDCMImageIO ImageIOType;
	typedef itk::GradientAnisotropicDiffusionImageFilter<InputImageType,
	InputImageType> DiffusionFilterType;
	typedef itk::GradientMagnitudeImageFilter<InputImageType, InputImageType>
			GradientMagnitudeFilterType;
	typedef itk::Functor::ScalarToRGBPixelFunctor<int> ColorMapFunctorType;
	typedef itk::UnaryFunctorImageFilter<InputImageType,
	RGBImageType, ColorMapFunctorType> ColorMapFilterType;
	typedef itk::JPEGImageIO JImageIOType;

	ReaderType::Pointer reader = ReaderType::New();
	WriterType::Pointer writer = WriterType::New();
	ImageIOType::Pointer GDCMImageIO = ImageIOType::New();
	JImageIOType::Pointer JPEGImageIO = JImageIOType::New();
	ColorMapFilterType::Pointer colormapper = ColorMapFilterType::New();

	reader->SetFileName(argv[1]);
	reader->SetImageIO(GDCMImageIO);

	try {
		reader->Update();
	}
	catch (itk::ExceptionObject & e) {
		std::cerr << "exception in file reader " << std::endl;
		std::cerr << e << std::endl;
		return 1;
	}
	DiffusionFilterType::Pointer diffusion = DiffusionFilterType::New();
	diffusion->SetNumberOfIterations(1);
	diffusion->SetConductanceParameter(4);
	diffusion->SetTimeStep(0.125);
	GradientMagnitudeFilterType::Pointer gradient = GradientMagnitudeFilterType::New();
	diffusion->SetInput(reader->GetOutput());
	gradient->SetInput(diffusion->GetOutput());
	gradient->Update();
	MyWatershedSegmenter<InputImageType> watershed(gradient->GetOutput());
	watershed.buildLowerCompleteImage();
	watershed.buildLabeledImage();
	colormapper->SetInput(watershed.returnFinalImage());
	writer->SetInput(colormapper->GetOutput());
	writer->UseInputMetaDataDictionaryOff();
	writer->SetImageIO(JPEGImageIO);
	writer->SetFileName(argv[2]);
	writer->Update();
}
// ------------------------------------------------------------------------
void DicomParser::writeSeries(const DicomSeries &series, const QString &outputFolder)
{
	// create the series name
	QString name = QString::fromStdString(series.description);
	name.replace(" ","_");
	name += "_" + QString::number(series.images.front().seriesNumber);
	name += ".nrrd";
	
	QDir path(outputFolder);
	QString fullPath = path.absoluteFilePath(name);
	

	std::vector<DicomImage> images = series.images;
	std::sort(images.begin(), images.end());

	// write and build the output images 
	typedef itk::Image<unsigned short, 3> ImageType;
	typedef itk::Image<unsigned short, 4> OutputImageType;
	typedef itk::ImageFileReader<ImageType> ReaderType;
	typedef itk::JoinSeriesImageFilter<ImageType, OutputImageType> JoinerType;

	JoinerType::Pointer joiner = JoinerType::New();
	ImageType::Pointer orig;
	for(unsigned int i = 0; i < images.size(); i++)
	{
		ReaderType::Pointer reader = ReaderType::New();
		reader->SetFileName(images[i].filename);
		std::cout << images[i].filename << std::endl;
		reader->SetImageIO(itk::GDCMImageIO::New());
		reader->Update();

		ImageType::Pointer im = reader->GetOutput();
		if(i == 0) orig = im;


		im->SetOrigin(orig->GetOrigin());
		im->SetDirection(orig->GetDirection());
		im->SetSpacing(orig->GetSpacing());

		joiner->SetInput(i, reader->GetOutput());
	}


	std::cout << joiner->GetOutput()->GetDirection() << std::endl;


	typedef itk::ImageFileWriter<OutputImageType> WriterType;
	WriterType::Pointer writer = WriterType::New();
	writer->SetInput(joiner->GetOutput());
	writer->SetFileName(fullPath.toStdString());
	writer->SetImageIO(itk::NrrdImageIO::New());
	writer->Update();

}
Beispiel #3
0
ImageType::Pointer vesselnessFilter(ImageType::Pointer im, float typeImageFactor_, double alpha, double beta, double gamma, double sigmaMinimum, double sigmaMaximum, unsigned int numberOfSigmaSteps, double sigmaDistance)
{
    typedef itk::ImageDuplicator< ImageType > DuplicatorTypeIm;
    DuplicatorTypeIm::Pointer duplicator = DuplicatorTypeIm::New();
    duplicator->SetInputImage(im);
    duplicator->Update();
    ImageType::Pointer clonedImage = duplicator->GetOutput();

    typedef itk::SymmetricSecondRankTensor< double, 3 > HessianPixelType;
    typedef itk::Image< HessianPixelType, 3 >           HessianImageType;
    typedef itk::HessianToObjectnessMeasureImageFilter< HessianImageType, ImageType > ObjectnessFilterType;
    ObjectnessFilterType::Pointer objectnessFilter = ObjectnessFilterType::New();
    objectnessFilter->SetBrightObject( 1-typeImageFactor_ );
    objectnessFilter->SetScaleObjectnessMeasure( false );
    objectnessFilter->SetAlpha( alpha );
    objectnessFilter->SetBeta( beta );
    objectnessFilter->SetGamma( gamma );
    objectnessFilter->SetObjectDimension(1);

    typedef itk::MultiScaleHessianBasedMeasureImageFilter< ImageType, HessianImageType, ImageType > MultiScaleEnhancementFilterType;
    MultiScaleEnhancementFilterType::Pointer multiScaleEnhancementFilter =
        MultiScaleEnhancementFilterType::New();
    multiScaleEnhancementFilter->SetInput( clonedImage );
    multiScaleEnhancementFilter->SetHessianToMeasureFilter( objectnessFilter );
    multiScaleEnhancementFilter->SetSigmaStepMethodToLogarithmic();
    multiScaleEnhancementFilter->SetSigmaMinimum( sigmaMinimum );
    multiScaleEnhancementFilter->SetSigmaMaximum( sigmaMaximum );
    multiScaleEnhancementFilter->SetNumberOfSigmaSteps( numberOfSigmaSteps );
    multiScaleEnhancementFilter->Update();

    ImageType::Pointer vesselnessImage = multiScaleEnhancementFilter->GetOutput();

    WriterType::Pointer writerVesselNess = WriterType::New();
    itk::NiftiImageIO::Pointer ioV = itk::NiftiImageIO::New();
    writerVesselNess->SetImageIO(ioV);
    writerVesselNess->SetInput( vesselnessImage );
    writerVesselNess->SetFileName("imageVesselNessFilter.nii.gz");
    try {
        writerVesselNess->Update();
    }
    catch( itk::ExceptionObject & e )
    {
        cout << "Exception thrown ! " << endl;
        cout << "An error ocurred during Writing 1" << endl;
        cout << "Location    = " << e.GetLocation()    << endl;
        cout << "Description = " << e.GetDescription() << endl;
    }

    return vesselnessImage;
}
void ScaleSpaceExplorer::SavePlateness(){
	QFileDialog dialog;
	dialog.setAcceptMode(QFileDialog::AcceptSave);
	dialog.setNameFilter("Image files (*.ome.tif)");
	dialog.setFileMode(QFileDialog::AnyFile);
	if(dialog.exec()){
			QString fileName = dialog.selectedFiles().first();

			typedef itk::ImageFileWriter<VertexnessImageType> WriterType;

			WriterType::Pointer writer = WriterType::New();
			itk::SCIFIOImageIO::Pointer iodriver = itk::SCIFIOImageIO::New();
			writer->SetImageIO(iodriver);
			writer->SetFileName(fileName.toStdString());
			writer->SetInput(m_PlatenessImages[m_CurrentPlateness]);
			writer->Update();

	}
}
// ------------------------------------------------------------------------
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 Image3D::TransformMeshToBinaryImage(Mesh* m, string filename, OrientationType orient, bool sub_segmentation, bool cropUpDown, CVector3* upperSlicePoint, CVector3* upperSliceNormal, CVector3* downSlicePoint, CVector3* downSliceNormal)
{
    //m->subdivision(2);
    MeshTypeB::Pointer mesh;
    MeshFilterType::Pointer meshFilter = MeshFilterType::New();
    if (cropUpDown)
    {
        mesh = MeshTypeB::New();
        vtkSmartPointer<vtkPolyData> polyData;
        try {
            polyData = m->reduceMeshUpAndDown(*upperSlicePoint, *upperSliceNormal, *downSlicePoint, *downSliceNormal);
        }
        catch (const exception& e) {
            cout << e.what() << endl;
        }

        vtkSmartPointer<vtkFillHolesFilter> fillHolesFilter = vtkSmartPointer<vtkFillHolesFilter>::New();
        fillHolesFilter->SetInputData(polyData);
        fillHolesFilter->SetHoleSize(1000.0);
        fillHolesFilter->Update();

        // Make the triangle windong order consistent
        vtkSmartPointer<vtkPolyDataNormals> normals = vtkSmartPointer<vtkPolyDataNormals>::New();
        normals->SetInputData(fillHolesFilter->GetOutput());
        normals->ConsistencyOn();
        normals->SplittingOff();
        normals->Update();

        // Restore the original normals
        normals->GetOutput()->GetPointData()->SetNormals(polyData->GetPointData()->GetNormals());
        polyData = normals->GetOutput();

        //
        // Transfer the points from the vtkPolyData into the itk::Mesh
        //
        const unsigned int numberOfPoints = polyData->GetNumberOfPoints();
        vtkPoints * vtkpoints = polyData->GetPoints();
        mesh->GetPoints()->Reserve( numberOfPoints );
        for(unsigned int p =0; p < numberOfPoints; p++)
        {
            double * apoint = vtkpoints->GetPoint( p );
            mesh->SetPoint( p, MeshTypeB::PointType( apoint ));
        }

        //
        // Transfer the cells from the vtkPolyData into the itk::Mesh
        //
        vtkCellArray * triangleStrips = polyData->GetStrips();
        vtkIdType  * cellPoints;
        vtkIdType    numberOfCellPoints;

        //
        // First count the total number of triangles from all the triangle strips.
        //
        unsigned int numberOfTriangles = 0;
        triangleStrips->InitTraversal();
        while( triangleStrips->GetNextCell( numberOfCellPoints, cellPoints ) )
        {
            numberOfTriangles += numberOfCellPoints-2;
        }

        vtkCellArray * polygons = polyData->GetPolys();
        polygons->InitTraversal();
        while( polygons->GetNextCell( numberOfCellPoints, cellPoints ) )
        {
            if( numberOfCellPoints == 3 )
            {
                numberOfTriangles ++;
            }
        }

        //
        // Reserve memory in the itk::Mesh for all those triangles
        //
        mesh->GetCells()->Reserve( numberOfTriangles );

        //
        // Copy the triangles from vtkPolyData into the itk::Mesh
        //
        //
        typedef MeshTypeB::CellType   CellType;
        typedef itk::TriangleCell< CellType > TriangleCellType;
        int cellId = 0;

        // first copy the triangle strips
        triangleStrips->InitTraversal();
        while( triangleStrips->GetNextCell( numberOfCellPoints, cellPoints ) )
        {
            unsigned int numberOfTrianglesInStrip = numberOfCellPoints - 2;

            unsigned long pointIds[3];
            pointIds[0] = cellPoints[0];
            pointIds[1] = cellPoints[1];
            pointIds[2] = cellPoints[2];

            for( unsigned int t=0; t < numberOfTrianglesInStrip; t++ )
            {
                MeshTypeB::CellAutoPointer c;
                TriangleCellType * tcell = new TriangleCellType;
                tcell->SetPointIds( pointIds );
                c.TakeOwnership( tcell );
                mesh->SetCell( cellId, c );
                cellId++;
                pointIds[0] = pointIds[1];
                pointIds[1] = pointIds[2];
                pointIds[2] = cellPoints[t+3];
            }
        }

        // then copy the normal triangles
        polygons->InitTraversal();
        while( polygons->GetNextCell( numberOfCellPoints, cellPoints ) )
        {
            if( numberOfCellPoints !=3 ) // skip any non-triangle.
            {
                continue;
            }
            MeshTypeB::CellAutoPointer c;
            TriangleCellType * t = new TriangleCellType;
            t->SetPointIds( (unsigned long*)cellPoints );
            c.TakeOwnership( t );
            mesh->SetCell( cellId, c );
            cellId++;
        }

        meshFilter->SetInput(mesh);
    }
    else
    {
        mesh = MeshTypeB::New();
        vector<Vertex*> points = m->getListPoints();
        PointType pnt;
        CVector3 p, n;
        for (unsigned int i=0; i<points.size(); i++) {
            p = points[i]->getPosition();
            n = points[i]->getNormal();
            pnt[0] = p[0]; pnt[1] = p[1]; pnt[2] = p[2];
            mesh->SetPoint(i,pnt);
        }
        vector<int> triangles = m->getListTriangles();
        for (unsigned int i=0; i<triangles.size(); i+=3)
        {
            CellTypeB::CellAutoPointer triangle;
            triangle.TakeOwnership(new CellTypeB);
            triangle->SetPointId(0,triangles[i]);
            triangle->SetPointId(1,triangles[i+1]);
            triangle->SetPointId(2,triangles[i+2]);
            mesh->SetCell((int)(i+1)/3,triangle);
        }
        meshFilter->SetInput(mesh);
    }

    meshFilter->SetOrigin(imageOriginale_->GetOrigin());
    meshFilter->SetSpacing(imageOriginale_->GetSpacing());
    meshFilter->SetSize(imageOriginale_->GetLargestPossibleRegion().GetSize());
    meshFilter->SetDirection(imageOriginale_->GetDirection());
    meshFilter->SetIndex(imageOriginale_->GetLargestPossibleRegion().GetIndex());
    //meshFilter->SetTolerance(1.0);
    meshFilter->SetInsideValue(1.0);
    meshFilter->SetOutsideValue(0.0);
    try {
        meshFilter->Update();
    }
    catch( itk::ExceptionObject & e )
    {
        cout << "Exception thrown ! " << endl;
        cout << "An error ocurred during creating binary image" << endl;
        cout << "Location    = " << e.GetLocation()    << endl;
        cout << "Description = " << e.GetDescription() << endl;
    }
    
    BinaryImageType::Pointer im = meshFilter->GetOutput();
    
    if (!sub_segmentation)
    {
        imageSegmentation_ = im;
    }
    else
    {
        BinaryImageType::RegionType region = im->GetLargestPossibleRegion();
        itk::ImageRegionConstIterator<BinaryImageType> imageIterator(im,region);
        unsigned char pixel, pixel_seg;
        BinaryIndexType index;
        while(!imageIterator.IsAtEnd())
        {
            index = imageIterator.GetIndex();
            pixel = imageIterator.Get();
            
            pixel_seg = imageSegmentation_->GetPixel(index);
            im->SetPixel(index,pixel && !pixel_seg);
            ++imageIterator;
        }
    }
    
    OrientImage<BinaryImageType> orientationFilter;
    orientationFilter.setInputImage(im);
    orientationFilter.orientation(orient);
    im = orientationFilter.getOutputImage();
    
    // Write the image
    typedef itk::ImageFileWriter< BinaryImageType >     WriterType;
    WriterType::Pointer writer = WriterType::New();
    itk::NiftiImageIO::Pointer io = itk::NiftiImageIO::New();
    writer->SetImageIO(io);
    writer->SetFileName(filename);
    writer->SetInput(im);
    try {
        writer->Update();
    }
    catch( itk::ExceptionObject & e )
    {
        cout << "Exception thrown ! " << endl;
        cout << "An error ocurred during Writing" << endl;
        cout << "Location    = " << e.GetLocation()    << endl;
        cout << "Description = " << e.GetDescription() << endl;
    }
}
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;

}
int main(int, char ** argv)
{
	OptionsData options;
	readXMLValues(argv[2], options);
	
	exit(1);


	// parse the dicom directory
	gdcm::Directory dir;
	dir.Load(argv[1], true);
	gdcm::Directory::FilenamesType filenames = dir.GetFilenames();

	
	gdcm::Tag seriesDescription = gdcm::Tag(0x0008,0x103e);
	gdcm::Tag seriesNumber = gdcm::Tag(0x0020,0x0011);
	gdcm::Tag instanceNumber = gdcm::Tag(0x0020,0x0013);
	gdcm::Tag sliceThickness = gdcm::Tag(0x0018,0x0050);
	gdcm::Tag triggerTime = gdcm::Tag(0x0018,0x1060);
	gdcm::Tag numberOfImages = gdcm::Tag(0x0018,0x1090);
	gdcm::Tag slicePosition = gdcm::Tag(0x0019,0x1015);
	gdcm::Tag imagePosition = gdcm::Tag(0x0020,0x0032);
	gdcm::Tag imageOrientation = gdcm::Tag(0x0020,0x0037);
	gdcm::Tag sliceLocation = gdcm::Tag(0x0020,0x1041);
	gdcm::Tag rows = gdcm::Tag(0x0028,0x0010);
	gdcm::Tag cols = gdcm::Tag(0x0028,0x0011);
	gdcm::Tag pixelSpacing = gdcm::Tag(0x0028,0x0030);

	gdcm::Scanner scanner;
	scanner.AddTag(seriesDescription);
	scanner.AddTag(seriesNumber);
	scanner.AddTag(instanceNumber);
	scanner.AddTag(sliceThickness);
	scanner.AddTag(triggerTime);
	scanner.AddTag(numberOfImages);
	scanner.AddTag(slicePosition);
	scanner.AddTag(imagePosition);
	scanner.AddTag(imageOrientation);
	scanner.AddTag(sliceLocation);
	scanner.AddTag(rows);
	scanner.AddTag(cols);
	scanner.AddTag(pixelSpacing);

	scanner.Scan(filenames);
	gdcm::Scanner::MappingType mapping = scanner.GetMappings();


	// extract all the images that are Short axis and are the first instance
	gdcm::Directory::FilenamesType targetFilenames;
	for(unsigned int i = 0; i < filenames.size(); i++)
	{
		const char * fname = filenames[i].c_str();
		if(mapping.count(fname) == 0) continue;


		// extract the image information
		std::string descriptionStr = mapping[fname][seriesDescription];
		std::string instanceNumberStr = mapping[fname][instanceNumber];
		QString description = QString::fromStdString(descriptionStr);
		unsigned int instanceNumber = QString::fromStdString(instanceNumberStr).toInt();

		// check that the description is a short axis one and is instance 1
		if(instanceNumber == 1 && description.contains("sa", Qt::CaseInsensitive))
		{
			targetFilenames.push_back(filenames[i]);
		}
	}


	// sort the images based on their slice position
	/*
	gdcm::Sorter sorter;
	sorter.SetSortFunction(position_sort);
	sorter.StableSort(targetFilenames);

	gdcm::Directory::FilenamesType sorted = sorter.GetFilenames();
	for(unsigned int i = 0; i < sorted.size(); i++)
	{
		const char * fname = sorted[i].c_str();
		std::string position = mapping[fname][imagePosition];
		std::cout << position << std::endl;
		std::cout << mapping[fname][sliceLocation] << std::endl;
	}
	*/

	std::cout << targetFilenames.size() << std::endl;


	// find the slice with the smallest slice position
	double smallest = 1000000.0;
	int smallestIndex;
	for(unsigned int i = 0; i < targetFilenames.size(); i++)
	{
		const char * fname = targetFilenames[i].c_str();
		std::string slicePosition = mapping[fname][sliceLocation];
		double pos = QString::fromStdString(slicePosition).toDouble();

		std::cout << pos << std::endl;
		if(pos < smallest)
		{	
			smallest = pos;
			smallestIndex = i;
		}
	}

	// load the image
	typedef itk::Image<unsigned short, 3> ImageType;
	typedef itk::ImageFileReader<ImageType> ReaderType;
	ReaderType::Pointer reader = ReaderType::New();
	reader->SetFileName(targetFilenames[smallestIndex]);
	reader->SetImageIO(itk::GDCMImageIO::New());
	reader->Update();

	
	// flip the x and y axis
	typedef itk::PermuteAxesImageFilter<ImageType> FlipperType;
	FlipperType::Pointer flipper = FlipperType::New();
	itk::FixedArray<unsigned int, 3> order;
	order[0] = 1;
	order[1] = 0;
	order[2] = 2;
	flipper->SetOrder(order);
	flipper->SetInput(reader->GetOutput());
	flipper->Update();


	ImageType::Pointer referenceImage = flipper->GetOutput();
	ImageType::DirectionType direction = referenceImage->GetDirection();
	direction.SetIdentity();
	referenceImage->SetDirection(direction);
	
	ImageType::PointType origin = referenceImage->GetOrigin();
	origin.Fill(20.0);
	referenceImage->SetOrigin(origin);

	ImageType::SpacingType spacing;
	spacing.Fill(1.0);

	referenceImage->SetSpacing(spacing);


	
	flipper->GetOutput()->Print(std::cout);

	typedef itk::ImageFileWriter<ImageType> WriterType;
	WriterType::Pointer writer = WriterType::New();
	writer->SetInput(referenceImage);
	writer->SetImageIO(itk::NrrdImageIO::New());
	writer->SetFileName("test.nrrd");
	writer->Update();

	std::cout << targetFilenames[smallestIndex] << std::endl;

	return 0;
}
void mitk::DiffusionImageNrrdWriterService::Write()
{
  mitk::Image::ConstPointer input = dynamic_cast<const mitk::Image *>(this->GetInput());

  VectorImageType::Pointer itkImg;
  mitk::CastToItkImage(input,itkImg);

  if (input.IsNull())
  {
    MITK_ERROR <<"Sorry, input to DiffusionImageNrrdWriterService is NULL!";
    return;
  }
  if ( this->GetOutputLocation().empty() )
  {
    MITK_ERROR << "Sorry, filename has not been set!";
    return ;
  }
  mitk::LocaleSwitch localeSwitch("C");

  char keybuffer[512];
  char valbuffer[512];

  //itk::MetaDataDictionary dic = input->GetImage()->GetMetaDataDictionary();

  vnl_matrix_fixed<double,3,3> measurementFrame = mitk::DiffusionPropertyHelper::GetMeasurementFrame(input);
  if (measurementFrame(0,0) || measurementFrame(0,1) || measurementFrame(0,2) ||
    measurementFrame(1,0) || measurementFrame(1,1) || measurementFrame(1,2) ||
    measurementFrame(2,0) || measurementFrame(2,1) || measurementFrame(2,2))
  {
    sprintf( valbuffer, " (%lf,%lf,%lf) (%lf,%lf,%lf) (%lf,%lf,%lf)", measurementFrame(0,0), measurementFrame(0,1), measurementFrame(0,2), measurementFrame(1,0), measurementFrame(1,1), measurementFrame(1,2), measurementFrame(2,0), measurementFrame(2,1), measurementFrame(2,2));
    itk::EncapsulateMetaData<std::string>(itkImg->GetMetaDataDictionary(),std::string("measurement frame"),std::string(valbuffer));
  }

  sprintf( valbuffer, "DWMRI");
  itk::EncapsulateMetaData<std::string>(itkImg->GetMetaDataDictionary(),std::string("modality"),std::string(valbuffer));

  if(mitk::DiffusionPropertyHelper::GetGradientContainer(input)->Size())
  {
    sprintf( valbuffer, "%1f", mitk::DiffusionPropertyHelper::GetReferenceBValue(input) );
    itk::EncapsulateMetaData<std::string>(itkImg->GetMetaDataDictionary(),std::string("DWMRI_b-value"),std::string(valbuffer));
  }

  for(unsigned int i=0; i<mitk::DiffusionPropertyHelper::GetGradientContainer(input)->Size(); i++)
  {
    sprintf( keybuffer, "DWMRI_gradient_%04d", i );

    /*if(itk::ExposeMetaData<std::string>(input->GetMetaDataDictionary(),
    std::string(keybuffer),tmp))
    continue;*/

    sprintf( valbuffer, "%1f %1f %1f", mitk::DiffusionPropertyHelper::GetGradientContainer(input)->ElementAt(i).get(0),
      mitk::DiffusionPropertyHelper::GetGradientContainer(input)->ElementAt(i).get(1), mitk::DiffusionPropertyHelper::GetGradientContainer(input)->ElementAt(i).get(2));

    itk::EncapsulateMetaData<std::string>(itkImg->GetMetaDataDictionary(),std::string(keybuffer),std::string(valbuffer));
  }

  typedef itk::VectorImage<short,3> ImageType;

  std::string ext = this->GetMimeType()->GetExtension(this->GetOutputLocation());
  ext = itksys::SystemTools::LowerCase(ext);

  // default extension is .dwi
  if( ext == "")
  {
    ext = ".nrrd";
    this->SetOutputLocation(this->GetOutputLocation() + ext);
  }

  if (ext == ".hdwi" || ext == ".nrrd" || ext == ".dwi")
  {

    MITK_INFO << "Extension " << ext;
    itk::NrrdImageIO::Pointer io = itk::NrrdImageIO::New();
    //io->SetNrrdVectorType( nrrdKindList );
    io->SetFileType( itk::ImageIOBase::Binary );
    io->UseCompressionOn();

    typedef itk::ImageFileWriter<ImageType> WriterType;
    WriterType::Pointer nrrdWriter = WriterType::New();
    nrrdWriter->UseInputMetaDataDictionaryOn();
    nrrdWriter->SetInput( itkImg );
    nrrdWriter->SetImageIO(io);
    nrrdWriter->SetFileName(this->GetOutputLocation());
    nrrdWriter->UseCompressionOn();
    nrrdWriter->SetImageIO(io);
    try
    {
      nrrdWriter->Update();
    }
    catch (itk::ExceptionObject e)
    {
      std::cout << e << std::endl;
      throw;
    }

  }
}