17 #ifndef __mitkLabelSetImageWriter__cpp
18 #define __mitkLabelSetImageWriter__cpp
29 #include "itkImageFileReader.h"
30 #include "itkImageFileWriter.h"
31 #include "itkMetaDataDictionary.h"
32 #include "itkMetaDataObject.h"
33 #include "itkNrrdImageIO.h"
67 if (inputVector.IsNull())
69 mitkThrow() <<
"Cannot write non-image data";
79 if (inputVector->GetDimension() == 2 && !geometry->Is2DConvertable())
81 MITK_WARN <<
"Saving a 2D image with 3D geometry information. Geometry information will be lost! You might "
82 "consider using Convert2Dto3DImageFilter before saving.";
86 affTrans->SetIdentity();
89 geometry->SetIndexToWorldTransform(affTrans);
90 geometry->SetSpacing(spacing);
91 geometry->SetOrigin(origin);
97 MITK_INFO <<
"Writing image: " << path << std::endl;
104 const unsigned int dimension = inputVector->GetDimension();
105 const unsigned int *
const dimensions = inputVector->GetDimensions();
112 itk::Vector<double, 4u> spacing4D;
113 spacing4D[0] = mitkSpacing[0];
114 spacing4D[1] = mitkSpacing[1];
115 spacing4D[2] = mitkSpacing[2];
118 itk::Vector<double, 4u> origin4D;
119 origin4D[0] = mitkOrigin[0];
120 origin4D[1] = mitkOrigin[1];
121 origin4D[2] = mitkOrigin[2];
125 nrrdImageIo->SetNumberOfDimensions(dimension);
128 static_cast<itk::ImageIOBase::IOComponentType
>(pixelType.
GetComponentType()) :
129 itk::ImageIOBase::UNKNOWNCOMPONENTTYPE);
132 itk::ImageIORegion ioRegion(dimension);
134 for (
unsigned int i = 0; i < dimension; i++)
136 nrrdImageIo->SetDimensions(i, dimensions[i]);
137 nrrdImageIo->SetSpacing(i, spacing4D[i]);
138 nrrdImageIo->SetOrigin(i, origin4D[i]);
141 mitkDirection.SetVnlVector(geometry->GetIndexToWorldTransform()->GetMatrix().GetVnlMatrix().get_column(i));
142 itk::Vector<double, 4u> direction4D;
143 direction4D[0] = mitkDirection[0];
144 direction4D[1] = mitkDirection[1];
145 direction4D[2] = mitkDirection[2];
157 vnl_vector<double> axisDirection(dimension);
158 for (
unsigned int j = 0; j < dimension; j++)
160 axisDirection[j] = direction4D[j] / spacing4D[i];
162 nrrdImageIo->SetDirection(i, axisDirection);
164 ioRegion.SetSize(i, inputVector->GetLargestPossibleRegion().GetSize(i));
165 ioRegion.SetIndex(i, inputVector->GetLargestPossibleRegion().GetIndex(i));
169 nrrdImageIo->UseCompressionOn();
171 nrrdImageIo->SetIORegion(ioRegion);
172 nrrdImageIo->SetFileName(path);
178 sprintf(keybuffer,
"modality");
179 sprintf(valbuffer,
"org.mitk.image.multilabel");
180 itk::EncapsulateMetaData<std::string>(
181 nrrdImageIo->GetMetaDataDictionary(), std::string(keybuffer), std::string(valbuffer));
183 sprintf(keybuffer,
"layers");
184 sprintf(valbuffer,
"%1d", input->GetNumberOfLayers());
185 itk::EncapsulateMetaData<std::string>(
186 nrrdImageIo->GetMetaDataDictionary(), std::string(keybuffer), std::string(valbuffer));
188 for (
unsigned int layerIdx = 0; layerIdx < input->GetNumberOfLayers(); layerIdx++)
190 sprintf(keybuffer,
"layer_%03d", layerIdx);
191 sprintf(valbuffer,
"%1d", input->GetNumberOfLabels(layerIdx));
192 itk::EncapsulateMetaData<std::string>(
193 nrrdImageIo->GetMetaDataDictionary(), std::string(keybuffer), std::string(valbuffer));
196 unsigned int count(0);
197 while (iter != input->GetLabelSet(layerIdx)->IteratorConstEnd())
199 std::unique_ptr<TiXmlDocument> document;
200 document.reset(
new TiXmlDocument());
202 TiXmlDeclaration *decl =
new TiXmlDeclaration(
"1.0",
"",
"");
203 document->LinkEndChild(decl);
205 document->LinkEndChild(labelElem);
206 TiXmlPrinter printer;
207 printer.SetIndent(
"");
208 printer.SetLineBreak(
"");
210 document->Accept(&printer);
212 sprintf(keybuffer,
"org.mitk.label_%03u_%05u", layerIdx, count);
213 itk::EncapsulateMetaData<std::string>(
214 nrrdImageIo->GetMetaDataDictionary(), std::string(keybuffer), printer.Str());
222 nrrdImageIo->Write(imageAccess.
GetData());
224 catch (
const std::exception &e)
237 io->SetFileName(fileName);
238 io->ReadImageInformation();
240 itk::MetaDataDictionary imgMetaDataDictionary = io->GetMetaDataDictionary();
241 std::string value(
"");
242 itk::ExposeMetaData<std::string>(imgMetaDataDictionary,
"modality", value);
243 if (value.compare(
"org.mitk.image.multilabel") == 0)
259 const unsigned int MINDIM = 2;
260 const unsigned int MAXDIM = 4;
264 MITK_INFO <<
"loading " << path <<
" via itk::ImageIOFactory... " << std::endl;
269 mitkThrow() <<
"Empty filename in mitk::ItkImageIO ";
274 nrrdImageIO->SetFileName(path);
275 nrrdImageIO->ReadImageInformation();
277 unsigned int ndim = nrrdImageIO->GetNumberOfDimensions();
278 if (ndim < MINDIM || ndim > MAXDIM)
280 MITK_WARN <<
"Sorry, only dimensions 2, 3 and 4 are supported. The given file has " << ndim
281 <<
" dimensions! Reading as 4D.";
285 itk::ImageIORegion ioRegion(ndim);
286 itk::ImageIORegion::SizeType ioSize = ioRegion.GetSize();
287 itk::ImageIORegion::IndexType ioStart = ioRegion.GetIndex();
289 unsigned int dimensions[MAXDIM];
305 for (i = 0; i < ndim; ++i)
308 ioSize[i] = nrrdImageIO->GetDimensions(i);
311 dimensions[i] = nrrdImageIO->GetDimensions(i);
312 spacing[i] = nrrdImageIO->GetSpacing(i);
318 origin[i] = nrrdImageIO->GetOrigin(i);
322 ioRegion.SetSize(ioSize);
323 ioRegion.SetIndex(ioStart);
325 MITK_INFO <<
"ioRegion: " << ioRegion << std::endl;
326 nrrdImageIO->SetIORegion(ioRegion);
327 void *buffer =
new unsigned char[nrrdImageIO->GetImageSizeInBytes()];
328 nrrdImageIO->Read(buffer);
330 image->Initialize(
MakePixelType(nrrdImageIO), ndim, dimensions);
335 matrix.SetIdentity();
336 unsigned int j, itkDimMax3 = (ndim >= 3 ? 3 : ndim);
337 for (i = 0; i < itkDimMax3; ++i)
338 for (j = 0; j < itkDimMax3; ++j)
339 matrix[i][j] = nrrdImageIO->GetDirection(j)[i];
342 PlaneGeometry *planeGeometry = image->GetSlicedGeometry(0)->GetPlaneGeometry(0);
356 timeGeometry->Initialize(slicedGeometry, image->GetDimension(3));
357 image->SetTimeGeometry(timeGeometry);
360 MITK_INFO <<
"number of image components: " << image->GetPixelType().GetNumberOfComponents() << std::endl;
362 const itk::MetaDataDictionary &dictionary = nrrdImageIO->GetMetaDataDictionary();
363 for (itk::MetaDataDictionary::ConstIterator iter = dictionary.Begin(), iterEnd = dictionary.End(); iter != iterEnd;
366 std::string key = std::string(
"meta.") + iter->first;
367 if (iter->second->GetMetaDataObjectTypeInfo() ==
typeid(std::string))
370 dynamic_cast<itk::MetaDataObject<std::string> *
>(iter->second.GetPointer())->GetMetaDataObjectValue();
382 unsigned int numberOfLayers =
GetIntByKey(dictionary,
"layers");
386 for (
unsigned int layerIdx = 0; layerIdx < numberOfLayers; layerIdx++)
388 sprintf(keybuffer,
"layer_%03d", layerIdx);
389 int numberOfLabels =
GetIntByKey(dictionary, keybuffer);
393 for (
int labelIdx = 0; labelIdx < numberOfLabels; labelIdx++)
396 sprintf(keybuffer,
"label_%03d_%05d", layerIdx, labelIdx);
398 doc.Parse(_xmlStr.c_str());
400 TiXmlElement *labelElem = doc.FirstChildElement(
"Label");
402 mitkThrow() <<
"Error parsing NRRD header for mitk::LabelSetImage IO";
406 if (label->GetValue() == 0)
407 output->SetExteriorLabel(label);
408 labelSet->AddLabel(label);
409 labelSet->SetLayer(layerIdx);
411 output->AddLabelSetToLayer(layerIdx, labelSet);
414 MITK_INFO <<
"...finished!" << std::endl;
416 std::vector<BaseData::Pointer> result;
417 result.push_back(output.GetPointer());
423 std::vector<std::string> imgMetaKeys = dic.GetKeys();
424 std::vector<std::string>::const_iterator itKey = imgMetaKeys.begin();
425 std::string metaString(
"");
426 for (; itKey != imgMetaKeys.end(); itKey++)
428 itk::ExposeMetaData<std::string>(dic, *itKey, metaString);
429 if (itKey->find(str.c_str()) != std::string::npos)
431 return atoi(metaString.c_str());
439 std::vector<std::string> imgMetaKeys = dic.GetKeys();
440 std::vector<std::string>::const_iterator itKey = imgMetaKeys.begin();
441 std::string metaString(
"");
442 for (; itKey != imgMetaKeys.end(); itKey++)
444 itk::ExposeMetaData<std::string>(dic, *itKey, metaString);
445 if (itKey->find(str.c_str()) != std::string::npos)
456 #endif //__mitkLabelSetImageWriter__cpp
MITKMULTILABEL_EXPORT Image::Pointer ConvertLabelSetImageToImage(LabelSetImage::ConstPointer labelSetImage)
Convert mitk::LabelSetImage to mitk::Image (itk::VectorImage)
itk::SmartPointer< Self > Pointer
void SetSpacing(const mitk::Vector3D &aSpacing, bool enforceSetSpacing=false)
Set the spacing (m_Spacing).
static itk::SmartPointer< mitk::Label > LoadLabelFromTiXmlDocument(TiXmlElement *labelElem)
Creates a mitk::Label from a TiXmlElement.
virtual ConfidenceLevel GetReaderConfidenceLevel() const override
std::string GetFileName()
MITKMULTILABEL_EXPORT LabelSetImage::Pointer ConvertImageToLabelSetImage(Image::Pointer image)
Convert mitk::Image to mitk::LabelSetImage, templating and differentation between itk::Image and itk:...
int GetIntByKey(const itk::MetaDataDictionary &dic, const std::string &str)
std::string GetStringByKey(const itk::MetaDataDictionary &dic, const std::string &str)
const void * GetData() const
Gives const access to the data.
DataCollection - Class to facilitate loading/accessing structured data.
void ValidateOutputLocation() const
itk::ImageIOBase::IOPixelType GetPixelType() const
virtual void Write() override
Write the base data to the specified location or output stream.
std::string GetLocalFileName() const
Get a local file name for reading.
virtual void InitializeEvenlySpaced(mitk::PlaneGeometry *geometry2D, unsigned int slices)
Completely initialize this instance as evenly-spaced with slices parallel to the provided PlaneGeomet...
static const int PixelComponentUserType
void SetRanking(int ranking)
Set the service ranking for this file writer.
virtual ConfidenceLevel GetReaderConfidenceLevel() const override
MITKCORE_EXPORT mitk::PixelType MakePixelType(vtkImageData *vtkimagedata)
deduct the PixelType for a given vtk image
Convenience class to temporarily change the current locale.
std::pair< us::ServiceRegistration< IFileReader >, us::ServiceRegistration< IFileWriter > > RegisterService(us::ModuleContext *context=us::GetModuleContext())
void SetOrigin(const Point3D &origin)
Set the origin, i.e. the upper-left corner of the plane.
virtual const BaseData * GetInput() const override
Get the input data set via SetInput().
virtual ConfidenceLevel GetWriterConfidenceLevel() const override
static const char * GetStaticNameOfClass()
A local file representation for streams.
int GetComponentType() const
Get the component type (the scalar (!) type). Each element may contain m_NumberOfComponents (more tha...
LabelContainerType::const_iterator LabelContainerConstIteratorType
Point3D GetCornerPoint(int id) const
Get the position of the corner number id (in world coordinates)
Describes the geometry of a data object consisting of slices.
void SetRanking(int ranking)
Set the service ranking for this file reader.
static TiXmlElement * GetLabelAsTiXmlElement(Label *label)
Creates a TiXmlElement from a mitk::Label.
vcl_size_t GetNumberOfComponents() const
Get the number of components of which each element consists.
LabelSetImage class for handling labels and layers in a segmentation session.
ConfidenceLevel
A confidence level describing the confidence of the reader or writer in handling the given data...
virtual ConfidenceLevel GetWriterConfidenceLevel() const override
Describes a two-dimensional, rectangular plane.
virtual std::vector< BaseData::Pointer > Read() override
Reads a number of mitk::LabelSetImages from the file system.
ImageReadAccessor class to get locked read access for a particular image part.
Abstract class for implementing a reader and writer.
Class for defining the data type of pixels.
mitk::AffineTransform3D * GetIndexToWorldTransform()
Get the transformation used to convert from index to world coordinates.
static itkEventMacro(BoundingShapeInteractionEvent, itk::AnyEvent) class MITKBOUNDINGSHAPE_EXPORT BoundingShapeInteractor Pointer New()
Basic interaction methods for mitk::GeometryData.