diff --git a/Modules/DiffusionImaging/DiffusionIO/files.cmake b/Modules/DiffusionImaging/DiffusionIO/files.cmake index 1422e03ba4..92e14187be 100644 --- a/Modules/DiffusionImaging/DiffusionIO/files.cmake +++ b/Modules/DiffusionImaging/DiffusionIO/files.cmake @@ -1,41 +1,40 @@ set(CPP_FILES mitkDiffusionModuleActivator.cpp mitkNrrdTbssImageWriterFactory.cpp #mitkFiberBundleXIOFactory.cpp - mitkConnectomicsNetworkIOFactory.cpp mitkConnectomicsNetworkReader.cpp mitkConnectomicsNetworkWriter.cpp mitkConnectomicsNetworkSerializer.cpp mitkConnectomicsNetworkDefinitions.cpp mitkNrrdTbssRoiImageIOFactory.cpp #mitkFiberBundleXWriterFactory.cpp - mitkConnectomicsNetworkWriterFactory.cpp mitkNrrdTbssRoiImageWriterFactory.cpp mitkNrrdTensorImageReader.cpp mitkNrrdTensorImageWriter.cpp - mitkNrrdTensorImageIOFactory.cpp - mitkNrrdTensorImageWriterFactory.cpp mitkTensorImageSerializer.cpp mitkTensorImageSource.cpp mitkFiberTrackingObjectFactory.cpp mitkConnectomicsObjectFactory.cpp mitkQuantificationObjectFactory.cpp mitkNrrdTbssImageIOFactory.cpp mitkDiffusionCoreObjectFactory.cpp + mitkDiffusionIOMimeTypes.cpp + mitkNrrdDiffusionImageReader.cpp - mitkNrrdDiffusionImageIOFactory.cpp +# mitkNrrdDiffusionImageIOFactory.cpp mitkNrrdDiffusionImageWriterFactory.cpp mitkDiffusionImageSerializer.cpp mitkNrrdQBallImageReader.cpp mitkNrrdQBallImageWriter.cpp - mitkNrrdQBallImageIOFactory.cpp - mitkNrrdQBallImageWriterFactory.cpp mitkQBallImageSerializer.cpp + mitkFiberBundleXReader.cpp + mitkFiberBundleXWriter.cpp + mitkFiberBundleXSerializer.cpp mitkFiberBundleXMapper2D.cpp mitkFiberBundleXMapper3D.cpp mitkCompositeMapper.cpp ) diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkConnectomicsNetworkIOFactory.cpp b/Modules/DiffusionImaging/DiffusionIO/mitkConnectomicsNetworkIOFactory.cpp deleted file mode 100644 index 98c49d5b01..0000000000 --- a/Modules/DiffusionImaging/DiffusionIO/mitkConnectomicsNetworkIOFactory.cpp +++ /dev/null @@ -1,51 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "mitkConnectomicsNetworkIOFactory.h" -#include "mitkIOAdapter.h" -#include "mitkConnectomicsNetworkReader.h" - -#include "itkVersion.h" - - -namespace mitk -{ - -ConnectomicsNetworkIOFactory::ConnectomicsNetworkIOFactory() -{ - typedef ConnectomicsNetworkReader ConnectomicsNetworkReaderType; - this->RegisterOverride("mitkIOAdapter", //beibehalten - "mitkConnectomicsNetworkReader", //umbenennen - "Connectomics Network IO", //angezeigter name - 1, - itk::CreateObjectFunction >::New()); -} - -ConnectomicsNetworkIOFactory::~ConnectomicsNetworkIOFactory() -{ -} - -const char* ConnectomicsNetworkIOFactory::GetITKSourceVersion() const -{ - return ITK_SOURCE_VERSION; -} - -const char* ConnectomicsNetworkIOFactory::GetDescription() const -{ - return "ConnectomicsNetworkIOFactory, allows the loading of Connectomics Networks"; -} - -} // end namespace mitk diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkConnectomicsNetworkIOFactory.h b/Modules/DiffusionImaging/DiffusionIO/mitkConnectomicsNetworkIOFactory.h deleted file mode 100644 index 89476ea29f..0000000000 --- a/Modules/DiffusionImaging/DiffusionIO/mitkConnectomicsNetworkIOFactory.h +++ /dev/null @@ -1,63 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ -#ifndef __MITK_CONNECTOMICS_NETWORK_IO_FACTORY_H_HEADER__ -#define __MITK_CONNECTOMICS_NETWORK_IO_FACTORY_H_HEADER__ - -#ifdef _MSC_VER -#pragma warning ( disable : 4786 ) -#endif - -#include "itkObjectFactoryBase.h" -#include "mitkBaseData.h" - -namespace mitk -{ - /** - * \brief Create instances of ConnectomicsNetwork objects using an object factory. - */ -class ConnectomicsNetworkIOFactory : public itk::ObjectFactoryBase -{ -public: - /** Standard class typedefs. */ - typedef ConnectomicsNetworkIOFactory Self; - typedef itk::ObjectFactoryBase Superclass; - typedef itk::SmartPointer Pointer; - typedef itk::SmartPointer ConstPointer; - - /** Class methods used to interface with the registered factories. */ - virtual const char* GetITKSourceVersion(void) const; - virtual const char* GetDescription(void) const; - - /** Method for class instantiation. */ - itkFactorylessNewMacro(Self); - static ConnectomicsNetworkIOFactory* FactoryNew() { return new ConnectomicsNetworkIOFactory;} - /** Run-time type information (and related methods). */ - itkTypeMacro(ConnectomicsNetworkIOFactory, ObjectFactoryBase); - -protected: - ConnectomicsNetworkIOFactory(); - ~ConnectomicsNetworkIOFactory(); - -private: - ConnectomicsNetworkIOFactory(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - -}; - - -} // end namespace mitk - -#endif // __MITK_CONNECTOMICS_NETWORK_IO_FACTORY_H_HEADER__ diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkConnectomicsNetworkReader.cpp b/Modules/DiffusionImaging/DiffusionIO/mitkConnectomicsNetworkReader.cpp index ac302f1fee..8b1465d9d2 100644 --- a/Modules/DiffusionImaging/DiffusionIO/mitkConnectomicsNetworkReader.cpp +++ b/Modules/DiffusionImaging/DiffusionIO/mitkConnectomicsNetworkReader.cpp @@ -1,276 +1,214 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkConnectomicsNetworkReader.h" #include "mitkConnectomicsNetworkDefinitions.h" #include #include "itksys/SystemTools.hxx" #include #include "mitkGeometry3D.h" +#include +#include "mitkDiffusionIOMimeTypes.h" -void mitk::ConnectomicsNetworkReader::GenerateData() +namespace mitk { - MITK_INFO << "Reading connectomics network"; - if ( ( ! m_OutputCache ) ) + + ConnectomicsNetworkReader::ConnectomicsNetworkReader(const ConnectomicsNetworkReader& other) + : mitk::AbstractFileReader(other) { - Superclass::SetNumberOfRequiredOutputs(0); - this->GenerateOutputInformation(); } - if (!m_OutputCache) + ConnectomicsNetworkReader::ConnectomicsNetworkReader() + : mitk::AbstractFileReader( CustomMimeType( mitk::DiffusionIOMimeTypes::CONNECTOMICS_MIMETYPE_NAME() ), mitk::DiffusionIOMimeTypes::CONNECTOMICS_MIMETYPE_DESCRIPTION ) { - itkWarningMacro("Tree cache is empty!"); + m_ServiceReg = this->RegisterService(); } - - Superclass::SetNumberOfRequiredOutputs(1); - Superclass::SetNthOutput(0, m_OutputCache.GetPointer()); -} - -void mitk::ConnectomicsNetworkReader::GenerateOutputInformation() -{ - m_OutputCache = OutputType::New(); - - std::string ext = itksys::SystemTools::GetFilenameLastExtension(m_FileName); - ext = itksys::SystemTools::LowerCase(ext); - - if ( m_FileName == "") + ConnectomicsNetworkReader::~ConnectomicsNetworkReader() { - MITK_ERROR << "No file name specified."; } - else if (ext == ".cnf") + + std::vector > ConnectomicsNetworkReader::Read() { - try + std::vector > result; + std::string location = GetInputLocation(); + + std::string ext = itksys::SystemTools::GetFilenameLastExtension(location); + ext = itksys::SystemTools::LowerCase(ext); + + if ( location == "") { - TiXmlDocument doc( m_FileName ); - bool loadOkay = doc.LoadFile(); - if(!loadOkay) + MITK_ERROR << "No file name specified."; + } + else if (ext == ".cnf") + { + try { - mitkThrow() << "Could not open file " << m_FileName << " for reading."; - } + mitk::ConnectomicsNetwork::Pointer outputNetwork = mitk::ConnectomicsNetwork::New(); - TiXmlHandle hDoc(&doc); - TiXmlElement* pElem; - TiXmlHandle hRoot(0); - - pElem = hDoc.FirstChildElement().Element(); - - // save this for later - hRoot = TiXmlHandle(pElem); - - pElem = hRoot.FirstChildElement(mitk::ConnectomicsNetworkDefinitions::XML_GEOMETRY).Element(); - - // read geometry - mitk::Geometry3D::Pointer geometry = mitk::Geometry3D::New(); - - // read origin - mitk::Point3D origin; - double temp = 0; - pElem->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_ORIGIN_X, &temp); - origin[0] = temp; - pElem->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_ORIGIN_Y, &temp); - origin[1] = temp; - pElem->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_ORIGIN_Z, &temp); - origin[2] = temp; - geometry->SetOrigin(origin); - - // read spacing - ScalarType spacing[3]; - pElem->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_SPACING_X, &temp); - spacing[0] = temp; - pElem->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_SPACING_Y, &temp); - spacing[1] = temp; - pElem->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_SPACING_Z, &temp); - spacing[2] = temp; - geometry->SetSpacing(spacing); - - // read transform - vtkMatrix4x4* m = vtkMatrix4x4::New(); - pElem->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_MATRIX_XX, &temp); - m->SetElement(0,0,temp); - pElem->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_MATRIX_XY, &temp); - m->SetElement(1,0,temp); - pElem->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_MATRIX_XZ, &temp); - m->SetElement(2,0,temp); - pElem->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_MATRIX_YX, &temp); - m->SetElement(0,1,temp); - pElem->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_MATRIX_YY, &temp); - m->SetElement(1,1,temp); - pElem->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_MATRIX_YZ, &temp); - m->SetElement(2,1,temp); - pElem->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_MATRIX_ZX, &temp); - m->SetElement(0,2,temp); - pElem->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_MATRIX_ZY, &temp); - m->SetElement(1,2,temp); - pElem->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_MATRIX_ZZ, &temp); - m->SetElement(2,2,temp); - - m->SetElement(0,3,origin[0]); - m->SetElement(1,3,origin[1]); - m->SetElement(2,3,origin[2]); - m->SetElement(3,3,1); - geometry->SetIndexToWorldTransformByVtkMatrix(m); - - geometry->SetImageGeometry(true); - m_OutputCache->SetGeometry(geometry); - - // read network - std::map< int, mitk::ConnectomicsNetwork::VertexDescriptorType > idToVertexMap; - // read vertices - pElem = hRoot.FirstChildElement(mitk::ConnectomicsNetworkDefinitions::XML_VERTICES).Element(); - { - // walk through the vertices - TiXmlElement* vertexElement = pElem->FirstChildElement(); + TiXmlDocument doc( location ); + bool loadOkay = doc.LoadFile(); + if(!loadOkay) + { + mitkThrow() << "Could not open file " << location << " for reading."; + } - for( ; vertexElement; vertexElement=vertexElement->NextSiblingElement()) + TiXmlHandle hDoc(&doc); + TiXmlElement* pElem; + TiXmlHandle hRoot(0); + + pElem = hDoc.FirstChildElement().Element(); + + // save this for later + hRoot = TiXmlHandle(pElem); + + pElem = hRoot.FirstChildElement(mitk::ConnectomicsNetworkDefinitions::XML_GEOMETRY).Element(); + + // read geometry + mitk::Geometry3D::Pointer geometry = mitk::Geometry3D::New(); + + // read origin + mitk::Point3D origin; + double temp = 0; + pElem->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_ORIGIN_X, &temp); + origin[0] = temp; + pElem->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_ORIGIN_Y, &temp); + origin[1] = temp; + pElem->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_ORIGIN_Z, &temp); + origin[2] = temp; + geometry->SetOrigin(origin); + + // read spacing + ScalarType spacing[3]; + pElem->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_SPACING_X, &temp); + spacing[0] = temp; + pElem->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_SPACING_Y, &temp); + spacing[1] = temp; + pElem->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_SPACING_Z, &temp); + spacing[2] = temp; + geometry->SetSpacing(spacing); + + // read transform + vtkMatrix4x4* m = vtkMatrix4x4::New(); + pElem->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_MATRIX_XX, &temp); + m->SetElement(0,0,temp); + pElem->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_MATRIX_XY, &temp); + m->SetElement(1,0,temp); + pElem->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_MATRIX_XZ, &temp); + m->SetElement(2,0,temp); + pElem->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_MATRIX_YX, &temp); + m->SetElement(0,1,temp); + pElem->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_MATRIX_YY, &temp); + m->SetElement(1,1,temp); + pElem->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_MATRIX_YZ, &temp); + m->SetElement(2,1,temp); + pElem->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_MATRIX_ZX, &temp); + m->SetElement(0,2,temp); + pElem->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_MATRIX_ZY, &temp); + m->SetElement(1,2,temp); + pElem->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_MATRIX_ZZ, &temp); + m->SetElement(2,2,temp); + + m->SetElement(0,3,origin[0]); + m->SetElement(1,3,origin[1]); + m->SetElement(2,3,origin[2]); + m->SetElement(3,3,1); + geometry->SetIndexToWorldTransformByVtkMatrix(m); + + geometry->SetImageGeometry(true); + outputNetwork->SetGeometry(geometry); + + // read network + std::map< int, mitk::ConnectomicsNetwork::VertexDescriptorType > idToVertexMap; + // read vertices + pElem = hRoot.FirstChildElement(mitk::ConnectomicsNetworkDefinitions::XML_VERTICES).Element(); { - std::vector< float > pos; - std::string label; - int vertexID(0); - - vertexElement->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_VERTEX_X, &temp); - pos.push_back(temp); - vertexElement->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_VERTEX_Y, &temp); - pos.push_back(temp); - vertexElement->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_VERTEX_Z, &temp); - pos.push_back(temp); - vertexElement->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_VERTEX_ID, &vertexID); - vertexElement->QueryStringAttribute(mitk::ConnectomicsNetworkDefinitions::XML_VERTEX_LABEL, &label); - - mitk::ConnectomicsNetwork::VertexDescriptorType newVertex = m_OutputCache->AddVertex( vertexID ); - m_OutputCache->SetLabel( newVertex, label ); - m_OutputCache->SetCoordinates( newVertex, pos ); - - if ( idToVertexMap.count( vertexID ) > 0 ) + // walk through the vertices + TiXmlElement* vertexElement = pElem->FirstChildElement(); + + for( ; vertexElement; vertexElement=vertexElement->NextSiblingElement()) { - MITK_ERROR << "Aborting network creation, duplicate vertex ID in file."; - return; + std::vector< float > pos; + std::string label; + int vertexID(0); + + vertexElement->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_VERTEX_X, &temp); + pos.push_back(temp); + vertexElement->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_VERTEX_Y, &temp); + pos.push_back(temp); + vertexElement->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_VERTEX_Z, &temp); + pos.push_back(temp); + vertexElement->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_VERTEX_ID, &vertexID); + vertexElement->QueryStringAttribute(mitk::ConnectomicsNetworkDefinitions::XML_VERTEX_LABEL, &label); + + mitk::ConnectomicsNetwork::VertexDescriptorType newVertex = outputNetwork->AddVertex( vertexID ); + outputNetwork->SetLabel( newVertex, label ); + outputNetwork->SetCoordinates( newVertex, pos ); + + if ( idToVertexMap.count( vertexID ) > 0 ) + { + MITK_ERROR << "Aborting network creation, duplicate vertex ID in file."; + return result; + } + idToVertexMap.insert( std::pair< int, mitk::ConnectomicsNetwork::VertexDescriptorType >( vertexID, newVertex) ); } - idToVertexMap.insert( std::pair< int, mitk::ConnectomicsNetwork::VertexDescriptorType >( vertexID, newVertex) ); } - } - // read edges - pElem = hRoot.FirstChildElement(mitk::ConnectomicsNetworkDefinitions::XML_EDGES).Element(); - { - // walk through the edges - TiXmlElement* edgeElement = pElem->FirstChildElement(); - - for( ; edgeElement; edgeElement=edgeElement->NextSiblingElement()) + // read edges + pElem = hRoot.FirstChildElement(mitk::ConnectomicsNetworkDefinitions::XML_EDGES).Element(); { - int edgeID(0), edgeSourceID(0), edgeTargetID(0), edgeWeight(0); + // walk through the edges + TiXmlElement* edgeElement = pElem->FirstChildElement(); + + for( ; edgeElement; edgeElement=edgeElement->NextSiblingElement()) + { + int edgeID(0), edgeSourceID(0), edgeTargetID(0), edgeWeight(0); - edgeElement->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_EDGE_ID, &edgeID); - edgeElement->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_EDGE_SOURCE_ID, &edgeSourceID); - edgeElement->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_EDGE_TARGET_ID, &edgeTargetID); - edgeElement->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_EDGE_WEIGHT_ID, &edgeWeight); + edgeElement->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_EDGE_ID, &edgeID); + edgeElement->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_EDGE_SOURCE_ID, &edgeSourceID); + edgeElement->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_EDGE_TARGET_ID, &edgeTargetID); + edgeElement->Attribute(mitk::ConnectomicsNetworkDefinitions::XML_EDGE_WEIGHT_ID, &edgeWeight); - mitk::ConnectomicsNetwork::VertexDescriptorType source = idToVertexMap.find( edgeSourceID )->second; - mitk::ConnectomicsNetwork::VertexDescriptorType target = idToVertexMap.find( edgeTargetID )->second; - m_OutputCache->AddEdge( source, target, edgeSourceID, edgeTargetID, edgeWeight); + mitk::ConnectomicsNetwork::VertexDescriptorType source = idToVertexMap.find( edgeSourceID )->second; + mitk::ConnectomicsNetwork::VertexDescriptorType target = idToVertexMap.find( edgeTargetID )->second; + outputNetwork->AddEdge( source, target, edgeSourceID, edgeTargetID, edgeWeight); + } } - } - m_OutputCache->UpdateBounds(); - MITK_INFO << "Network read"; - } - catch (mitk::Exception e) - { - MITK_ERROR << e.GetDescription(); - } - catch(...) - { - MITK_ERROR << "Unknown error occured while trying to read file."; + outputNetwork->UpdateBounds(); + result.push_back(outputNetwork.GetPointer()); + MITK_INFO << "Network read"; + } + catch (mitk::Exception e) + { + MITK_ERROR << e.GetDescription(); + } + catch(...) + { + MITK_ERROR << "Unknown error occured while trying to read file."; + } } - } -} -void mitk::ConnectomicsNetworkReader::Update() -{ - this->GenerateData(); -} - -const char* mitk::ConnectomicsNetworkReader::GetFileName() const -{ - return m_FileName.c_str(); -} - - -void mitk::ConnectomicsNetworkReader::SetFileName(const char* aFileName) -{ - m_FileName = aFileName; -} - - -const char* mitk::ConnectomicsNetworkReader::GetFilePrefix() const -{ - return m_FilePrefix.c_str(); -} - - -void mitk::ConnectomicsNetworkReader::SetFilePrefix(const char* aFilePrefix) -{ - m_FilePrefix = aFilePrefix; -} - - -const char* mitk::ConnectomicsNetworkReader::GetFilePattern() const -{ - return m_FilePattern.c_str(); -} - - -void mitk::ConnectomicsNetworkReader::SetFilePattern(const char* aFilePattern) -{ - m_FilePattern = aFilePattern; -} - - -bool mitk::ConnectomicsNetworkReader::CanReadFile( - const std::string filename, const std::string /*filePrefix*/, - const std::string /*filePattern*/) -{ - // First check the extension - if( filename == "" ) - { - return false; + return result; } - std::string ext = itksys::SystemTools::GetFilenameLastExtension(filename); - ext = itksys::SystemTools::LowerCase(ext); - if (ext == ".cnf") - { - return true; - } - return false; -} +} //namespace MITK -mitk::BaseDataSource::DataObjectPointer mitk::ConnectomicsNetworkReader::MakeOutput(const DataObjectIdentifierType &name) +mitk::ConnectomicsNetworkReader* mitk::ConnectomicsNetworkReader::Clone() const { - itkDebugMacro("MakeOutput(" << name << ")"); - if( this->IsIndexedOutputName(name) ) - { - return this->MakeOutput( this->MakeIndexFromOutputName(name) ); - } - return static_cast(OutputType::New().GetPointer()); + return new ConnectomicsNetworkReader(*this); } - -mitk::BaseDataSource::DataObjectPointer mitk::ConnectomicsNetworkReader::MakeOutput(DataObjectPointerArraySizeType /*idx*/) -{ - return OutputType::New().GetPointer(); -} - diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkConnectomicsNetworkReader.h b/Modules/DiffusionImaging/DiffusionIO/mitkConnectomicsNetworkReader.h index 00218ee23a..f8e550746c 100644 --- a/Modules/DiffusionImaging/DiffusionIO/mitkConnectomicsNetworkReader.h +++ b/Modules/DiffusionImaging/DiffusionIO/mitkConnectomicsNetworkReader.h @@ -1,74 +1,53 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef __mitkConnectomicsNetworkReader_h #define __mitkConnectomicsNetworkReader_h #include "mitkCommon.h" -#include "mitkFileReader.h" +#include +#include +#include #include "mitkConnectomicsNetwork.h" namespace mitk { /** \brief The reader for connectomics network files (.cnf) */ - class ConnectomicsNetworkReader : public FileReader, public BaseDataSource + class ConnectomicsNetworkReader : public mitk::AbstractFileReader { public: - typedef mitk::ConnectomicsNetwork OutputType; - mitkClassMacro( ConnectomicsNetworkReader, BaseDataSource ); - itkFactorylessNewMacro(Self) - itkCloneMacro(Self) - - const char* GetFileName() const; - void SetFileName(const char* aFileName); - const char* GetFilePrefix() const; - void SetFilePrefix(const char* aFilePrefix); - const char* GetFilePattern() const; - void SetFilePattern(const char* aFilePattern); - - static bool CanReadFile(const std::string filename, const std::string filePrefix, const std::string filePattern); - - virtual void Update(); - - BaseDataSource::DataObjectPointer MakeOutput(const DataObjectIdentifierType &name); + ConnectomicsNetworkReader(const ConnectomicsNetworkReader& other); + ConnectomicsNetworkReader(); + virtual ~ConnectomicsNetworkReader(); - BaseDataSource::DataObjectPointer MakeOutput( DataObjectPointerArraySizeType idx); - - protected: - - /** Does the real work. */ - virtual void GenerateData(); - virtual void GenerateOutputInformation(); - - OutputType::Pointer m_OutputCache; - - std::string m_FileName; - std::string m_FilePrefix; - std::string m_FilePattern; + using AbstractFileReader::Read; + virtual std::vector > Read(); private: - void operator=(const Self&); //purposely not implemented + ConnectomicsNetworkReader* Clone() const; + + us::ServiceRegistration m_ServiceReg; }; } //namespace MITK #endif // __mitkConnectomicsNetworkReader_h diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkConnectomicsNetworkSerializer.cpp b/Modules/DiffusionImaging/DiffusionIO/mitkConnectomicsNetworkSerializer.cpp index c06d8f1b77..0a53f86f09 100644 --- a/Modules/DiffusionImaging/DiffusionIO/mitkConnectomicsNetworkSerializer.cpp +++ b/Modules/DiffusionImaging/DiffusionIO/mitkConnectomicsNetworkSerializer.cpp @@ -1,74 +1,74 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkConnectomicsNetworkSerializer.h" #include "mitkConnectomicsNetwork.h" #include "mitkConnectomicsNetworkWriter.h" #include MITK_REGISTER_SERIALIZER(ConnectomicsNetworkSerializer) mitk::ConnectomicsNetworkSerializer::ConnectomicsNetworkSerializer() { } mitk::ConnectomicsNetworkSerializer::~ConnectomicsNetworkSerializer() { } std::string mitk::ConnectomicsNetworkSerializer::Serialize() { const ConnectomicsNetwork* conNet = dynamic_cast( m_Data.GetPointer() ); if (conNet == NULL) { MITK_ERROR << " Object at " << (const void*) this->m_Data << " is not an mitk::ConnectomicsNetwork. Cannot serialize as ConnectomicsNetwork."; return ""; } std::string filename( this->GetUniqueFilenameInWorkingDirectory() ); filename += "_"; filename += m_FilenameHint; filename += ".cnf"; std::string fullname(m_WorkingDirectory); fullname += "/"; fullname += itksys::SystemTools::ConvertToOutputPath(filename.c_str()); try { - ConnectomicsNetworkWriter::Pointer writer = ConnectomicsNetworkWriter::New(); - writer->SetFileName(fullname); - writer->SetInputConnectomicsNetwork(const_cast(conNet)); - writer->Write(); + ConnectomicsNetworkWriter writer; + writer.SetOutputLocation(fullname); + writer.SetInput(const_cast(conNet)); + writer.Write(); } catch (std::exception& e) { MITK_ERROR << " Error serializing object at " << (const void*) this->m_Data << " to " << fullname << ": " << e.what(); return ""; } return filename; } diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkConnectomicsNetworkWriter.cpp b/Modules/DiffusionImaging/DiffusionIO/mitkConnectomicsNetworkWriter.cpp index c082c6d90c..87dae9b2d3 100644 --- a/Modules/DiffusionImaging/DiffusionIO/mitkConnectomicsNetworkWriter.cpp +++ b/Modules/DiffusionImaging/DiffusionIO/mitkConnectomicsNetworkWriter.cpp @@ -1,162 +1,136 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkConnectomicsNetworkWriter.h" #include "mitkConnectomicsNetworkDefinitions.h" #include #include "itksys/SystemTools.hxx" +#include "mitkDiffusionIOMimeTypes.h" mitk::ConnectomicsNetworkWriter::ConnectomicsNetworkWriter() -: m_FileName(""), m_FilePrefix(""), m_FilePattern(""), m_Success(false) + : AbstractFileWriter(mitk::ConnectomicsNetwork::GetStaticNameOfClass(), CustomMimeType( mitk::DiffusionIOMimeTypes::CONNECTOMICS_MIMETYPE_NAME() ), mitk::DiffusionIOMimeTypes::CONNECTOMICS_MIMETYPE_DESCRIPTION ) +{ + RegisterService(); +} + +mitk::ConnectomicsNetworkWriter::ConnectomicsNetworkWriter(const mitk::ConnectomicsNetworkWriter& other) + : AbstractFileWriter(other) { - this->SetNumberOfRequiredInputs( 1 ); } mitk::ConnectomicsNetworkWriter::~ConnectomicsNetworkWriter() {} +mitk::ConnectomicsNetworkWriter* mitk::ConnectomicsNetworkWriter::Clone() const +{ + return new ConnectomicsNetworkWriter(*this); +} -void mitk::ConnectomicsNetworkWriter::GenerateData() +void mitk::ConnectomicsNetworkWriter::Write() { MITK_INFO << "Writing connectomics network"; - m_Success = false; - InputType* input = this->GetInput(); - if (input == NULL) + InputType::ConstPointer input = dynamic_cast(this->GetInput()); + if (input.IsNull() ) { - itkWarningMacro(<<"Sorry, input to ConnectomicsNetworkWriter is NULL!"); + MITK_ERROR <<"Sorry, input to ConnectomicsNetworkWriter is NULL!"; return; } - if ( m_FileName == "" ) + if ( this->GetOutputLocation().c_str() == "" ) { - itkWarningMacro( << "Sorry, filename has not been set!" ); + MITK_ERROR << "Sorry, filename has not been set!" ; return ; } - std::string ext = itksys::SystemTools::GetFilenameLastExtension(m_FileName); + std::string ext = itksys::SystemTools::GetFilenameLastExtension(this->GetOutputLocation()); ext = itksys::SystemTools::LowerCase(ext); if (ext == ".cnf") { // Get geometry of the network mitk::BaseGeometry* geometry = input->GetGeometry(); // Create XML document TiXmlDocument documentXML; { // begin document TiXmlDeclaration* declXML = new TiXmlDeclaration( "1.0", "", "" ); // TODO what to write here? encoding? etc.... documentXML.LinkEndChild( declXML ); TiXmlElement* mainXML = new TiXmlElement(mitk::ConnectomicsNetworkDefinitions::XML_CONNECTOMICS_FILE); mainXML->SetAttribute(mitk::ConnectomicsNetworkDefinitions::XML_FILE_VERSION, mitk::ConnectomicsNetworkDefinitions::VERSION_STRING); documentXML.LinkEndChild(mainXML); TiXmlElement* geometryXML = new TiXmlElement(mitk::ConnectomicsNetworkDefinitions::XML_GEOMETRY); { // begin geometry geometryXML->SetDoubleAttribute(mitk::ConnectomicsNetworkDefinitions::XML_MATRIX_XX, geometry->GetMatrixColumn(0)[0]); geometryXML->SetDoubleAttribute(mitk::ConnectomicsNetworkDefinitions::XML_MATRIX_XY, geometry->GetMatrixColumn(0)[1]); geometryXML->SetDoubleAttribute(mitk::ConnectomicsNetworkDefinitions::XML_MATRIX_XZ, geometry->GetMatrixColumn(0)[2]); geometryXML->SetDoubleAttribute(mitk::ConnectomicsNetworkDefinitions::XML_MATRIX_YX, geometry->GetMatrixColumn(1)[0]); geometryXML->SetDoubleAttribute(mitk::ConnectomicsNetworkDefinitions::XML_MATRIX_YY, geometry->GetMatrixColumn(1)[1]); geometryXML->SetDoubleAttribute(mitk::ConnectomicsNetworkDefinitions::XML_MATRIX_YZ, geometry->GetMatrixColumn(1)[2]); geometryXML->SetDoubleAttribute(mitk::ConnectomicsNetworkDefinitions::XML_MATRIX_ZX, geometry->GetMatrixColumn(2)[0]); geometryXML->SetDoubleAttribute(mitk::ConnectomicsNetworkDefinitions::XML_MATRIX_ZY, geometry->GetMatrixColumn(2)[1]); geometryXML->SetDoubleAttribute(mitk::ConnectomicsNetworkDefinitions::XML_MATRIX_ZZ, geometry->GetMatrixColumn(2)[2]); geometryXML->SetDoubleAttribute(mitk::ConnectomicsNetworkDefinitions::XML_ORIGIN_X, geometry->GetOrigin()[0]); geometryXML->SetDoubleAttribute(mitk::ConnectomicsNetworkDefinitions::XML_ORIGIN_Y, geometry->GetOrigin()[1]); geometryXML->SetDoubleAttribute(mitk::ConnectomicsNetworkDefinitions::XML_ORIGIN_Z, geometry->GetOrigin()[2]); geometryXML->SetDoubleAttribute(mitk::ConnectomicsNetworkDefinitions::XML_SPACING_X, geometry->GetSpacing()[0]); geometryXML->SetDoubleAttribute(mitk::ConnectomicsNetworkDefinitions::XML_SPACING_Y, geometry->GetSpacing()[1]); geometryXML->SetDoubleAttribute(mitk::ConnectomicsNetworkDefinitions::XML_SPACING_Z, geometry->GetSpacing()[2]); } // end geometry mainXML->LinkEndChild(geometryXML); TiXmlElement* verticesXML = new TiXmlElement(mitk::ConnectomicsNetworkDefinitions::XML_VERTICES); { // begin vertices section - VertexVectorType vertexVector = this->GetInput()->GetVectorOfAllNodes(); + VertexVectorType vertexVector = dynamic_cast(this->GetInput())->GetVectorOfAllNodes(); for( unsigned int index = 0; index < vertexVector.size(); index++ ) { // not localized as of yet TODO TiXmlElement* vertexXML = new TiXmlElement(mitk::ConnectomicsNetworkDefinitions::XML_VERTEX ); vertexXML->SetAttribute( mitk::ConnectomicsNetworkDefinitions::XML_VERTEX_ID , vertexVector[ index ].id ); vertexXML->SetAttribute( mitk::ConnectomicsNetworkDefinitions::XML_VERTEX_LABEL , vertexVector[ index ].label ); vertexXML->SetDoubleAttribute( mitk::ConnectomicsNetworkDefinitions::XML_VERTEX_X , vertexVector[ index ].coordinates[0] ); vertexXML->SetDoubleAttribute( mitk::ConnectomicsNetworkDefinitions::XML_VERTEX_Y , vertexVector[ index ].coordinates[1] ); vertexXML->SetDoubleAttribute( mitk::ConnectomicsNetworkDefinitions::XML_VERTEX_Z , vertexVector[ index ].coordinates[2] ); verticesXML->LinkEndChild(vertexXML); } } // end vertices section mainXML->LinkEndChild(verticesXML); TiXmlElement* edgesXML = new TiXmlElement(mitk::ConnectomicsNetworkDefinitions::XML_EDGES); { // begin edges section - EdgeVectorType edgeVector = this->GetInput()->GetVectorOfAllEdges(); + EdgeVectorType edgeVector = dynamic_cast(this->GetInput())->GetVectorOfAllEdges(); for(unsigned int index = 0; index < edgeVector.size(); index++ ) { TiXmlElement* edgeXML = new TiXmlElement(mitk::ConnectomicsNetworkDefinitions::XML_EDGE ); edgeXML->SetAttribute( mitk::ConnectomicsNetworkDefinitions::XML_EDGE_ID , index ); edgeXML->SetAttribute( mitk::ConnectomicsNetworkDefinitions::XML_EDGE_SOURCE_ID , edgeVector[ index ].second.sourceId ); edgeXML->SetAttribute( mitk::ConnectomicsNetworkDefinitions::XML_EDGE_TARGET_ID , edgeVector[ index ].second.targetId ); edgeXML->SetAttribute( mitk::ConnectomicsNetworkDefinitions::XML_EDGE_WEIGHT_ID , edgeVector[ index ].second.weight ); edgesXML->LinkEndChild(edgeXML); } } // end edges section mainXML->LinkEndChild(edgesXML); } // end document - documentXML.SaveFile( m_FileName ); - - m_Success = true; - + documentXML.SaveFile( this->GetOutputLocation().c_str() ); MITK_INFO << "Connectomics network written"; } } - - -void mitk::ConnectomicsNetworkWriter::SetInputConnectomicsNetwork( InputType* conNetwork ) -{ - this->ProcessObject::SetNthInput( 0, conNetwork ); -} - - -mitk::ConnectomicsNetwork* mitk::ConnectomicsNetworkWriter::GetInput() -{ - if ( this->GetNumberOfInputs() < 1 ) - { - return NULL; - } - else - { - return dynamic_cast ( this->ProcessObject::GetInput( 0 ) ); - } -} - - -std::vector mitk::ConnectomicsNetworkWriter::GetPossibleFileExtensions() -{ - std::vector possibleFileExtensions; - possibleFileExtensions.push_back(".cnf"); - return possibleFileExtensions; -} - -std::string mitk::ConnectomicsNetworkWriter::GetSupportedBaseData() const -{ - return InputType::GetStaticNameOfClass(); -} diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkConnectomicsNetworkWriter.h b/Modules/DiffusionImaging/DiffusionIO/mitkConnectomicsNetworkWriter.h index 2116f19aff..74cbf74258 100644 --- a/Modules/DiffusionImaging/DiffusionIO/mitkConnectomicsNetworkWriter.h +++ b/Modules/DiffusionImaging/DiffusionIO/mitkConnectomicsNetworkWriter.h @@ -1,159 +1,57 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef __mitkConnectomicsNetworkWriter_h #define __mitkConnectomicsNetworkWriter_h -#include -#include +#include #include "mitkConnectomicsNetwork.h" #include namespace mitk { /** * Writes connectomics networks to a file * @ingroup Process */ - class ConnectomicsNetworkWriter : public mitk::FileWriterWithInformation + class ConnectomicsNetworkWriter : public mitk::AbstractFileWriter { public: - - mitkClassMacro( ConnectomicsNetworkWriter, mitk::FileWriterWithInformation ); - - //mitkWriterMacro; - - virtual void Write() - { - if ( this->GetInput() == NULL ) - { - itkExceptionMacro(<<"Write:Please specify an input!"); - return; - } - /* Fill in image information.*/ - this->UpdateOutputInformation(); - (*(this->GetInputs().begin()))->SetRequestedRegionToLargestPossibleRegion(); - this->PropagateRequestedRegion(NULL); - this->UpdateOutputData(NULL); - } - - virtual void Update() - { - Write(); - } - - itkFactorylessNewMacro(Self) - itkCloneMacro(Self) - typedef mitk::ConnectomicsNetwork InputType; typedef std::vector< std::pair< std::pair< mitk::ConnectomicsNetwork::NetworkNode, mitk::ConnectomicsNetwork::NetworkNode > , mitk::ConnectomicsNetwork::NetworkEdge > > EdgeVectorType; typedef std::vector< mitk::ConnectomicsNetwork::NetworkNode > VertexVectorType; - /** - * Sets the filename of the file to write. - * @param _arg the name of the file to write. - */ - itkSetStringMacro( FileName ); - - /** - * @returns the name of the file to be written to disk. - */ - itkGetStringMacro( FileName ); - - /** - * @warning multiple write not (yet) supported - */ - itkSetStringMacro( FilePrefix ); - - /** - * @warning multiple write not (yet) supported - */ - itkGetStringMacro( FilePrefix ); - - /** - * @warning multiple write not (yet) supported - */ - itkSetStringMacro( FilePattern ); - - /** - * @warning multiple write not (yet) supported - */ - itkGetStringMacro( FilePattern ); - - /** - * Sets the input object for the filter. - * @param input the diffusion volumes to write to file. - */ - void SetInputConnectomicsNetwork( InputType* input ); - - /** - * @returns the 0'th input object of the filter. - */ - InputType* GetInput(); - - /** - * Returns false if an error happened during writing - */ - itkGetMacro( Success, bool ); - - /** - * @return possible file extensions for the data type associated with the writer - */ - virtual std::vector GetPossibleFileExtensions(); - - std::string GetSupportedBaseData() const; - - // FileWriterWithInformation methods - virtual const char * GetDefaultFilename() { return "ConnectomicsNetwork.cnf"; } - virtual const char * GetFileDialogPattern() { return "ConnectomicsNetwork (*.cnf)"; } - virtual const char * GetDefaultExtension() { return ".cnf"; } - virtual bool CanWriteBaseDataType(BaseData::Pointer data) { - return (dynamic_cast(data.GetPointer()) != NULL); } - - virtual void DoWrite(BaseData::Pointer data) { - if (CanWriteBaseDataType(data)) { - this->SetInputConnectomicsNetwork(dynamic_cast(data.GetPointer())); - this->Update(); - } - } - - - protected: - ConnectomicsNetworkWriter(); - virtual ~ConnectomicsNetworkWriter(); - virtual void GenerateData(); + using AbstractFileWriter::Write; + virtual void Write(); - std::string m_FileName; - - std::string m_FilePrefix; - - std::string m_FilePattern; + protected: - bool m_Success; + ConnectomicsNetworkWriter(const ConnectomicsNetworkWriter& other); + virtual mitk::ConnectomicsNetworkWriter* Clone() const; }; } // end of namespace mitk #endif //__mitkConnectomicsNetworkWriter_h diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkConnectomicsNetworkWriterFactory.cpp b/Modules/DiffusionImaging/DiffusionIO/mitkConnectomicsNetworkWriterFactory.cpp deleted file mode 100644 index 279a379bf3..0000000000 --- a/Modules/DiffusionImaging/DiffusionIO/mitkConnectomicsNetworkWriterFactory.cpp +++ /dev/null @@ -1,75 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "mitkConnectomicsNetworkWriterFactory.h" - -#include "itkCreateObjectFunction.h" -#include "itkVersion.h" - -#include "mitkConnectomicsNetworkWriter.h" - -namespace mitk -{ - -template -class CreateConnectomicsNetworkWriter : public itk::CreateObjectFunctionBase -{ -public: - - /** Standard class typedefs. */ - typedef CreateConnectomicsNetworkWriter Self; - typedef itk::SmartPointer Pointer; - - /** Methods from itk:LightObject. */ - itkFactorylessNewMacro(Self); - LightObject::Pointer CreateObject() { typename T::Pointer p = T::New(); - p->Register(); - return p.GetPointer(); - } - -protected: - CreateConnectomicsNetworkWriter() {} - ~CreateConnectomicsNetworkWriter() {} - -private: - CreateConnectomicsNetworkWriter(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented -}; - -ConnectomicsNetworkWriterFactory::ConnectomicsNetworkWriterFactory() -{ - this->RegisterOverride("IOWriter", - "ConnectomicsNetworkWriter", - "ConnectomicsNetwork Writer", - 1, - mitk::CreateConnectomicsNetworkWriter< mitk::ConnectomicsNetworkWriter >::New()); -} - -ConnectomicsNetworkWriterFactory::~ConnectomicsNetworkWriterFactory() -{ -} - -const char* ConnectomicsNetworkWriterFactory::GetITKSourceVersion() const -{ - return ITK_SOURCE_VERSION; -} - -const char* ConnectomicsNetworkWriterFactory::GetDescription() const -{ - return "ConnectomicsNetworkWriterFactory"; -} - -} // end namespace mitk diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkConnectomicsNetworkWriterFactory.h b/Modules/DiffusionImaging/DiffusionIO/mitkConnectomicsNetworkWriterFactory.h deleted file mode 100644 index 0662c7c957..0000000000 --- a/Modules/DiffusionImaging/DiffusionIO/mitkConnectomicsNetworkWriterFactory.h +++ /dev/null @@ -1,54 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#ifndef ConnectomicsNetwork_WRITERFACTORY_H_HEADER_INCLUDED -#define ConnectomicsNetwork_WRITERFACTORY_H_HEADER_INCLUDED - -#include "itkObjectFactoryBase.h" -#include "mitkBaseData.h" - -namespace mitk -{ - -class ConnectomicsNetworkWriterFactory : public itk::ObjectFactoryBase -{ -public: - - mitkClassMacro( mitk::ConnectomicsNetworkWriterFactory, itk::ObjectFactoryBase ) - - /** Class methods used to interface with the registered factories. */ - virtual const char* GetITKSourceVersion(void) const; - virtual const char* GetDescription(void) const; - - /** Method for class instantiation. */ - itkFactorylessNewMacro(Self); - -protected: - ConnectomicsNetworkWriterFactory(); - ~ConnectomicsNetworkWriterFactory(); - -private: - ConnectomicsNetworkWriterFactory(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - -}; - -} // end namespace mitk - -#endif // ConnectomicsNetwork_WRITERFACTORY_H_HEADER_INCLUDED - - - diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkConnectomicsObjectFactory.cpp b/Modules/DiffusionImaging/DiffusionIO/mitkConnectomicsObjectFactory.cpp index 93b82a9b03..23918b4413 100644 --- a/Modules/DiffusionImaging/DiffusionIO/mitkConnectomicsObjectFactory.cpp +++ b/Modules/DiffusionImaging/DiffusionIO/mitkConnectomicsObjectFactory.cpp @@ -1,128 +1,110 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkConnectomicsObjectFactory.h" #include "mitkConnectomicsNetwork.h" -#include "mitkConnectomicsNetworkIOFactory.h" -#include "mitkConnectomicsNetworkWriter.h" -#include "mitkConnectomicsNetworkWriterFactory.h" #include "mitkConnectomicsNetworkMapper3D.h" mitk::ConnectomicsObjectFactory::ConnectomicsObjectFactory() : CoreObjectFactoryBase() - , m_ConnectomicsNetworkIOFactory(mitk::ConnectomicsNetworkIOFactory::New().GetPointer()) - , m_ConnectomicsNetworkWriterFactory(mitk::ConnectomicsNetworkWriterFactory::New().GetPointer()) { static bool alreadyDone = false; if (!alreadyDone) { MITK_DEBUG << "ConnectomicsObjectFactory c'tor" << std::endl; - itk::ObjectFactoryBase::RegisterFactory(m_ConnectomicsNetworkIOFactory); - - itk::ObjectFactoryBase::RegisterFactory(m_ConnectomicsNetworkWriterFactory); - - m_FileWriters.push_back( mitk::ConnectomicsNetworkWriter::New().GetPointer() ); - - CreateFileExtensionsMap(); - alreadyDone = true; } } mitk::ConnectomicsObjectFactory::~ConnectomicsObjectFactory() { - itk::ObjectFactoryBase::UnRegisterFactory(m_ConnectomicsNetworkIOFactory); - itk::ObjectFactoryBase::UnRegisterFactory(m_ConnectomicsNetworkWriterFactory); } mitk::Mapper::Pointer mitk::ConnectomicsObjectFactory::CreateMapper(mitk::DataNode* node, MapperSlotId id) { mitk::Mapper::Pointer newMapper=NULL; if ( id == mitk::BaseRenderer::Standard3D ) { std::string classname("ConnectomicsNetwork"); if (node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { newMapper = mitk::ConnectomicsNetworkMapper3D::New(); newMapper->SetDataNode(node); } } return newMapper; } void mitk::ConnectomicsObjectFactory::SetDefaultProperties(mitk::DataNode* node) { std::string classname("ConnectomicsNetwork"); if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { mitk::ConnectomicsNetworkMapper3D::SetDefaultProperties(node); } } const char* mitk::ConnectomicsObjectFactory::GetFileExtensions() { std::string fileExtension; this->CreateFileExtensions(m_FileExtensionsMap, fileExtension); return fileExtension.c_str(); }; mitk::CoreObjectFactoryBase::MultimapType mitk::ConnectomicsObjectFactory::GetFileExtensionsMap() { return m_FileExtensionsMap; } const char* mitk::ConnectomicsObjectFactory::GetSaveFileExtensions() { std::string fileExtension; this->CreateFileExtensions(m_SaveFileExtensionsMap, fileExtension); return fileExtension.c_str(); }; mitk::CoreObjectFactoryBase::MultimapType mitk::ConnectomicsObjectFactory::GetSaveFileExtensionsMap() { return m_SaveFileExtensionsMap; } void mitk::ConnectomicsObjectFactory::CreateFileExtensionsMap() { - m_FileExtensionsMap.insert(std::pair("*.cnf", "Connectomics Network File")); - - m_SaveFileExtensionsMap.insert(std::pair("*.cnf", "Connectomics Network File")); } struct RegisterConnectomicsObjectFactory{ RegisterConnectomicsObjectFactory() : m_Factory( mitk::ConnectomicsObjectFactory::New() ) { mitk::CoreObjectFactory::GetInstance()->RegisterExtraFactory( m_Factory ); } ~RegisterConnectomicsObjectFactory() { mitk::CoreObjectFactory::GetInstance()->UnRegisterExtraFactory( m_Factory ); } mitk::ConnectomicsObjectFactory::Pointer m_Factory; }; static RegisterConnectomicsObjectFactory registerDiffusionCoreObjectFactory; diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkDiffusionCoreObjectFactory.cpp b/Modules/DiffusionImaging/DiffusionIO/mitkDiffusionCoreObjectFactory.cpp index 3b284e47c3..f086e2a058 100644 --- a/Modules/DiffusionImaging/DiffusionIO/mitkDiffusionCoreObjectFactory.cpp +++ b/Modules/DiffusionImaging/DiffusionIO/mitkDiffusionCoreObjectFactory.cpp @@ -1,239 +1,199 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkDiffusionCoreObjectFactory.h" #include "mitkProperties.h" #include "mitkBaseRenderer.h" #include "mitkDataNode.h" -#include "mitkNrrdDiffusionImageIOFactory.h" #include "mitkNrrdDiffusionImageWriterFactory.h" #include "mitkNrrdDiffusionImageWriter.h" #include "mitkDiffusionImage.h" -#include "mitkNrrdQBallImageIOFactory.h" -#include "mitkNrrdQBallImageWriterFactory.h" -#include "mitkNrrdQBallImageWriter.h" - -#include "mitkNrrdTensorImageIOFactory.h" -#include "mitkNrrdTensorImageWriterFactory.h" -#include "mitkNrrdTensorImageWriter.h" - #include "mitkCompositeMapper.h" #include "mitkDiffusionImageMapper.h" #include "mitkGPUVolumeMapper3D.h" #include "mitkVolumeDataVtkMapper3D.h" typedef short DiffusionPixelType; typedef mitk::DiffusionImage DiffusionImageShort; typedef std::multimap MultimapType; mitk::DiffusionCoreObjectFactory::DiffusionCoreObjectFactory() : CoreObjectFactoryBase() - , m_NrrdDiffusionImageIOFactory(mitk::NrrdDiffusionImageIOFactory::New().GetPointer()) - , m_NrrdQBallImageIOFactory(mitk::NrrdQBallImageIOFactory::New().GetPointer()) - , m_NrrdTensorImageIOFactory(mitk::NrrdTensorImageIOFactory::New().GetPointer()) , m_NrrdDiffusionImageWriterFactory(mitk::NrrdDiffusionImageWriterFactory::New().GetPointer()) - , m_NrrdQBallImageWriterFactory(mitk::NrrdQBallImageWriterFactory::New().GetPointer()) - , m_NrrdTensorImageWriterFactory(mitk::NrrdTensorImageWriterFactory::New().GetPointer()) { static bool alreadyDone = false; if (!alreadyDone) { MITK_DEBUG << "DiffusionCoreObjectFactory c'tor" << std::endl; - itk::ObjectFactoryBase::RegisterFactory(m_NrrdDiffusionImageIOFactory); - itk::ObjectFactoryBase::RegisterFactory(m_NrrdQBallImageIOFactory); - itk::ObjectFactoryBase::RegisterFactory(m_NrrdTensorImageIOFactory); - itk::ObjectFactoryBase::RegisterFactory(m_NrrdDiffusionImageWriterFactory); - itk::ObjectFactoryBase::RegisterFactory(m_NrrdQBallImageWriterFactory); - itk::ObjectFactoryBase::RegisterFactory(m_NrrdTensorImageWriterFactory); m_FileWriters.push_back( NrrdDiffusionImageWriter::New().GetPointer() ); - m_FileWriters.push_back( NrrdQBallImageWriter::New().GetPointer() ); - m_FileWriters.push_back( NrrdTensorImageWriter::New().GetPointer() ); CreateFileExtensionsMap(); alreadyDone = true; } } mitk::DiffusionCoreObjectFactory::~DiffusionCoreObjectFactory() { - itk::ObjectFactoryBase::UnRegisterFactory(m_NrrdDiffusionImageIOFactory); - itk::ObjectFactoryBase::UnRegisterFactory(m_NrrdQBallImageIOFactory); - itk::ObjectFactoryBase::UnRegisterFactory(m_NrrdTensorImageIOFactory); itk::ObjectFactoryBase::UnRegisterFactory(m_NrrdDiffusionImageWriterFactory); - itk::ObjectFactoryBase::UnRegisterFactory(m_NrrdQBallImageWriterFactory); - itk::ObjectFactoryBase::UnRegisterFactory(m_NrrdTensorImageWriterFactory); } mitk::Mapper::Pointer mitk::DiffusionCoreObjectFactory::CreateMapper(mitk::DataNode* node, MapperSlotId id) { mitk::Mapper::Pointer newMapper=NULL; if ( id == mitk::BaseRenderer::Standard2D ) { std::string classname("QBallImage"); if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { newMapper = mitk::CompositeMapper::New(); newMapper->SetDataNode(node); node->SetMapper(3, ((CompositeMapper*)newMapper.GetPointer())->GetImageMapper()); } classname = "TensorImage"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { newMapper = mitk::CompositeMapper::New(); newMapper->SetDataNode(node); node->SetMapper(3, ((CompositeMapper*)newMapper.GetPointer())->GetImageMapper()); } classname = "DiffusionImage"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { newMapper = mitk::DiffusionImageMapper::New(); newMapper->SetDataNode(node); } } else if ( id == mitk::BaseRenderer::Standard3D ) { std::string classname("QBallImage"); if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { newMapper = mitk::GPUVolumeMapper3D::New(); newMapper->SetDataNode(node); } classname = "TensorImage"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { newMapper = mitk::GPUVolumeMapper3D::New(); newMapper->SetDataNode(node); } classname = "DiffusionImage"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { newMapper = mitk::GPUVolumeMapper3D::New(); newMapper->SetDataNode(node); } } return newMapper; } void mitk::DiffusionCoreObjectFactory::SetDefaultProperties(mitk::DataNode* node) { std::string classname = "QBallImage"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { mitk::CompositeMapper::SetDefaultProperties(node); mitk::GPUVolumeMapper3D::SetDefaultProperties(node); } classname = "TensorImage"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { mitk::CompositeMapper::SetDefaultProperties(node); mitk::GPUVolumeMapper3D::SetDefaultProperties(node); } classname = "DiffusionImage"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { mitk::DiffusionImageMapper::SetDefaultProperties(node); mitk::GPUVolumeMapper3D::SetDefaultProperties(node); } } const char* mitk::DiffusionCoreObjectFactory::GetFileExtensions() { std::string fileExtension; this->CreateFileExtensions(m_FileExtensionsMap, fileExtension); return fileExtension.c_str(); } mitk::CoreObjectFactoryBase::MultimapType mitk::DiffusionCoreObjectFactory::GetFileExtensionsMap() { return m_FileExtensionsMap; } const char* mitk::DiffusionCoreObjectFactory::GetSaveFileExtensions() { std::string fileExtension; this->CreateFileExtensions(m_SaveFileExtensionsMap, fileExtension); return fileExtension.c_str(); } mitk::CoreObjectFactoryBase::MultimapType mitk::DiffusionCoreObjectFactory::GetSaveFileExtensionsMap() { return m_SaveFileExtensionsMap; } void mitk::DiffusionCoreObjectFactory::CreateFileExtensionsMap() { - m_FileExtensionsMap.insert(std::pair("*.dwi", "Diffusion Weighted Images")); - m_FileExtensionsMap.insert(std::pair("*.hdwi", "Diffusion Weighted Images")); - m_FileExtensionsMap.insert(std::pair("*.nii", "Diffusion Weighted Images for FSL")); - m_FileExtensionsMap.insert(std::pair("*.fsl", "Diffusion Weighted Images for FSL")); - m_FileExtensionsMap.insert(std::pair("*.fslgz", "Diffusion Weighted Images for FSL")); - m_FileExtensionsMap.insert(std::pair("*.qbi", "Q-Ball Images")); - m_FileExtensionsMap.insert(std::pair("*.hqbi", "Q-Ball Images")); - m_FileExtensionsMap.insert(std::pair("*.dti", "Tensor Images")); - m_FileExtensionsMap.insert(std::pair("*.hdti", "Tensor Images")); // m_FileExtensionsMap.insert(std::pair("*.pf", "Planar Figure File")); m_SaveFileExtensionsMap.insert(std::pair("*.dwi", "Diffusion Weighted Images")); m_SaveFileExtensionsMap.insert(std::pair("*.hdwi", "Diffusion Weighted Images")); m_SaveFileExtensionsMap.insert(std::pair("*.nii", "Diffusion Weighted Images for FSL")); m_SaveFileExtensionsMap.insert(std::pair("*.fsl", "Diffusion Weighted Images for FSL")); m_SaveFileExtensionsMap.insert(std::pair("*.fslgz", "Diffusion Weighted Images for FSL")); - m_SaveFileExtensionsMap.insert(std::pair("*.qbi", "Q-Ball Images")); - m_SaveFileExtensionsMap.insert(std::pair("*.hqbi", "Q-Ball Images")); - m_SaveFileExtensionsMap.insert(std::pair("*.dti", "Tensor Images")); - m_SaveFileExtensionsMap.insert(std::pair("*.hdti", "Tensor Images")); // m_SaveFileExtensionsMap.insert(std::pair("*.pf", "Planar Figure File")); } struct RegisterDiffusionCoreObjectFactory{ RegisterDiffusionCoreObjectFactory() : m_Factory( mitk::DiffusionCoreObjectFactory::New() ) { mitk::CoreObjectFactory::GetInstance()->RegisterExtraFactory( m_Factory ); } ~RegisterDiffusionCoreObjectFactory() { mitk::CoreObjectFactory::GetInstance()->UnRegisterExtraFactory( m_Factory ); } mitk::DiffusionCoreObjectFactory::Pointer m_Factory; }; static RegisterDiffusionCoreObjectFactory registerDiffusionCoreObjectFactory; diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkDiffusionCoreObjectFactory.h b/Modules/DiffusionImaging/DiffusionIO/mitkDiffusionCoreObjectFactory.h index da416c1a34..4b75db9b9f 100644 --- a/Modules/DiffusionImaging/DiffusionIO/mitkDiffusionCoreObjectFactory.h +++ b/Modules/DiffusionImaging/DiffusionIO/mitkDiffusionCoreObjectFactory.h @@ -1,69 +1,66 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef DiffusionCoreObjectFactory_H_INCLUDED #define DiffusionCoreObjectFactory_H_INCLUDED #include "mitkCoreObjectFactory.h" namespace mitk { class DiffusionCoreObjectFactory : public CoreObjectFactoryBase { public: mitkClassMacro(DiffusionCoreObjectFactory,CoreObjectFactoryBase) itkFactorylessNewMacro(Self) itkCloneMacro(Self) ~DiffusionCoreObjectFactory(); virtual Mapper::Pointer CreateMapper(mitk::DataNode* node, MapperSlotId slotId); virtual void SetDefaultProperties(mitk::DataNode* node); virtual const char* GetFileExtensions(); virtual mitk::CoreObjectFactoryBase::MultimapType GetFileExtensionsMap(); virtual const char* GetSaveFileExtensions(); virtual mitk::CoreObjectFactoryBase::MultimapType GetSaveFileExtensionsMap(); protected: DiffusionCoreObjectFactory(); void CreateFileExtensionsMap(); MultimapType m_FileExtensionsMap; MultimapType m_SaveFileExtensionsMap; private: std::string m_ExternalFileExtensions; std::string m_InternalFileExtensions; std::string m_SaveFileExtensions; itk::ObjectFactoryBase::Pointer m_NrrdDiffusionImageIOFactory; itk::ObjectFactoryBase::Pointer m_NrrdQBallImageIOFactory; - itk::ObjectFactoryBase::Pointer m_NrrdTensorImageIOFactory; itk::ObjectFactoryBase::Pointer m_NrrdDiffusionImageWriterFactory; itk::ObjectFactoryBase::Pointer m_NrrdQBallImageWriterFactory; - itk::ObjectFactoryBase::Pointer m_NrrdTensorImageWriterFactory; - }; } #endif diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkDiffusionIOMimeTypes.cpp b/Modules/DiffusionImaging/DiffusionIO/mitkDiffusionIOMimeTypes.cpp new file mode 100644 index 0000000000..cfca45d9bb --- /dev/null +++ b/Modules/DiffusionImaging/DiffusionIO/mitkDiffusionIOMimeTypes.cpp @@ -0,0 +1,138 @@ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ + +#include "mitkDiffusionIOMimeTypes.h" +#include "mitkIOMimeTypes.h" + +namespace mitk +{ + +std::vector DiffusionIOMimeTypes::Get() +{ + std::vector mimeTypes; + + // order matters here (descending rank for mime types) + + mimeTypes.push_back(DWI_MIMETYPE().Clone()); + mimeTypes.push_back(DTI_MIMETYPE().Clone()); + mimeTypes.push_back(QBI_MIMETYPE().Clone()); + + mimeTypes.push_back(FIBERBUNDLE_MIMETYPE().Clone()); + + mimeTypes.push_back(CONNECTOMICS_MIMETYPE().Clone()); + + return mimeTypes; +} + +// Mime Types + +CustomMimeType DiffusionIOMimeTypes::FIBERBUNDLE_MIMETYPE() +{ + CustomMimeType mimeType(FIBERBUNDLE_MIMETYPE_NAME()); + std::string category = "Fiber Bundle File"; + mimeType.SetComment("Fiber Bundles"); + mimeType.SetCategory(category); + mimeType.AddExtension("fib"); + mimeType.AddExtension("trk"); + mimeType.AddExtension("vtk"); + return mimeType; +} + +CustomMimeType DiffusionIOMimeTypes::DWI_MIMETYPE() +{ + CustomMimeType mimeType(DWI_MIMETYPE_NAME()); + std::string category = "Diffusion Weighted Image"; + mimeType.SetComment("Diffusion Weighted Images"); + mimeType.SetCategory(category); + mimeType.AddExtension("dwi"); + mimeType.AddExtension("hdwi"); + mimeType.AddExtension("fsl"); + mimeType.AddExtension("fslgz"); + return mimeType; +} + +CustomMimeType DiffusionIOMimeTypes::DTI_MIMETYPE() +{ + CustomMimeType mimeType(DTI_MIMETYPE_NAME()); + std::string category = "Tensor Images"; + mimeType.SetComment("Diffusion Tensor Images"); + mimeType.SetCategory(category); + mimeType.AddExtension("dti"); + mimeType.AddExtension("hdti"); + return mimeType; +} + +CustomMimeType DiffusionIOMimeTypes::QBI_MIMETYPE() +{ + CustomMimeType mimeType(QBI_MIMETYPE_NAME()); + std::string category = "Q-Ball Images"; + mimeType.SetComment("Diffusion Q-Ball Images"); + mimeType.SetCategory(category); + mimeType.AddExtension("qbi"); + mimeType.AddExtension("hqbi"); + return mimeType; +} + +CustomMimeType DiffusionIOMimeTypes::CONNECTOMICS_MIMETYPE() +{ + CustomMimeType mimeType(CONNECTOMICS_MIMETYPE_NAME()); + std::string category = "Connectomics Networks"; + mimeType.SetComment("Connectomics Networks"); + mimeType.SetCategory(category); + mimeType.AddExtension("cnf"); + return mimeType; +} + +// Names +std::string DiffusionIOMimeTypes::DWI_MIMETYPE_NAME() +{ + static std::string name = IOMimeTypes::DEFAULT_BASE_NAME() + ".dwi"; + return name; +} + +std::string DiffusionIOMimeTypes::DTI_MIMETYPE_NAME() +{ + static std::string name = IOMimeTypes::DEFAULT_BASE_NAME() + ".dti"; + return name; +} + +std::string DiffusionIOMimeTypes::QBI_MIMETYPE_NAME() +{ + static std::string name = IOMimeTypes::DEFAULT_BASE_NAME() + ".qbi"; + return name; +} + +std::string DiffusionIOMimeTypes::FIBERBUNDLE_MIMETYPE_NAME() +{ + static std::string name = IOMimeTypes::DEFAULT_BASE_NAME() + ".fib"; + return name; +} + +std::string DiffusionIOMimeTypes::CONNECTOMICS_MIMETYPE_NAME() +{ + static std::string name = IOMimeTypes::DEFAULT_BASE_NAME() + ".cnf"; + return name; +} + +// Descriptions +const std::string DiffusionIOMimeTypes::FIBERBUNDLE_MIMETYPE_DESCRIPTION = "Fiberbundles"; + +const std::string DiffusionIOMimeTypes::DWI_MIMETYPE_DESCRIPTION = "Diffusion Weighted Images"; +const std::string DiffusionIOMimeTypes::DTI_MIMETYPE_DESCRIPTION = "Diffusion Tensor Images"; +const std::string DiffusionIOMimeTypes::QBI_MIMETYPE_DESCRIPTION = "Q-Ball Images"; + +const std::string DiffusionIOMimeTypes::CONNECTOMICS_MIMETYPE_DESCRIPTION = "Connectomics Networks"; +} diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkDiffusionIOMimeTypes.h b/Modules/DiffusionImaging/DiffusionIO/mitkDiffusionIOMimeTypes.h new file mode 100644 index 0000000000..92823b59f9 --- /dev/null +++ b/Modules/DiffusionImaging/DiffusionIO/mitkDiffusionIOMimeTypes.h @@ -0,0 +1,72 @@ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ + +#ifndef MITKDIFFUSIONIOMIMETYPES_H +#define MITKDIFFUSIONIOMIMETYPES_H + +#include "mitkCustomMimeType.h" + +#include + +namespace mitk { + +class DiffusionIOMimeTypes +{ +public: + + // Get all Diffusion Mime Types + static std::vector Get(); + + // ------------------------------ VTK formats ---------------------------------- + + static CustomMimeType FIBERBUNDLE_MIMETYPE(); // fib + + static std::string FIBERBUNDLE_MIMETYPE_NAME(); + + static const std::string FIBERBUNDLE_MIMETYPE_DESCRIPTION; + + // ------------------------- Image formats (ITK based) -------------------------- + + static CustomMimeType DWI_MIMETYPE(); // dwi, hdwi + static CustomMimeType DTI_MIMETYPE(); // dti, hdti + static CustomMimeType QBI_MIMETYPE(); // qbi, hqbi + + static std::string DWI_MIMETYPE_NAME(); + static std::string DTI_MIMETYPE_NAME(); + static std::string QBI_MIMETYPE_NAME(); + + static const std::string DWI_MIMETYPE_DESCRIPTION; + static const std::string DTI_MIMETYPE_DESCRIPTION; + static const std::string QBI_MIMETYPE_DESCRIPTION; + + // ------------------------------ MITK formats ---------------------------------- + + static CustomMimeType CONNECTOMICS_MIMETYPE(); // cnf + + static std::string CONNECTOMICS_MIMETYPE_NAME(); + + static const std::string CONNECTOMICS_MIMETYPE_DESCRIPTION; + +private: + + // purposely not implemented + DiffusionIOMimeTypes(); + DiffusionIOMimeTypes(const DiffusionIOMimeTypes&); +}; + +} + +#endif // MITKDIFFUSIONIOMIMETYPES_H diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkDiffusionModuleActivator.cpp b/Modules/DiffusionImaging/DiffusionIO/mitkDiffusionModuleActivator.cpp index 4b50242299..b68efb772b 100644 --- a/Modules/DiffusionImaging/DiffusionIO/mitkDiffusionModuleActivator.cpp +++ b/Modules/DiffusionImaging/DiffusionIO/mitkDiffusionModuleActivator.cpp @@ -1,50 +1,95 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include +#include -//#include -//#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "mitkDiffusionIOMimeTypes.h" namespace mitk { /** \brief Registers services for segmentation module. */ class DiffusionModuleActivator : public us::ModuleActivator { public: - void Load(us::ModuleContext* /*context*/) + void Load(us::ModuleContext* context) { -// m_FiberBundleXReader = new FiberBundleXReader(); -// m_FiberBundleXWriter = new FiberBundleXWriter(); + us::ServiceProperties props; + props[ us::ServiceConstants::SERVICE_RANKING() ] = 10; + + std::vector mimeTypes = mitk::DiffusionIOMimeTypes::Get(); + for (std::vector::const_iterator mimeTypeIter = mimeTypes.begin(), + iterEnd = mimeTypes.end(); mimeTypeIter != iterEnd; ++mimeTypeIter) + { + context->RegisterService(*mimeTypeIter, props); + } + + m_NrrdDiffusionImageReader = new NrrdDiffusionImageReader(); + m_NrrdTensorImageReader = new NrrdTensorImageReader(); + m_NrrdQBallImageReader = new NrrdQBallImageReader(); + m_FiberBundleXReader = new FiberBundleXReader(); + m_ConnectomicsNetworkReader = new ConnectomicsNetworkReader(); + + m_NrrdTensorImageWriter = new NrrdTensorImageWriter(); + m_NrrdQBallImageWriter = new NrrdQBallImageWriter(); + m_FiberBundleXWriter = new FiberBundleXWriter(); + m_ConnectomicsNetworkWriter = new ConnectomicsNetworkWriter(); } void Unload(us::ModuleContext*) { -// delete m_FiberBundleXReader; -// delete m_FiberBundleXWriter; + delete m_NrrdDiffusionImageReader; + delete m_NrrdTensorImageReader; + delete m_NrrdQBallImageReader; + delete m_FiberBundleXReader; + delete m_ConnectomicsNetworkReader; + + delete m_NrrdTensorImageWriter; + delete m_NrrdQBallImageWriter; + delete m_FiberBundleXWriter; + delete m_ConnectomicsNetworkWriter; } private: -// FiberBundleXReader * m_FiberBundleXReader; -// FiberBundleXWriter * m_FiberBundleXWriter; + NrrdDiffusionImageReader * m_NrrdDiffusionImageReader; + NrrdTensorImageReader * m_NrrdTensorImageReader; + NrrdQBallImageReader * m_NrrdQBallImageReader; + FiberBundleXReader * m_FiberBundleXReader; + ConnectomicsNetworkReader * m_ConnectomicsNetworkReader; + + NrrdTensorImageWriter * m_NrrdTensorImageWriter; + NrrdQBallImageWriter * m_NrrdQBallImageWriter; + FiberBundleXWriter * m_FiberBundleXWriter; + ConnectomicsNetworkWriter * m_ConnectomicsNetworkWriter; }; } US_EXPORT_MODULE_ACTIVATOR(mitk::DiffusionModuleActivator) diff --git a/Modules/DiffusionImaging/FiberTracking/IODataStructures/FiberBundleX/mitkFiberBundleXReader.cpp b/Modules/DiffusionImaging/DiffusionIO/mitkFiberBundleXReader.cpp similarity index 88% rename from Modules/DiffusionImaging/FiberTracking/IODataStructures/FiberBundleX/mitkFiberBundleXReader.cpp rename to Modules/DiffusionImaging/DiffusionIO/mitkFiberBundleXReader.cpp index cda259ab09..7f25dfd464 100644 --- a/Modules/DiffusionImaging/FiberTracking/IODataStructures/FiberBundleX/mitkFiberBundleXReader.cpp +++ b/Modules/DiffusionImaging/DiffusionIO/mitkFiberBundleXReader.cpp @@ -1,108 +1,99 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkFiberBundleXReader.h" #include #include #include #include #include #include #include #include #include #include #include #include +#include "mitkDiffusionIOMimeTypes.h" mitk::FiberBundleXReader::FiberBundleXReader() - :mitk::AbstractFileReader() + : mitk::AbstractFileReader( CustomMimeType( mitk::DiffusionIOMimeTypes::FIBERBUNDLE_MIMETYPE_NAME() ), mitk::DiffusionIOMimeTypes::FIBERBUNDLE_MIMETYPE_DESCRIPTION ) { - std::string category = "Fiber Bundle File"; - mitk::CustomMimeType customMimeType; - customMimeType.SetCategory(category); - customMimeType.AddExtension("fib"); - customMimeType.AddExtension("trk"); - customMimeType.AddExtension("vtk"); - - this->SetDescription(category); - this->SetMimeType(customMimeType); - m_ServiceReg = this->RegisterService(); } mitk::FiberBundleXReader::FiberBundleXReader(const FiberBundleXReader &other) :mitk::AbstractFileReader(other) { } mitk::FiberBundleXReader * mitk::FiberBundleXReader::Clone() const { return new FiberBundleXReader(*this); } std::vector > mitk::FiberBundleXReader::Read() { std::vector > result; try { const std::string& locale = "C"; const std::string& currLocale = setlocale( LC_ALL, NULL ); setlocale(LC_ALL, locale.c_str()); std::string filename = this->GetInputLocation(); std::string ext = itksys::SystemTools::GetFilenameLastExtension(filename); ext = itksys::SystemTools::LowerCase(ext); if (ext==".trk") { FiberBundleX::Pointer image = FiberBundleX::New(); TrackVisFiberReader reader; reader.open(this->GetInputLocation().c_str()); reader.read(image.GetPointer()); result.push_back(image.GetPointer()); return result; } vtkSmartPointer chooser=vtkSmartPointer::New(); chooser->SetFileName( this->GetInputLocation().c_str() ); if( chooser->IsFilePolyData()) { vtkSmartPointer reader = vtkSmartPointer::New(); reader->SetFileName( this->GetInputLocation().c_str() ); reader->Update(); if ( reader->GetOutput() != NULL ) { vtkSmartPointer fiberPolyData = reader->GetOutput(); FiberBundleX::Pointer image = FiberBundleX::New(fiberPolyData); result.push_back(image.GetPointer()); return result; } } setlocale(LC_ALL, currLocale.c_str()); MITK_INFO << "Fiber bundle read"; } catch(...) { throw; } return result; } diff --git a/Modules/DiffusionImaging/FiberTracking/IODataStructures/FiberBundleX/mitkFiberBundleXReader.h b/Modules/DiffusionImaging/DiffusionIO/mitkFiberBundleXReader.h similarity index 100% rename from Modules/DiffusionImaging/FiberTracking/IODataStructures/FiberBundleX/mitkFiberBundleXReader.h rename to Modules/DiffusionImaging/DiffusionIO/mitkFiberBundleXReader.h diff --git a/Modules/DiffusionImaging/FiberTracking/IODataStructures/FiberBundleX/mitkFiberBundleXSerializer.cpp b/Modules/DiffusionImaging/DiffusionIO/mitkFiberBundleXSerializer.cpp similarity index 100% rename from Modules/DiffusionImaging/FiberTracking/IODataStructures/FiberBundleX/mitkFiberBundleXSerializer.cpp rename to Modules/DiffusionImaging/DiffusionIO/mitkFiberBundleXSerializer.cpp diff --git a/Modules/DiffusionImaging/FiberTracking/IODataStructures/FiberBundleX/mitkFiberBundleXSerializer.h b/Modules/DiffusionImaging/DiffusionIO/mitkFiberBundleXSerializer.h similarity index 89% rename from Modules/DiffusionImaging/FiberTracking/IODataStructures/FiberBundleX/mitkFiberBundleXSerializer.h rename to Modules/DiffusionImaging/DiffusionIO/mitkFiberBundleXSerializer.h index cc8c912114..02043bd112 100644 --- a/Modules/DiffusionImaging/FiberTracking/IODataStructures/FiberBundleX/mitkFiberBundleXSerializer.h +++ b/Modules/DiffusionImaging/DiffusionIO/mitkFiberBundleXSerializer.h @@ -1,40 +1,39 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef mitkFiberBundleXSerializer_h_included #define mitkFiberBundleXSerializer_h_included -#include #include "mitkBaseDataSerializer.h" namespace mitk { /** \brief Serializes mitk::Surface for mitk::SceneIO */ -class MitkFiberTracking_EXPORT FiberBundleXSerializer : public BaseDataSerializer +class FiberBundleXSerializer : public BaseDataSerializer { public: mitkClassMacro( FiberBundleXSerializer, BaseDataSerializer ); itkFactorylessNewMacro(Self) itkCloneMacro(Self) virtual std::string Serialize(); protected: FiberBundleXSerializer(); virtual ~FiberBundleXSerializer(); }; } // namespace #endif diff --git a/Modules/DiffusionImaging/FiberTracking/IODataStructures/FiberBundleX/mitkFiberBundleXWriter.cpp b/Modules/DiffusionImaging/DiffusionIO/mitkFiberBundleXWriter.cpp similarity index 90% rename from Modules/DiffusionImaging/FiberTracking/IODataStructures/FiberBundleX/mitkFiberBundleXWriter.cpp rename to Modules/DiffusionImaging/DiffusionIO/mitkFiberBundleXWriter.cpp index 5c8eef50de..49fb66e264 100644 --- a/Modules/DiffusionImaging/FiberTracking/IODataStructures/FiberBundleX/mitkFiberBundleXWriter.cpp +++ b/Modules/DiffusionImaging/DiffusionIO/mitkFiberBundleXWriter.cpp @@ -1,137 +1,126 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkFiberBundleXWriter.h" #include #include #include #include #include #include #include +#include "mitkDiffusionIOMimeTypes.h" mitk::FiberBundleXWriter::FiberBundleXWriter() - : mitk::AbstractFileWriter(mitk::FiberBundleX::GetStaticNameOfClass()) + : mitk::AbstractFileWriter(mitk::FiberBundleX::GetStaticNameOfClass(), CustomMimeType( mitk::DiffusionIOMimeTypes::FIBERBUNDLE_MIMETYPE_NAME() ), mitk::DiffusionIOMimeTypes::FIBERBUNDLE_MIMETYPE_DESCRIPTION) { - std::string category = "Fiber Bundle File"; - mitk::CustomMimeType customMimeType; - customMimeType.SetCategory(category); - customMimeType.AddExtension("fib"); - customMimeType.AddExtension("afib"); - customMimeType.AddExtension("vtk"); - customMimeType.AddExtension("avtk"); - customMimeType.AddExtension("trk"); - - this->SetDescription(category); - this->SetMimeType(customMimeType); - RegisterService(); } mitk::FiberBundleXWriter::FiberBundleXWriter(const mitk::FiberBundleXWriter & other) :mitk::AbstractFileWriter(other) {} mitk::FiberBundleXWriter::~FiberBundleXWriter() {} mitk::FiberBundleXWriter * mitk::FiberBundleXWriter::Clone() const { return new mitk::FiberBundleXWriter(*this); } void mitk::FiberBundleXWriter::Write() { std::ostream* out; std::ofstream outStream; if( this->GetOutputStream() ) { out = this->GetOutputStream(); }else{ outStream.open( this->GetOutputLocation().c_str() ); out = &outStream; } if ( !out->good() ) { mitkThrow() << "Stream not good."; } try { const std::string& locale = "C"; const std::string& currLocale = setlocale( LC_ALL, NULL ); setlocale(LC_ALL, locale.c_str()); std::locale previousLocale(out->getloc()); std::locale I("C"); out->imbue(I); std::string filename = this->GetOutputLocation().c_str(); mitk::FiberBundleX::ConstPointer input = dynamic_cast(this->GetInput()); std::string ext = itksys::SystemTools::GetFilenameLastExtension(this->GetOutputLocation().c_str()); if (ext==".fib" || ext==".vtk") { MITK_INFO << "Writing fiber bundle as binary VTK"; vtkSmartPointer writer = vtkSmartPointer::New(); writer->SetInputData(input->GetFiberPolyData()); writer->SetFileName(this->GetOutputLocation().c_str()); writer->SetFileTypeToBinary(); writer->Write(); } else if (ext==".afib") { itksys::SystemTools::ReplaceString(filename,".afib",".fib"); MITK_INFO << "Writing fiber bundle as ascii VTK"; vtkSmartPointer writer = vtkSmartPointer::New(); writer->SetInputData(input->GetFiberPolyData()); writer->SetFileName(this->GetOutputLocation().c_str()); writer->SetFileTypeToASCII(); writer->Write(); } else if (ext==".avtk") { itksys::SystemTools::ReplaceString(filename,".avtk",".vtk"); MITK_INFO << "Writing fiber bundle as ascii VTK"; vtkSmartPointer writer = vtkSmartPointer::New(); writer->SetInputData(input->GetFiberPolyData()); writer->SetFileName(this->GetOutputLocation().c_str()); writer->SetFileTypeToASCII(); writer->Write(); } else if (ext==".trk") { MITK_INFO << "Writing fiber bundle as TRK"; TrackVisFiberReader trk; trk.create(filename, input.GetPointer()); trk.writeHdr(); trk.append(input.GetPointer()); } setlocale(LC_ALL, currLocale.c_str()); MITK_INFO << "Fiber bundle written"; } catch(...) { throw; } } diff --git a/Modules/DiffusionImaging/FiberTracking/IODataStructures/FiberBundleX/mitkFiberBundleXWriter.h b/Modules/DiffusionImaging/DiffusionIO/mitkFiberBundleXWriter.h similarity index 100% rename from Modules/DiffusionImaging/FiberTracking/IODataStructures/FiberBundleX/mitkFiberBundleXWriter.h rename to Modules/DiffusionImaging/DiffusionIO/mitkFiberBundleXWriter.h diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkFiberTrackingObjectFactory.cpp b/Modules/DiffusionImaging/DiffusionIO/mitkFiberTrackingObjectFactory.cpp index 160e33d600..cf8846e1fa 100644 --- a/Modules/DiffusionImaging/DiffusionIO/mitkFiberTrackingObjectFactory.cpp +++ b/Modules/DiffusionImaging/DiffusionIO/mitkFiberTrackingObjectFactory.cpp @@ -1,111 +1,127 @@ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ + #include "mitkFiberTrackingObjectFactory.h" mitk::FiberTrackingObjectFactory::FiberTrackingObjectFactory() : CoreObjectFactoryBase() { } mitk::FiberTrackingObjectFactory::~FiberTrackingObjectFactory() { } mitk::Mapper::Pointer mitk::FiberTrackingObjectFactory::CreateMapper(mitk::DataNode* node, MapperSlotId id) { mitk::Mapper::Pointer newMapper=NULL; if ( id == mitk::BaseRenderer::Standard2D ) { std::string classname("FiberBundleX"); if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { newMapper = mitk::FiberBundleXMapper2D::New(); newMapper->SetDataNode(node); } } else if ( id == mitk::BaseRenderer::Standard3D ) { std::string classname("FiberBundleX"); if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { newMapper = mitk::FiberBundleXMapper3D::New(); newMapper->SetDataNode(node); } // classname = "FiberBundleXThreadMonitor"; // if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) // { // newMapper = mitk::FiberBundleXThreadMonitorMapper3D::New(); // newMapper->SetDataNode(node); // } } return newMapper; } void mitk::FiberTrackingObjectFactory::SetDefaultProperties(mitk::DataNode* node) { std::string classname("FiberBundleX"); if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { mitk::FiberBundleXMapper3D::SetDefaultProperties(node); mitk::FiberBundleXMapper2D::SetDefaultProperties(node); } // classname = "FiberBundleXThreadMonitor"; // if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) // { // mitk::FiberBundleXThreadMonitorMapper3D::SetDefaultProperties(node); // } } const char* mitk::FiberTrackingObjectFactory::GetFileExtensions() { std::string fileExtension; this->CreateFileExtensions(m_FileExtensionsMap, fileExtension); return fileExtension.c_str(); } mitk::CoreObjectFactoryBase::MultimapType mitk::FiberTrackingObjectFactory::GetFileExtensionsMap() { return m_FileExtensionsMap; } const char* mitk::FiberTrackingObjectFactory::GetSaveFileExtensions() { std::string fileExtension; this->CreateFileExtensions(m_SaveFileExtensionsMap, fileExtension); return fileExtension.c_str(); } mitk::CoreObjectFactoryBase::MultimapType mitk::FiberTrackingObjectFactory::GetSaveFileExtensionsMap() { return m_SaveFileExtensionsMap; } void mitk::FiberTrackingObjectFactory::CreateFileExtensionsMap() { } void mitk::FiberTrackingObjectFactory::RegisterIOFactories() { } struct RegisterFiberTrackingObjectFactory{ RegisterFiberTrackingObjectFactory() : m_Factory( mitk::FiberTrackingObjectFactory::New() ) { mitk::CoreObjectFactory::GetInstance()->RegisterExtraFactory( m_Factory ); } ~RegisterFiberTrackingObjectFactory() { mitk::CoreObjectFactory::GetInstance()->UnRegisterExtraFactory( m_Factory ); } mitk::FiberTrackingObjectFactory::Pointer m_Factory; }; static RegisterFiberTrackingObjectFactory registerFiberTrackingObjectFactory; diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkFiberTrackingObjectFactory.h b/Modules/DiffusionImaging/DiffusionIO/mitkFiberTrackingObjectFactory.h index f78bc04bc9..b26f470e1b 100644 --- a/Modules/DiffusionImaging/DiffusionIO/mitkFiberTrackingObjectFactory.h +++ b/Modules/DiffusionImaging/DiffusionIO/mitkFiberTrackingObjectFactory.h @@ -1,54 +1,70 @@ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ + #ifndef MITKFIBERTRACKINGOBJECTFACTORY_H #define MITKFIBERTRACKINGOBJECTFACTORY_H #include "mitkCoreObjectFactory.h" //modernized fiberbundle datastrucutre #include "mitkFiberBundleX.h" #include "mitkFiberBundleXMapper3D.h" #include "mitkFiberBundleXMapper2D.h" //#include "mitkFiberBundleXThreadMonitorMapper3D.h" //#include "mitkFiberBundleXThreadMonitor.h" namespace mitk { class FiberTrackingObjectFactory : public CoreObjectFactoryBase { public: mitkClassMacro(FiberTrackingObjectFactory,CoreObjectFactoryBase) itkFactorylessNewMacro(Self) itkCloneMacro(Self) ~FiberTrackingObjectFactory(); virtual Mapper::Pointer CreateMapper(mitk::DataNode* node, MapperSlotId slotId); virtual void SetDefaultProperties(mitk::DataNode* node); virtual const char* GetFileExtensions(); virtual mitk::CoreObjectFactoryBase::MultimapType GetFileExtensionsMap(); virtual const char* GetSaveFileExtensions(); virtual mitk::CoreObjectFactoryBase::MultimapType GetSaveFileExtensionsMap(); void RegisterIOFactories(); protected: FiberTrackingObjectFactory(); private: void CreateFileExtensionsMap(); std::string m_ExternalFileExtensions; std::string m_InternalFileExtensions; std::string m_SaveFileExtensions; MultimapType m_FileExtensionsMap; MultimapType m_SaveFileExtensionsMap; }; } #endif // MITKFIBERTRACKINGOBJECTFACTORY_H diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdDiffusionImageIOFactory.cpp b/Modules/DiffusionImaging/DiffusionIO/mitkNrrdDiffusionImageIOFactory.cpp deleted file mode 100644 index 15c5359ace..0000000000 --- a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdDiffusionImageIOFactory.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "mitkNrrdDiffusionImageIOFactory.h" -#include "mitkIOAdapter.h" -#include "mitkNrrdDiffusionImageReader.h" - -#include "itkVersion.h" - - -namespace mitk -{ - -NrrdDiffusionImageIOFactory::NrrdDiffusionImageIOFactory() -{ - typedef short DiffusionPixelType; - typedef itk::VectorImage< DiffusionPixelType, 3 > DiffusionImageType; - typedef NrrdDiffusionImageReader NrrdDiffVolReaderType; - this->RegisterOverride("mitkIOAdapter", - "mitkNrrdDiffusionImageReader", - "mitk Diffusion Image IO", - 1, - itk::CreateObjectFunction >::New()); -} - -NrrdDiffusionImageIOFactory::~NrrdDiffusionImageIOFactory() -{ -} - -const char* NrrdDiffusionImageIOFactory::GetITKSourceVersion() const -{ - return ITK_SOURCE_VERSION; -} - -const char* NrrdDiffusionImageIOFactory::GetDescription() const -{ - return "NrrdDiffusionImage IO Factory, allows the loading of NRRD DWI data"; -} - -} // end namespace mitk diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdDiffusionImageIOFactory.h b/Modules/DiffusionImaging/DiffusionIO/mitkNrrdDiffusionImageIOFactory.h deleted file mode 100644 index 59c7176d25..0000000000 --- a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdDiffusionImageIOFactory.h +++ /dev/null @@ -1,75 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ -#ifndef __MITK_NRRD_DIFFUSION_VOULMES_IO_FACTORY_H_HEADER__ -#define __MITK_NRRD_DIFFUSION_VOULMES_IO_FACTORY_H_HEADER__ - -#ifdef _MSC_VER -#pragma warning ( disable : 4786 ) -#endif - -#include "itkObjectFactoryBase.h" -#include "mitkBaseData.h" - -namespace mitk -{ -//##Documentation -//## @brief Create instances of NrrdDiffusionImageReader objects using an object factory. -//## -class NrrdDiffusionImageIOFactory : public itk::ObjectFactoryBase -{ -public: - /** Standard class typedefs. */ - typedef NrrdDiffusionImageIOFactory Self; - typedef itk::ObjectFactoryBase Superclass; - typedef itk::SmartPointer Pointer; - typedef itk::SmartPointer ConstPointer; - - /** Class methods used to interface with the registered factories. */ - virtual const char* GetITKSourceVersion(void) const; - virtual const char* GetDescription(void) const; - - /** Method for class instantiation. */ - itkFactorylessNewMacro(Self); - static NrrdDiffusionImageIOFactory* FactoryNew() { return new NrrdDiffusionImageIOFactory;} - /** Run-time type information (and related methods). */ - itkTypeMacro(NrrdDiffusionImageIOFactory, ObjectFactoryBase); - - /** Register one factory of this type */ - static void RegisterOneFactory(void) - { - static bool IsRegistered = false; - if ( !IsRegistered ) - { - NrrdDiffusionImageIOFactory::Pointer fac = NrrdDiffusionImageIOFactory::New(); - ObjectFactoryBase::RegisterFactory( fac ); - IsRegistered = true; - } - } - -protected: - NrrdDiffusionImageIOFactory(); - ~NrrdDiffusionImageIOFactory(); - -private: - NrrdDiffusionImageIOFactory(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - -}; - - -} // end namespace mitk - -#endif // __MITK_NRRD_DIFFUSION_VOULMES_IO_FACTORY_H_HEADER__ diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdDiffusionImageReader.cpp b/Modules/DiffusionImaging/DiffusionIO/mitkNrrdDiffusionImageReader.cpp index be41bfc08b..8833e7ac2c 100644 --- a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdDiffusionImageReader.cpp +++ b/Modules/DiffusionImaging/DiffusionIO/mitkNrrdDiffusionImageReader.cpp @@ -1,532 +1,420 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef __mitkNrrdDiffusionImageReader_cpp #define __mitkNrrdDiffusionImageReader_cpp #include "mitkNrrdDiffusionImageReader.h" #include "itkImageFileReader.h" #include "itkMetaDataObject.h" #include "itkNrrdImageIO.h" #include "itkNiftiImageIO.h" #include #include #include "itksys/SystemTools.hxx" +#include "mitkCustomMimeType.h" +#include "mitkDiffusionIOMimeTypes.h" namespace mitk { - template - void NrrdDiffusionImageReader - ::GenerateData() - { +NrrdDiffusionImageReader:: +NrrdDiffusionImageReader(const NrrdDiffusionImageReader & other) + : AbstractFileReader(other) +{ +} - // Since everything is completely read in GenerateOutputInformation() it is stored - // in a cache variable. A timestamp is associated. - // If the timestamp of the cache variable is newer than the MTime, we only need to - // assign the cache variable to the DataObject. - // Otherwise, the tree must be read again from the file and OuputInformation must - // be updated! - if ( ( ! m_OutputCache ) || ( this->GetMTime( ) > m_CacheTime.GetMTime( ) ) ) - { - this->GenerateOutputInformation(); - itkWarningMacro("Cache regenerated!"); - } - if (!m_OutputCache) - { - itkWarningMacro("cache is empty!"); - } +NrrdDiffusionImageReader* NrrdDiffusionImageReader::Clone() const +{ + return new NrrdDiffusionImageReader(*this); +} - static_cast(this->GetOutput()) - ->SetVectorImage(m_OutputCache->GetVectorImage()); - static_cast(this->GetOutput()) - ->SetReferenceBValue(m_OutputCache->GetReferenceBValue()); - static_cast(this->GetOutput()) - ->SetMeasurementFrame(m_OutputCache->GetMeasurementFrame()); - static_cast(this->GetOutput()) - ->SetDirections(m_OutputCache->GetDirections()); - static_cast(this->GetOutput()) - ->InitializeFromVectorImage(); - } - template - void NrrdDiffusionImageReader::GenerateOutputInformation() - { - typename OutputType::Pointer outputForCache = OutputType::New(); - if ( m_FileName == "") - { - throw itk::ImageFileReaderException(__FILE__, __LINE__, "Sorry, the filename to be read is empty!"); - } - else - { - try - { - const std::string& locale = "C"; - const std::string& currLocale = setlocale( LC_ALL, NULL ); +NrrdDiffusionImageReader:: +~NrrdDiffusionImageReader() +{} - if ( locale.compare(currLocale)!=0 ) - { - try - { - setlocale(LC_ALL, locale.c_str()); - } - catch(...) - { - MITK_INFO << "Could not set locale " << locale; - } - } +NrrdDiffusionImageReader:: +NrrdDiffusionImageReader() + : mitk::AbstractFileReader( CustomMimeType( mitk::DiffusionIOMimeTypes::DWI_MIMETYPE_NAME() ), mitk::DiffusionIOMimeTypes::DWI_MIMETYPE_DESCRIPTION ) +{ + m_ServiceReg = this->RegisterService(); +} - MITK_INFO << "NrrdDiffusionImageReader: reading image information"; - typename ImageType::Pointer img; +std::vector > +NrrdDiffusionImageReader:: +Read() +{ + std::vector > result; - std::string ext = itksys::SystemTools::GetFilenameLastExtension(m_FileName); - ext = itksys::SystemTools::LowerCase(ext); - if (ext == ".hdwi" || ext == ".dwi") - { - typedef itk::ImageFileReader FileReaderType; - typename FileReaderType::Pointer reader = FileReaderType::New(); - reader->SetFileName(this->m_FileName); - itk::NrrdImageIO::Pointer io = itk::NrrdImageIO::New(); - reader->SetImageIO(io); - reader->Update(); - img = reader->GetOutput(); + // Since everything is completely read in GenerateOutputInformation() it is stored + // in a cache variable. A timestamp is associated. + // If the timestamp of the cache variable is newer than the MTime, we only need to + // assign the cache variable to the DataObject. + // Otherwise, the tree must be read again from the file and OuputInformation must + // be updated! + + if(m_OutputCache.IsNull()) InternalRead(); + + OutputType::Pointer resultImage = OutputType::New(); + resultImage->SetVectorImage(m_OutputCache->GetVectorImage()); + resultImage->SetReferenceBValue(m_OutputCache->GetReferenceBValue()); + resultImage->SetMeasurementFrame(m_OutputCache->GetMeasurementFrame()); + resultImage->SetDirections(m_OutputCache->GetDirections()); + resultImage->InitializeFromVectorImage(); - int vecsize = img->GetVectorLength(); - std::cout << vecsize << std::endl; + result.push_back(resultImage.GetPointer()); + return result; +} +void NrrdDiffusionImageReader::InternalRead() +{ + OutputType::Pointer outputForCache = OutputType::New(); + if ( this->GetInputLocation() == "") + { + throw itk::ImageFileReaderException(__FILE__, __LINE__, "Sorry, the filename 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()); } - else if(ext == ".fsl" || ext == ".fslgz") + catch(...) { - // create temporary file with correct ending for nifti-io - std::string fname3 = "temp_dwi"; - fname3 += ext == ".fsl" ? ".nii" : ".nii.gz"; - itksys::SystemTools::CopyAFile(m_FileName.c_str(), fname3.c_str()); - - // create reader and read file - typedef itk::Image ImageType4D; - itk::NiftiImageIO::Pointer io2 = itk::NiftiImageIO::New(); - typedef itk::ImageFileReader FileReaderType; - typename FileReaderType::Pointer reader = FileReaderType::New(); - reader->SetFileName(fname3); - reader->SetImageIO(io2); - reader->Update(); - typename ImageType4D::Pointer img4 = reader->GetOutput(); - - // delete temporary file - itksys::SystemTools::RemoveFile(fname3.c_str()); - - // convert 4D file to vector image - img = ImageType::New(); - - typename ImageType::SpacingType spacing; - typename ImageType4D::SpacingType spacing4 = img4->GetSpacing(); - for(int i=0; i<3; i++) - spacing[i] = spacing4[i]; - img->SetSpacing( spacing ); // Set the image spacing + MITK_INFO << "Could not set locale " << locale; + } + } - typename ImageType::PointType origin; - typename ImageType4D::PointType origin4 = img4->GetOrigin(); - for(int i=0; i<3; i++) - origin[i] = origin4[i]; - img->SetOrigin( origin ); // Set the image origin - typename ImageType::DirectionType direction; - typename ImageType4D::DirectionType direction4 = img4->GetDirection(); - for(int i=0; i<3; i++) - for(int j=0; j<3; j++) - direction[i][j] = direction4[i][j]; - img->SetDirection( direction ); // Set the image direction + MITK_INFO << "NrrdDiffusionImageReader: reading image information"; + ImageType::Pointer img; - typename ImageType::RegionType region; - typename ImageType4D::RegionType region4 = img4->GetLargestPossibleRegion(); + std::string ext = itksys::SystemTools::GetFilenameLastExtension(this->GetInputLocation()); + ext = itksys::SystemTools::LowerCase(ext); + if (ext == ".hdwi" || ext == ".dwi") + { + typedef itk::ImageFileReader FileReaderType; + FileReaderType::Pointer reader = FileReaderType::New(); + reader->SetFileName(this->GetInputLocation()); + itk::NrrdImageIO::Pointer io = itk::NrrdImageIO::New(); + reader->SetImageIO(io); + reader->Update(); + img = reader->GetOutput(); - typename ImageType::RegionType::SizeType size; - typename ImageType4D::RegionType::SizeType size4 = region4.GetSize(); + int vecsize = img->GetVectorLength(); + std::cout << vecsize << std::endl; - for(int i=0; i<3; i++) - size[i] = size4[i]; - typename ImageType::RegionType::IndexType index; - typename ImageType4D::RegionType::IndexType index4 = region4.GetIndex(); - for(int i=0; i<3; i++) - index[i] = index4[i]; + } + else if(ext == ".fsl" || ext == ".fslgz") + { + // create temporary file with correct ending for nifti-io + std::string fname3 = "temp_dwi"; + fname3 += ext == ".fsl" ? ".nii" : ".nii.gz"; + itksys::SystemTools::CopyAFile(this->GetInputLocation().c_str(), fname3.c_str()); + + // create reader and read file + typedef itk::Image ImageType4D; + itk::NiftiImageIO::Pointer io2 = itk::NiftiImageIO::New(); + typedef itk::ImageFileReader FileReaderType; + FileReaderType::Pointer reader = FileReaderType::New(); + reader->SetFileName(fname3); + reader->SetImageIO(io2); + reader->Update(); + ImageType4D::Pointer img4 = reader->GetOutput(); - region.SetSize(size); - region.SetIndex(index); - img->SetRegions( region ); + // delete temporary file + itksys::SystemTools::RemoveFile(fname3.c_str()); - img->SetVectorLength(size4[3]); - img->Allocate(); + // convert 4D file to vector image + img = ImageType::New(); - itk::ImageRegionIterator it (img, img->GetLargestPossibleRegion() ); - typedef typename ImageType::PixelType VecPixType; - for (it.GoToBegin(); !it.IsAtEnd(); ++it) - { - VecPixType vec = it.Get(); - typename ImageType::IndexType currentIndex = it.GetIndex(); - for(int i=0; i<3; i++) - index4[i] = currentIndex[i]; - for(unsigned int ind=0; indGetPixel(index4); - } - it.Set(vec); - } - } + ImageType::SpacingType spacing; + ImageType4D::SpacingType spacing4 = img4->GetSpacing(); + for(int i=0; i<3; i++) + spacing[i] = spacing4[i]; + img->SetSpacing( spacing ); // Set the image spacing - m_DiffusionVectors = GradientDirectionContainerType::New(); - m_OriginalDiffusionVectors = GradientDirectionContainerType::New(); - if (ext == ".hdwi" || ext == ".dwi") - { + ImageType::PointType origin; + ImageType4D::PointType origin4 = img4->GetOrigin(); + for(int i=0; i<3; i++) + origin[i] = origin4[i]; + img->SetOrigin( origin ); // Set the image origin - itk::MetaDataDictionary imgMetaDictionary = img->GetMetaDataDictionary(); - std::vector imgMetaKeys = imgMetaDictionary.GetKeys(); - std::vector::const_iterator itKey = imgMetaKeys.begin(); - std::string metaString; + ImageType::DirectionType direction; + ImageType4D::DirectionType direction4 = img4->GetDirection(); + for(int i=0; i<3; i++) + for(int j=0; j<3; j++) + direction[i][j] = direction4[i][j]; + img->SetDirection( direction ); // Set the image direction - GradientDirectionType vect3d; + ImageType::RegionType region; + ImageType4D::RegionType region4 = img4->GetLargestPossibleRegion(); - int numberOfImages = 0; - int numberOfGradientImages = 0; - bool readb0 = false; - double xx, xy, xz, yx, yy, yz, zx, zy, zz; + ImageType::RegionType::SizeType size; + ImageType4D::RegionType::SizeType size4 = region4.GetSize(); - for (; itKey != imgMetaKeys.end(); itKey ++) - { - double x,y,z; + for(int i=0; i<3; i++) + size[i] = size4[i]; - itk::ExposeMetaData (imgMetaDictionary, *itKey, metaString); - if (itKey->find("DWMRI_gradient") != std::string::npos) - { - sscanf(metaString.c_str(), "%lf %lf %lf\n", &x, &y, &z); - vect3d[0] = x; vect3d[1] = y; vect3d[2] = z; - m_DiffusionVectors->InsertElement( numberOfImages, vect3d ); - ++numberOfImages; - // If the direction is 0.0, this is a reference image - if (vect3d[0] == 0.0 && - vect3d[1] == 0.0 && - vect3d[2] == 0.0) - { - continue; - } - ++numberOfGradientImages;; - } - else if (itKey->find("DWMRI_b-value") != std::string::npos) - { - readb0 = true; - m_B_Value = atof(metaString.c_str()); - } - else 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 ) - { - m_MeasurementFrame(0,0) = xx; - m_MeasurementFrame(0,1) = xy; - m_MeasurementFrame(0,2) = xz; - m_MeasurementFrame(1,0) = yx; - m_MeasurementFrame(1,1) = yy; - m_MeasurementFrame(1,2) = yz; - m_MeasurementFrame(2,0) = zx; - m_MeasurementFrame(2,1) = zy; - m_MeasurementFrame(2,2) = zz; - } - else - { - m_MeasurementFrame(0,0) = 1; - m_MeasurementFrame(0,1) = 0; - m_MeasurementFrame(0,2) = 0; - m_MeasurementFrame(1,0) = 0; - m_MeasurementFrame(1,1) = 1; - m_MeasurementFrame(1,2) = 0; - m_MeasurementFrame(2,0) = 0; - m_MeasurementFrame(2,1) = 0; - m_MeasurementFrame(2,2) = 1; - } - } - } + ImageType::RegionType::IndexType index; + ImageType4D::RegionType::IndexType index4 = region4.GetIndex(); + for(int i=0; i<3; i++) + index[i] = index4[i]; + + region.SetSize(size); + region.SetIndex(index); + img->SetRegions( region ); + + img->SetVectorLength(size4[3]); + img->Allocate(); - if(!readb0) + itk::ImageRegionIterator it (img, img->GetLargestPossibleRegion() ); + typedef ImageType::PixelType VecPixType; + for (it.GoToBegin(); !it.IsAtEnd(); ++it) + { + VecPixType vec = it.Get(); + ImageType::IndexType currentIndex = it.GetIndex(); + for(int i=0; i<3; i++) + index4[i] = currentIndex[i]; + for(unsigned int ind=0; indGetPixel(index4); } - + it.Set(vec); } - else if(ext == ".fsl" || ext == ".fslgz") + } + + m_DiffusionVectors = GradientDirectionContainerType::New(); + m_OriginalDiffusionVectors = GradientDirectionContainerType::New(); + if (ext == ".hdwi" || ext == ".dwi") + { + + itk::MetaDataDictionary imgMetaDictionary = img->GetMetaDataDictionary(); + std::vector imgMetaKeys = imgMetaDictionary.GetKeys(); + std::vector::const_iterator itKey = imgMetaKeys.begin(); + std::string metaString; + + GradientDirectionType vect3d; + + int numberOfImages = 0; + int numberOfGradientImages = 0; + bool readb0 = false; + double xx, xy, xz, yx, yy, yz, zx, zy, zz; + + for (; itKey != imgMetaKeys.end(); itKey ++) { + double x,y,z; - std::string line; - std::vector bvec_entries; - std::string fname = m_FileName; - fname += ".bvecs"; - std::ifstream myfile (fname.c_str()); - if (myfile.is_open()) + itk::ExposeMetaData (imgMetaDictionary, *itKey, metaString); + if (itKey->find("DWMRI_gradient") != std::string::npos) { - while ( myfile.good() ) + sscanf(metaString.c_str(), "%lf %lf %lf\n", &x, &y, &z); + vect3d[0] = x; vect3d[1] = y; vect3d[2] = z; + m_DiffusionVectors->InsertElement( numberOfImages, vect3d ); + ++numberOfImages; + // If the direction is 0.0, this is a reference image + if (vect3d[0] == 0.0 && + vect3d[1] == 0.0 && + vect3d[2] == 0.0) { - getline (myfile,line); - char* pch = strtok (const_cast(line.c_str())," "); - while (pch != NULL) - { - bvec_entries.push_back(atof(pch)); - pch = strtok (NULL, " "); - } + continue; } - myfile.close(); + ++numberOfGradientImages;; } - else + else if (itKey->find("DWMRI_b-value") != std::string::npos) { - MITK_INFO << "Unable to open bvecs file"; + readb0 = true; + m_B_Value = atof(metaString.c_str()); } - - std::vector bval_entries; - std::string fname2 = m_FileName; - fname2 += ".bvals"; - std::ifstream myfile2 (fname2.c_str()); - if (myfile2.is_open()) + else if (itKey->find("measurement frame") != std::string::npos) { - while ( myfile2.good() ) + 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 ) { - getline (myfile2,line); - char* pch = strtok (const_cast(line.c_str())," "); - while (pch != NULL) - { - bval_entries.push_back(atof(pch)); - pch = strtok (NULL, " "); - } + m_MeasurementFrame(0,0) = xx; + m_MeasurementFrame(0,1) = xy; + m_MeasurementFrame(0,2) = xz; + m_MeasurementFrame(1,0) = yx; + m_MeasurementFrame(1,1) = yy; + m_MeasurementFrame(1,2) = yz; + m_MeasurementFrame(2,0) = zx; + m_MeasurementFrame(2,1) = zy; + m_MeasurementFrame(2,2) = zz; } - myfile2.close(); - } - else - { - MITK_INFO << "Unable to open bvals file"; - } - - - m_B_Value = -1; - unsigned int numb = bval_entries.size(); - for(unsigned int i=0; i vec; - vec[0] = bvec_entries.at(i); - vec[1] = bvec_entries.at(i+numb); - vec[2] = bvec_entries.at(i+2*numb); + } + else if(ext == ".fsl" || ext == ".fslgz") + { - // Adjust the vector length to encode gradient strength - float factor = b_val/m_B_Value; - if(vec.magnitude() > 0) + std::string line; + std::vector bvec_entries; + std::string fname = this->GetInputLocation(); + fname += ".bvecs"; + std::ifstream myfile (fname.c_str()); + if (myfile.is_open()) + { + while ( myfile.good() ) + { + getline (myfile,line); + char* pch = strtok (const_cast(line.c_str())," "); + while (pch != NULL) { - vec[0] = sqrt(factor)*vec[0]; - vec[1] = sqrt(factor)*vec[1]; - vec[2] = sqrt(factor)*vec[2]; + bvec_entries.push_back(atof(pch)); + pch = strtok (NULL, " "); } - - m_DiffusionVectors->InsertElement(i,vec); } - - for(int i=0; i<3; i++) - for(int j=0; j<3; j++) - m_MeasurementFrame[i][j] = i==j ? 1 : 0; + myfile.close(); + } + else + { + MITK_INFO << "Unable to open bvecs file"; } - outputForCache->SetVectorImage(img); - outputForCache->SetReferenceBValue(m_B_Value); - outputForCache->SetMeasurementFrame(m_MeasurementFrame); - outputForCache->SetDirections(m_DiffusionVectors); - - - // Since we have already read the tree, we can store it in a cache variable - // so that it can be assigned to the DataObject in GenerateData(); - m_OutputCache = outputForCache; - m_CacheTime.Modified(); - - try + std::vector bval_entries; + std::string fname2 = this->GetInputLocation(); + fname2 += ".bvals"; + std::ifstream myfile2 (fname2.c_str()); + if (myfile2.is_open()) { - setlocale(LC_ALL, currLocale.c_str()); + while ( myfile2.good() ) + { + getline (myfile2,line); + char* pch = strtok (const_cast(line.c_str())," "); + while (pch != NULL) + { + bval_entries.push_back(atof(pch)); + pch = strtok (NULL, " "); + } + } + myfile2.close(); } - catch(...) + else { - MITK_INFO << "Could not reset locale " << currLocale; + MITK_INFO << "Unable to open bvals file"; } - } - catch(std::exception& e) - { - MITK_INFO << "Std::Exception while reading file!!"; - MITK_INFO << e.what(); - throw itk::ImageFileReaderException(__FILE__, __LINE__, e.what()); - } - catch(...) - { - MITK_INFO << "Exception while reading file!!"; - throw itk::ImageFileReaderException(__FILE__, __LINE__, "Sorry, an error occurred while reading the requested vessel tree file!"); - } - } - } - template - const char* NrrdDiffusionImageReader - ::GetFileName() const - { - return m_FileName.c_str(); - } + m_B_Value = -1; + unsigned int numb = bval_entries.size(); + for(unsigned int i=0; i - void NrrdDiffusionImageReader - ::SetFileName(const char* aFileName) - { - m_FileName = aFileName; - } + // Take the first entry in bvals as the reference b-value + if(m_B_Value == -1 && bval_entries.at(i) != 0) + { + m_B_Value = bval_entries.at(i); + } - template - const char* NrrdDiffusionImageReader - ::GetFilePrefix() const - { - return m_FilePrefix.c_str(); - } + float b_val = bval_entries.at(i); - template - void NrrdDiffusionImageReader - ::SetFilePrefix(const char* aFilePrefix) - { - m_FilePrefix = aFilePrefix; - } - template - const char* NrrdDiffusionImageReader - ::GetFilePattern() const - { - return m_FilePattern.c_str(); - } + vnl_vector_fixed< double, 3 > vec; + vec[0] = bvec_entries.at(i); + vec[1] = bvec_entries.at(i+numb); + vec[2] = bvec_entries.at(i+2*numb); - template - void NrrdDiffusionImageReader - ::SetFilePattern(const char* aFilePattern) - { - m_FilePattern = aFilePattern; - } + // Adjust the vector length to encode gradient strength + float factor = b_val/m_B_Value; + if(vec.magnitude() > 0) + { + vec[0] = sqrt(factor)*vec[0]; + vec[1] = sqrt(factor)*vec[1]; + vec[2] = sqrt(factor)*vec[2]; + } - template - bool NrrdDiffusionImageReader - ::CanReadFile(const std::string filename, const std::string /*filePrefix*/, const std::string /*filePattern*/) - { - // First check the extension - if( filename == "" ) - { - return false; - } - std::string ext = itksys::SystemTools::GetFilenameLastExtension(filename); - ext = itksys::SystemTools::LowerCase(ext); + m_DiffusionVectors->InsertElement(i,vec); + } + + for(int i=0; i<3; i++) + for(int j=0; j<3; j++) + m_MeasurementFrame[i][j] = i==j ? 1 : 0; + } + + outputForCache->SetVectorImage(img); + outputForCache->SetReferenceBValue(m_B_Value); + outputForCache->SetMeasurementFrame(m_MeasurementFrame); + outputForCache->SetDirections(m_DiffusionVectors); - if (ext == ".hdwi" || ext == ".dwi") - { - itk::NrrdImageIO::Pointer io = itk::NrrdImageIO::New(); - typedef itk::ImageFileReader FileReaderType; - typename FileReaderType::Pointer reader = FileReaderType::New(); - reader->SetImageIO(io); - reader->SetFileName(filename); + // Since we have already read the tree, we can store it in a cache variable + // so that it can be assigned to the DataObject in GenerateData(); + m_OutputCache = outputForCache; + m_CacheTime.Modified(); try { - reader->Update(); - } - catch(itk::ExceptionObject e) - { - MITK_INFO << e.GetDescription(); + setlocale(LC_ALL, currLocale.c_str()); } - - typename ImageType::Pointer img = reader->GetOutput(); - itk::MetaDataDictionary imgMetaDictionary = img->GetMetaDataDictionary(); - std::vector imgMetaKeys = imgMetaDictionary.GetKeys(); - std::vector::const_iterator itKey = imgMetaKeys.begin(); - std::string metaString; - - for (; itKey != imgMetaKeys.end(); itKey ++) + catch(...) { - itk::ExposeMetaData (imgMetaDictionary, *itKey, metaString); - if (itKey->find("modality") != std::string::npos) - { - if (metaString.find("DWMRI") != std::string::npos) - { - return true; - } - } + MITK_INFO << "Could not reset locale " << currLocale; } } - - if (ext == ".fsl" || ext == ".fslgz") + catch(std::exception& e) { - // itk::NiftiImageIO::Pointer io2 = itk::NiftiImageIO::New(); - - // typedef itk::ImageFileReader FileReaderType; - // typename FileReaderType::Pointer reader = FileReaderType::New(); - // reader->SetImageIO(io2); - // reader->SetFileName(filename); - - // try - // { - // reader->Update(); - // } - // catch(itk::ExceptionObject e) - // { - // MITK_INFO << e.GetDescription(); - // } - - std::string fname = filename; - fname += ".bvecs"; - - std::string fname2 = filename; - fname2 += ".bvals"; - - if( itksys::SystemTools::FileExists(fname.c_str()) - && itksys::SystemTools::FileExists(fname2.c_str()) ) - { - return true; - } - else - { - MITK_INFO << ".bvals and .bvals files do not exist properly"; - } - + MITK_INFO << "Std::Exception while reading file!!"; + MITK_INFO << e.what(); + throw itk::ImageFileReaderException(__FILE__, __LINE__, e.what()); + } + catch(...) + { + MITK_INFO << "Exception while reading file!!"; + throw itk::ImageFileReaderException(__FILE__, __LINE__, "Sorry, an error occurred while reading the requested vessel tree file!"); } - - return false; } +} } //namespace MITK #endif diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdDiffusionImageReader.h b/Modules/DiffusionImaging/DiffusionIO/mitkNrrdDiffusionImageReader.h index 20cad8b1da..f7c10669af 100644 --- a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdDiffusionImageReader.h +++ b/Modules/DiffusionImaging/DiffusionIO/mitkNrrdDiffusionImageReader.h @@ -1,87 +1,72 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef __mitkNrrdDiffusionImageReader_h #define __mitkNrrdDiffusionImageReader_h #include "mitkCommon.h" #include "itkVectorContainer.h" #include "mitkFileReader.h" #include "vnl/vnl_vector_fixed.h" #include "vnl/vnl_matrix_fixed.h" -#include "mitkDiffusionImageSource.h" + #include "itkVectorImage.h" +#include "mitkAbstractFileReader.h" +#include "mitkDiffusionImage.h" namespace mitk { /** \brief */ - template < class TPixelType > - class NrrdDiffusionImageReader : public mitk::DiffusionImageSource, public FileReader + class NrrdDiffusionImageReader : public mitk::AbstractFileReader { public: - typedef mitk::DiffusionImage OutputType; - typedef itk::VectorImage ImageType; - typedef DiffusionImageSource DiffVolSourceType; - typedef vnl_vector_fixed< double, 3 > GradientDirectionType; - typedef vnl_matrix_fixed< double, 3, 3 > MeasurementFrameType; - typedef itk::VectorContainer< unsigned int, - GradientDirectionType > GradientDirectionContainerType; - - mitkClassMacro( NrrdDiffusionImageReader, DiffVolSourceType ); - itkFactorylessNewMacro(Self) - itkCloneMacro(Self) + NrrdDiffusionImageReader(const NrrdDiffusionImageReader & other); + NrrdDiffusionImageReader(); + virtual ~NrrdDiffusionImageReader(); - const char* GetFileName() const; - void SetFileName(const char* aFileName); - const char* GetFilePrefix() const; - void SetFilePrefix(const char* aFilePrefix); - const char* GetFilePattern() const; - void SetFilePattern(const char* aFilePattern); + using AbstractFileReader::Read; + virtual std::vector > Read(); - static bool CanReadFile(const std::string filename, const std::string filePrefix, const std::string filePattern); + typedef mitk::DiffusionImage OutputType; + typedef itk::VectorImage ImageType; + typedef vnl_vector_fixed< double, 3 > GradientDirectionType; + typedef vnl_matrix_fixed< double, 3, 3 > MeasurementFrameType; + typedef itk::VectorContainer< unsigned int,GradientDirectionType > GradientDirectionContainerType; protected: - - /** Does the real work. */ - virtual void GenerateData(); - virtual void GenerateOutputInformation(); - - std::string m_FileName; - std::string m_FilePrefix; - std::string m_FilePattern; - - typename OutputType::Pointer m_OutputCache; + OutputType::Pointer m_OutputCache; itk::TimeStamp m_CacheTime; - GradientDirectionContainerType::Pointer m_OriginalDiffusionVectors; GradientDirectionContainerType::Pointer m_DiffusionVectors; float m_B_Value; - MeasurementFrameType m_MeasurementFrame; + void InternalRead(); + private: - void operator=(const Self&); //purposely not implemented + + NrrdDiffusionImageReader* Clone() const; + us::ServiceRegistration m_ServiceReg; }; } //namespace MITK -#include "mitkNrrdDiffusionImageReader.cpp" #endif // __mitkNrrdDiffusionImageReader_h diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdQBallImageIOFactory.cpp b/Modules/DiffusionImaging/DiffusionIO/mitkNrrdQBallImageIOFactory.cpp deleted file mode 100644 index b853a44761..0000000000 --- a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdQBallImageIOFactory.cpp +++ /dev/null @@ -1,51 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "mitkNrrdQBallImageIOFactory.h" -#include "mitkIOAdapter.h" -#include "mitkNrrdQBallImageReader.h" - -#include "itkVersion.h" - - -namespace mitk -{ - -NrrdQBallImageIOFactory::NrrdQBallImageIOFactory() -{ - typedef NrrdQBallImageReader NrrdQBIReaderType; - this->RegisterOverride("mitkIOAdapter", - "mitkNrrdQBallImageReader", - "QBallImages IO", - 1, - itk::CreateObjectFunction >::New()); -} - -NrrdQBallImageIOFactory::~NrrdQBallImageIOFactory() -{ -} - -const char* NrrdQBallImageIOFactory::GetITKSourceVersion() const -{ - return ITK_SOURCE_VERSION; -} - -const char* NrrdQBallImageIOFactory::GetDescription() const -{ - return "NrrdQBallImage IO Factory, allows the loading of NRRD qball data"; -} - -} // end namespace mitk diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdQBallImageIOFactory.h b/Modules/DiffusionImaging/DiffusionIO/mitkNrrdQBallImageIOFactory.h deleted file mode 100644 index 6d423e557b..0000000000 --- a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdQBallImageIOFactory.h +++ /dev/null @@ -1,77 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ -#ifndef __MITK_NRRD_QBI_IO_FACTORY_H_HEADER__ -#define __MITK_NRRD_QBI_IO_FACTORY_H_HEADER__ - -#ifdef _MSC_VER -#pragma warning ( disable : 4786 ) -#endif - -#include "itkObjectFactoryBase.h" -#include "mitkBaseData.h" -#include - -namespace mitk -{ -//##Documentation -//## @brief Create instances of NrrdQBallImageReader objects using an object factory. -//## -class NrrdQBallImageIOFactory : public itk::ObjectFactoryBase -{ -public: - /** Standard class typedefs. */ - typedef NrrdQBallImageIOFactory Self; - typedef itk::ObjectFactoryBase Superclass; - typedef itk::SmartPointer Pointer; - typedef itk::SmartPointer ConstPointer; - - /** Class methods used to interface with the registered factories. */ - virtual const char* GetITKSourceVersion(void) const; - virtual const char* GetDescription(void) const; - - /** Method for class instantiation. */ - itkFactorylessNewMacro(Self); - static NrrdQBallImageIOFactory* FactoryNew() { return new NrrdQBallImageIOFactory;} - /** Run-time type information (and related methods). */ - itkTypeMacro(NrrdQBallImageIOFactory, ObjectFactoryBase); - - /** Register one factory of this type */ - static void RegisterOneFactory(void) - { - static bool IsRegistered = false; - if ( !IsRegistered ) - { - NrrdQBallImageIOFactory::Pointer fac = NrrdQBallImageIOFactory::New(); - ObjectFactoryBase::RegisterFactory( fac ); - IsRegistered = true; - } - } - - -protected: - NrrdQBallImageIOFactory(); - ~NrrdQBallImageIOFactory(); - -private: - NrrdQBallImageIOFactory(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - -}; - - -} // end namespace mitk - -#endif // __MITK_NRRD_QBI_IO_FACTORY_H_HEADER__ diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdQBallImageReader.cpp b/Modules/DiffusionImaging/DiffusionIO/mitkNrrdQBallImageReader.cpp index b93458b4ab..6277a30a1b 100644 --- a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdQBallImageReader.cpp +++ b/Modules/DiffusionImaging/DiffusionIO/mitkNrrdQBallImageReader.cpp @@ -1,180 +1,138 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkNrrdQBallImageReader.h" +#include +#include "mitkDiffusionIOMimeTypes.h" #include "itkImageFileReader.h" #include "itkImageRegionIterator.h" #include "itkMetaDataObject.h" #include "itkNrrdImageIO.h" #include "mitkITKImageImport.h" #include "mitkImageDataItem.h" namespace mitk { + NrrdQBallImageReader::NrrdQBallImageReader(const NrrdQBallImageReader& other) + : mitk::AbstractFileReader(other) + { + } - void NrrdQBallImageReader - ::GenerateData() + NrrdQBallImageReader::NrrdQBallImageReader() + : mitk::AbstractFileReader( CustomMimeType( mitk::DiffusionIOMimeTypes::QBI_MIMETYPE_NAME() ), mitk::DiffusionIOMimeTypes::QBI_MIMETYPE_DESCRIPTION ) { - if ( m_FileName == "") + m_ServiceReg = this->RegisterService(); + } + + NrrdQBallImageReader::~NrrdQBallImageReader() + { + } + + std::vector > NrrdQBallImageReader::Read() + { + std::vector > result; + std::string location = GetInputLocation(); + + if ( location == "") { 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 ImageType; itk::NrrdImageIO::Pointer io = itk::NrrdImageIO::New(); typedef itk::ImageFileReader FileReaderType; FileReaderType::Pointer reader = FileReaderType::New(); reader->SetImageIO(io); - reader->SetFileName(this->m_FileName); + reader->SetFileName(location); reader->Update(); ImageType::Pointer img = reader->GetOutput(); typedef itk::Image,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 ot (vecImg, vecImg->GetLargestPossibleRegion() ); ot.GoToBegin(); itk::ImageRegionIterator it (img, img->GetLargestPossibleRegion() ); typedef ImageType::PixelType VarPixType; typedef VecImgType::PixelType FixPixType; for (it.GoToBegin(); !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()); + OutputType::Pointer resultImage = OutputType::New(); + resultImage->InitializeByItk( vecImg.GetPointer() ); + resultImage->SetVolume( vecImg->GetBufferPointer() ); + result.push_back( resultImage.GetPointer() ); 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!"); } } - } - - void NrrdQBallImageReader::GenerateOutputInformation() - { - - } - - - - const char* NrrdQBallImageReader - ::GetFileName() const - { - return m_FileName.c_str(); - } - - - void NrrdQBallImageReader - ::SetFileName(const char* aFileName) - { - m_FileName = aFileName; - } - - - const char* NrrdQBallImageReader - ::GetFilePrefix() const - { - return m_FilePrefix.c_str(); - } - - - void NrrdQBallImageReader - ::SetFilePrefix(const char* aFilePrefix) - { - m_FilePrefix = aFilePrefix; - } - - - const char* NrrdQBallImageReader - ::GetFilePattern() const - { - return m_FilePattern.c_str(); - } - - - void NrrdQBallImageReader - ::SetFilePattern(const char* aFilePattern) - { - m_FilePattern = aFilePattern; - } - - - bool NrrdQBallImageReader - ::CanReadFile(const std::string filename, const std::string /*filePrefix*/, const std::string /*filePattern*/) - { - // First check the extension - if( filename == "" ) - { - return false; - } - std::string ext = itksys::SystemTools::GetFilenameLastExtension(filename); - ext = itksys::SystemTools::LowerCase(ext); - - if (ext == ".hqbi" || ext == ".qbi") - { - return true; - } - - return false; + return result; } } //namespace MITK + +mitk::NrrdQBallImageReader* mitk::NrrdQBallImageReader::Clone() const +{ + return new NrrdQBallImageReader(*this); +} diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdQBallImageReader.h b/Modules/DiffusionImaging/DiffusionIO/mitkNrrdQBallImageReader.h index 0acef8e38a..3d61f01a50 100644 --- a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdQBallImageReader.h +++ b/Modules/DiffusionImaging/DiffusionIO/mitkNrrdQBallImageReader.h @@ -1,70 +1,60 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef __mitkNrrdQBallImageReader_h #define __mitkNrrdQBallImageReader_h #include "mitkCommon.h" #include "itkVectorContainer.h" -#include "mitkFileReader.h" #include "vnl/vnl_vector_fixed.h" #include "mitkQBallImage.h" -#include "mitkQBallImageSource.h" #include "itkVectorImage.h" +#include +#include +#include namespace mitk { /** \brief */ - class NrrdQBallImageReader : public mitk::QBallImageSource, public FileReader + class NrrdQBallImageReader : public mitk::AbstractFileReader { public: typedef mitk::QBallImage OutputType; - typedef mitk::QBallImageSource QBImgSourceType; - mitkClassMacro( NrrdQBallImageReader, QBImgSourceType ); - itkFactorylessNewMacro(Self) - itkCloneMacro(Self) + NrrdQBallImageReader(const NrrdQBallImageReader& other); + NrrdQBallImageReader(); + virtual ~NrrdQBallImageReader(); - const char* GetFileName() const; - void SetFileName(const char* aFileName); - const char* GetFilePrefix() const; - void SetFilePrefix(const char* aFilePrefix); - const char* GetFilePattern() const; - void SetFilePattern(const char* aFilePattern); - - static bool CanReadFile(const std::string filename, const std::string filePrefix, const std::string filePattern); + using AbstractFileReader::Read; + virtual std::vector > Read(); protected: - /** Does the real work. */ - virtual void GenerateData(); - virtual void GenerateOutputInformation(); - - std::string m_FileName; - std::string m_FilePrefix; - std::string m_FilePattern; private: - void operator=(const Self&); //purposely not implemented + private: + NrrdQBallImageReader* Clone() const; + + us::ServiceRegistration m_ServiceReg; }; } //namespace MITK #endif // __mitkNrrdQBallImageReader_h diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdQBallImageWriter.cpp b/Modules/DiffusionImaging/DiffusionIO/mitkNrrdQBallImageWriter.cpp index ad11a48f02..21187bf9a3 100644 --- a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdQBallImageWriter.cpp +++ b/Modules/DiffusionImaging/DiffusionIO/mitkNrrdQBallImageWriter.cpp @@ -1,160 +1,149 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkNrrdQBallImageWriter.h" #include "itkMetaDataDictionary.h" #include "itkMetaDataObject.h" #include "itkNrrdImageIO.h" #include "itkImageFileWriter.h" #include "mitkImageCast.h" +#include "mitkIOMimeTypes.h" +#include "mitkDiffusionIOMimeTypes.h" mitk::NrrdQBallImageWriter::NrrdQBallImageWriter() - : m_FileName(""), m_FilePrefix(""), m_FilePattern(""), m_Success(false) + : AbstractFileWriter(mitk::QBallImage::GetStaticNameOfClass(), CustomMimeType( mitk::DiffusionIOMimeTypes::QBI_MIMETYPE_NAME() ), mitk::DiffusionIOMimeTypes::QBI_MIMETYPE_DESCRIPTION) { - this->SetNumberOfRequiredInputs( 1 ); + RegisterService(); } +mitk::NrrdQBallImageWriter::NrrdQBallImageWriter(const mitk::NrrdQBallImageWriter& other) + : AbstractFileWriter(other) +{ +} mitk::NrrdQBallImageWriter::~NrrdQBallImageWriter() {} -void mitk::NrrdQBallImageWriter::GenerateData() +void mitk::NrrdQBallImageWriter::Write() { - m_Success = false; - InputType* input = this->GetInput(); - if (input == NULL) + InputType::ConstPointer input = dynamic_cast(this->GetInput()); + if (input.IsNull()) { - itkWarningMacro(<<"Sorry, input to NrrdQBallImageWriter is NULL!"); + MITK_ERROR <<"Sorry, input to NrrdQBallImageWriter is NULL!"; return; } - if ( m_FileName == "" ) + if ( this->GetOutputLocation().c_str() == "" ) { - itkWarningMacro( << "Sorry, filename has not been set!" ); + MITK_ERROR << "Sorry, filename has not been set!"; return ; } 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; } } itk::NrrdImageIO::Pointer io = itk::NrrdImageIO::New(); io->SetFileType( itk::ImageIOBase::Binary ); io->UseCompressionOn(); typedef itk::VectorImage VecImgType; typedef itk::Image,3> ImageType; typedef itk::ImageFileWriter WriterType; WriterType::Pointer nrrdWriter = WriterType::New(); ImageType::Pointer outimage = ImageType::New(); CastToItkImage(input, outimage); VecImgType::Pointer vecImg = VecImgType::New(); vecImg->SetSpacing( outimage->GetSpacing() ); // Set the image spacing vecImg->SetOrigin( outimage->GetOrigin() ); // Set the image origin vecImg->SetDirection( outimage->GetDirection() ); // Set the image direction vecImg->SetLargestPossibleRegion( outimage->GetLargestPossibleRegion()); vecImg->SetBufferedRegion( outimage->GetLargestPossibleRegion() ); vecImg->SetVectorLength(QBALL_ODFSIZE); vecImg->Allocate(); itk::ImageRegionIterator ot (vecImg, vecImg->GetLargestPossibleRegion() ); ot.GoToBegin(); itk::ImageRegionIterator it (outimage, outimage->GetLargestPossibleRegion() ); typedef ImageType::PixelType VecPixType; typedef VecImgType::PixelType VarVecType; for (it.GoToBegin(); !it.IsAtEnd(); ++it) { VecPixType vec = it.Get(); VarVecType varVec(vec.GetVnlVector().data_block(), QBALL_ODFSIZE); ot.Set(varVec); ++ot; } nrrdWriter->SetInput( vecImg ); nrrdWriter->SetImageIO(io); - nrrdWriter->SetFileName(m_FileName); + nrrdWriter->SetFileName(this->GetOutputLocation().c_str()); nrrdWriter->UseCompressionOn(); try { nrrdWriter->Update(); } catch (itk::ExceptionObject e) { std::cout << e << std::endl; } try { setlocale(LC_ALL, currLocale.c_str()); } catch(...) { MITK_INFO << "Could not reset locale " << currLocale; } - m_Success = true; -} - - -void mitk::NrrdQBallImageWriter::SetInput( InputType* diffVolumes ) -{ - this->ProcessObject::SetNthInput( 0, diffVolumes ); } - -mitk::QBallImage* mitk::NrrdQBallImageWriter::GetInput() -{ - if ( this->GetNumberOfInputs() < 1 ) - { - return NULL; - } - else - { - return dynamic_cast ( this->ProcessObject::GetInput( 0 ) ); - } -} - - -std::vector mitk::NrrdQBallImageWriter::GetPossibleFileExtensions() +mitk::NrrdQBallImageWriter* mitk::NrrdQBallImageWriter::Clone() const { - std::vector possibleFileExtensions; - possibleFileExtensions.push_back(".qbi"); - possibleFileExtensions.push_back(".hqbi"); - return possibleFileExtensions; + return new NrrdQBallImageWriter(*this); } -std::string mitk::NrrdQBallImageWriter::GetSupportedBaseData() const +mitk::IFileWriter::ConfidenceLevel mitk::NrrdQBallImageWriter::GetConfidenceLevel() const { - return InputType::GetStaticNameOfClass(); + InputType::ConstPointer input = dynamic_cast(this->GetInput()); + if (input.IsNull() ) + { + return Unsupported; + } + else + { + return Supported; + } } diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdQBallImageWriter.h b/Modules/DiffusionImaging/DiffusionIO/mitkNrrdQBallImageWriter.h index a801ab9953..fafaeb7a22 100644 --- a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdQBallImageWriter.h +++ b/Modules/DiffusionImaging/DiffusionIO/mitkNrrdQBallImageWriter.h @@ -1,133 +1,54 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef _MITK_NRRDQBI_WRITER__H_ #define _MITK_NRRDQBI_WRITER__H_ -#include -#include +#include #include namespace mitk { /** * Writes diffusion volumes to a file * @ingroup Process */ -class NrrdQBallImageWriter : public mitk::FileWriterWithInformation -{ -public: - - mitkClassMacro( NrrdQBallImageWriter, mitk::FileWriterWithInformation ); - - mitkWriterMacro; - - itkFactorylessNewMacro(Self) - itkCloneMacro(Self) + class NrrdQBallImageWriter : public mitk::AbstractFileWriter + { + public: typedef mitk::QBallImage InputType; - /** - * Sets the filename of the file to write. - * @param FileName the name of the file to write. - */ - itkSetStringMacro( FileName ); - - /** - * @returns the name of the file to be written to disk. - */ - itkGetStringMacro( FileName ); - - /** - * @warning multiple write not (yet) supported - */ - itkSetStringMacro( FilePrefix ); - - /** - * @warning multiple write not (yet) supported - */ - itkGetStringMacro( FilePrefix ); - - /** - * @warning multiple write not (yet) supported - */ - itkSetStringMacro( FilePattern ); - - /** - * @warning multiple write not (yet) supported - */ - itkGetStringMacro( FilePattern ); - - /** - * Sets the input object for the filter. - * @param input the diffusion volumes to write to file. - */ - using itk::ProcessObject::SetInput; - void SetInput( InputType* input ); - - /** - * @returns the 0'th input object of the filter. - */ - InputType* GetInput(); - - /** - * Returns false if an error happened during writing - */ - itkGetMacro( Success, bool ); - - /** - * @return possible file extensions for the data type associated with the writer - */ - virtual std::vector GetPossibleFileExtensions(); - - std::string GetSupportedBaseData() const; - - // FileWriterWithInformation methods - virtual const char * GetDefaultFilename() { return "QBalls.qbi"; } - virtual const char * GetFileDialogPattern() { return "Q-Ball Images (*.qbi *.hqbi"; } - virtual const char * GetDefaultExtension() { return ".qbi"; } - virtual bool CanWriteBaseDataType(BaseData::Pointer data) { return (dynamic_cast(data.GetPointer()) != NULL); }; - virtual void DoWrite(BaseData::Pointer data) { - if (CanWriteBaseDataType(data)) { - this->SetInput(dynamic_cast(data.GetPointer())); - this->Update(); - } - }; - -protected: - NrrdQBallImageWriter(); - virtual ~NrrdQBallImageWriter(); - virtual void GenerateData(); - - std::string m_FileName; - - std::string m_FilePrefix; + using AbstractFileWriter::Write; + virtual void Write(); - std::string m_FilePattern; + virtual ConfidenceLevel GetConfidenceLevel() const; - bool m_Success; + protected: -}; + NrrdQBallImageWriter(const NrrdQBallImageWriter& other); + virtual mitk::NrrdQBallImageWriter* Clone() const; + }; } // end of namespace mitk #endif //_MITK_NRRDQBI_WRITER__H_ diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdQBallImageWriterFactory.cpp b/Modules/DiffusionImaging/DiffusionIO/mitkNrrdQBallImageWriterFactory.cpp deleted file mode 100644 index 8136f50c25..0000000000 --- a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdQBallImageWriterFactory.cpp +++ /dev/null @@ -1,76 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "mitkNrrdQBallImageWriterFactory.h" - -#include "itkCreateObjectFunction.h" -#include "itkVersion.h" - -#include - -namespace mitk -{ - -//template -//class CreateNrrdQBallImageWriter : public itk::CreateObjectFunctionBase -//{ -//public: - -// /** Standard class typedefs. */ -// typedef CreateNrrdQBallImageWriter Self; -// typedef itk::SmartPointer Pointer; - -// /** Methods from itk:LightObject. */ -// itkFactorylessNewMacro(Self); -// LightObject::Pointer CreateObject() { typename T::Pointer p = T::New(); -// p->Register(); -// return p.GetPointer(); -// } - -//protected: -// CreateNrrdQBallImageWriter() {} -// ~CreateNrrdQBallImageWriter() {} - -//private: -// CreateNrrdQBallImageWriter(const Self&); //purposely not implemented -// void operator=(const Self&); //purposely not implemented -//}; - -NrrdQBallImageWriterFactory::NrrdQBallImageWriterFactory() -{ - typedef short DiffusionPixelType; - this->RegisterOverride("IOWriter", - "NrrdQBallImageWriter", - "NrrdQBallImage Writer", - 1, - itk::CreateObjectFunction< mitk::NrrdQBallImageWriter >::New()); -} - -NrrdQBallImageWriterFactory::~NrrdQBallImageWriterFactory() -{ -} - -const char* NrrdQBallImageWriterFactory::GetITKSourceVersion() const -{ - return ITK_SOURCE_VERSION; -} - -const char* NrrdQBallImageWriterFactory::GetDescription() const -{ - return "NrrdQBallImageWriterFactory"; -} - -} // end namespace mitk diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdQBallImageWriterFactory.h b/Modules/DiffusionImaging/DiffusionIO/mitkNrrdQBallImageWriterFactory.h deleted file mode 100644 index e66d64bb8b..0000000000 --- a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdQBallImageWriterFactory.h +++ /dev/null @@ -1,66 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#ifndef NRRDQBI_WRITERFACTORY_H_HEADER_INCLUDED -#define NRRDQBI_WRITERFACTORY_H_HEADER_INCLUDED - -#include "itkObjectFactoryBase.h" -#include "mitkBaseData.h" - -namespace mitk -{ - -class NrrdQBallImageWriterFactory : public itk::ObjectFactoryBase -{ -public: - - mitkClassMacro( mitk::NrrdQBallImageWriterFactory, itk::ObjectFactoryBase ) - - /** Class methods used to interface with the registered factories. */ - virtual const char* GetITKSourceVersion(void) const; - virtual const char* GetDescription(void) const; - - /** Method for class instantiation. */ - itkFactorylessNewMacro(Self); - - /** Register one factory of this type */ - static void RegisterOneFactory(void) - { - static bool IsRegistered = false; - if ( !IsRegistered ) - { - NrrdQBallImageWriterFactory::Pointer fac = NrrdQBallImageWriterFactory::New(); - ObjectFactoryBase::RegisterFactory( fac ); - IsRegistered = true; - } - } - -protected: - NrrdQBallImageWriterFactory(); - ~NrrdQBallImageWriterFactory(); - -private: - NrrdQBallImageWriterFactory(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - -}; - -} // end namespace mitk - -#endif // NRRDQBI_WRITERFACTORY_H_HEADER_INCLUDED - - - diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdTensorImageIOFactory.cpp b/Modules/DiffusionImaging/DiffusionIO/mitkNrrdTensorImageIOFactory.cpp deleted file mode 100644 index de84648cf6..0000000000 --- a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdTensorImageIOFactory.cpp +++ /dev/null @@ -1,51 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "mitkNrrdTensorImageIOFactory.h" -#include "mitkIOAdapter.h" -#include "mitkNrrdTensorImageReader.h" - -#include "itkVersion.h" - - -namespace mitk -{ - -NrrdTensorImageIOFactory::NrrdTensorImageIOFactory() -{ - typedef NrrdTensorImageReader NrrdDTIReaderType; - this->RegisterOverride("mitkIOAdapter", - "mitkNrrdTensorImageReader", - "TensorImages IO", - 1, - itk::CreateObjectFunction >::New()); -} - -NrrdTensorImageIOFactory::~NrrdTensorImageIOFactory() -{ -} - -const char* NrrdTensorImageIOFactory::GetITKSourceVersion() const -{ - return ITK_SOURCE_VERSION; -} - -const char* NrrdTensorImageIOFactory::GetDescription() const -{ - return "NrrdTensorImage IO Factory, allows the loading of NRRD tensor data"; -} - -} // end namespace mitk diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdTensorImageIOFactory.h b/Modules/DiffusionImaging/DiffusionIO/mitkNrrdTensorImageIOFactory.h deleted file mode 100644 index fe2c928896..0000000000 --- a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdTensorImageIOFactory.h +++ /dev/null @@ -1,75 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ -#ifndef __MITK_NRRD_DTI_IO_FACTORY_H_HEADER__ -#define __MITK_NRRD_DTI_IO_FACTORY_H_HEADER__ - -#ifdef _MSC_VER -#pragma warning ( disable : 4786 ) -#endif - -#include "itkObjectFactoryBase.h" -#include "mitkBaseData.h" - -namespace mitk -{ -//##Documentation -//## @brief Create instances of NrrdTensorImageReader objects using an object factory. -//## -class NrrdTensorImageIOFactory : public itk::ObjectFactoryBase -{ -public: - /** Standard class typedefs. */ - typedef NrrdTensorImageIOFactory Self; - typedef itk::ObjectFactoryBase Superclass; - typedef itk::SmartPointer Pointer; - typedef itk::SmartPointer ConstPointer; - - /** Class methods used to interface with the registered factories. */ - virtual const char* GetITKSourceVersion(void) const; - virtual const char* GetDescription(void) const; - - /** Method for class instantiation. */ - itkFactorylessNewMacro(Self); - static NrrdTensorImageIOFactory* FactoryNew() { return new NrrdTensorImageIOFactory;} - /** Run-time type information (and related methods). */ - itkTypeMacro(NrrdTensorImageIOFactory, ObjectFactoryBase); - - /** Register one factory of this type */ - static void RegisterOneFactory(void) - { - static bool IsRegistered = false; - if ( !IsRegistered ) - { - NrrdTensorImageIOFactory::Pointer ugVtkWriterFactory = NrrdTensorImageIOFactory::New(); - ObjectFactoryBase::RegisterFactory( ugVtkWriterFactory ); - IsRegistered = true; - } - } - -protected: - NrrdTensorImageIOFactory(); - ~NrrdTensorImageIOFactory(); - -private: - NrrdTensorImageIOFactory(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - -}; - - -} // end namespace mitk - -#endif // __MITK_NRRD_DTI_IO_FACTORY_H_HEADER__ diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdTensorImageReader.cpp b/Modules/DiffusionImaging/DiffusionIO/mitkNrrdTensorImageReader.cpp index 5dd4300541..449ce2699a 100644 --- a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdTensorImageReader.cpp +++ b/Modules/DiffusionImaging/DiffusionIO/mitkNrrdTensorImageReader.cpp @@ -1,480 +1,441 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkNrrdTensorImageReader.h" +#include +#include "mitkDiffusionIOMimeTypes.h" #include "itkImageFileReader.h" #include "itkImageRegionIterator.h" #include "itkMetaDataObject.h" #include "itkNrrdImageIO.h" #include #include "mitkITKImageImport.h" #include "mitkImageDataItem.h" namespace mitk { -void NrrdTensorImageReader -::GenerateData() -{ - if ( m_FileName == "") + NrrdTensorImageReader::NrrdTensorImageReader(const NrrdTensorImageReader& other) + : mitk::AbstractFileReader(other) + { + } + + NrrdTensorImageReader::NrrdTensorImageReader() + : mitk::AbstractFileReader( CustomMimeType( mitk::DiffusionIOMimeTypes::DTI_MIMETYPE_NAME() ), mitk::DiffusionIOMimeTypes::DTI_MIMETYPE_DESCRIPTION ) + { + m_ServiceReg = this->RegisterService(); + } + + NrrdTensorImageReader::~NrrdTensorImageReader() + { + } + + std::vector > NrrdTensorImageReader::Read() + { + std::vector > result; + std::string location = GetInputLocation(); + + if ( location == "") { - throw itk::ImageFileReaderException(__FILE__, __LINE__, "Sorry, the filename is empty!"); + throw itk::ImageFileReaderException(__FILE__, __LINE__, "Sorry, the filename is empty!"); } else { - try + try + { + const std::string& locale = "C"; + const std::string& currLocale = setlocale( LC_ALL, NULL ); + + if ( locale.compare(currLocale)!=0 ) { - const std::string& locale = "C"; - const std::string& currLocale = setlocale( LC_ALL, NULL ); + try + { + setlocale(LC_ALL, locale.c_str()); + } + catch(...) + { + MITK_INFO << "Could not set locale " << locale; + } + } - if ( locale.compare(currLocale)!=0 ) + try + { + std::string fname3 = "temp_dti.nii"; + itksys::SystemTools::CopyAFile(location.c_str(), fname3.c_str()); + + typedef itk::VectorImage ImageType; + itk::NiftiImageIO::Pointer io = itk::NiftiImageIO::New(); + typedef itk::ImageFileReader FileReaderType; + FileReaderType::Pointer reader = FileReaderType::New(); + reader->SetImageIO(io); + reader->SetFileName(fname3); + reader->Update(); + ImageType::Pointer img = reader->GetOutput(); + + typedef itk::Image,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->SetRegions( img->GetLargestPossibleRegion()); + vecImg->Allocate(); + + itk::ImageRegionIterator ot (vecImg, vecImg->GetLargestPossibleRegion() ); + ot.GoToBegin(); + + itk::ImageRegionIterator it (img, img->GetLargestPossibleRegion() ); + it.GoToBegin(); + + typedef ImageType::PixelType VarPixType; + typedef VecImgType::PixelType FixPixType; + int numComponents = img->GetNumberOfComponentsPerPixel(); + + if (numComponents==6) + { + MITK_INFO << "Trying to load dti as 6-comp nifti ..."; + while (!it.IsAtEnd()) { - try - { - setlocale(LC_ALL, locale.c_str()); - } - catch(...) - { - MITK_INFO << "Could not set locale " << locale; - } + VarPixType vec = it.Get(); + FixPixType fixVec(vec.GetDataPointer()); + + itk::DiffusionTensor3D 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; } - - try + } + else if(numComponents==9) + { + MITK_INFO << "Trying to load dti as 9-comp nifti ..."; + while (!it.IsAtEnd()) { - std::string fname3 = "temp_dti.nii"; - itksys::SystemTools::CopyAFile(m_FileName.c_str(), fname3.c_str()); - - typedef itk::VectorImage ImageType; - itk::NiftiImageIO::Pointer io = itk::NiftiImageIO::New(); - typedef itk::ImageFileReader FileReaderType; - FileReaderType::Pointer reader = FileReaderType::New(); - reader->SetImageIO(io); - reader->SetFileName(fname3); - reader->Update(); - ImageType::Pointer img = reader->GetOutput(); - - typedef itk::Image,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->SetRegions( img->GetLargestPossibleRegion()); - vecImg->Allocate(); - - itk::ImageRegionIterator ot (vecImg, vecImg->GetLargestPossibleRegion() ); - ot.GoToBegin(); - - itk::ImageRegionIterator it (img, img->GetLargestPossibleRegion() ); - it.GoToBegin(); - - typedef ImageType::PixelType VarPixType; - typedef VecImgType::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()); - - itk::DiffusionTensor3D 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(); - itk::DiffusionTensor3D 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 ImageType; - typedef itk::ImageFileReader 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()) - { - itk::DiffusionTensor3D 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; teGetPixel(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!"); - - FixPixType fixVec(tensor); - ot.Set(fixVec); - ++ot; - } - } - this->GetOutput()->InitializeByItk(vecImg.GetPointer()); - this->GetOutput()->SetVolume(vecImg->GetBufferPointer()); + VarPixType vec = it.Get(); + itk::DiffusionTensor3D 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; } - catch(...) + } + else if (numComponents==1) + { + MITK_INFO << "Trying to load dti as 4D nifti ..."; + typedef itk::Image ImageType; + typedef itk::ImageFileReader 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()) { - MITK_INFO << "Trying to load dti as nrrd ..."; - - typedef itk::VectorImage ImageType; - itk::NrrdImageIO::Pointer io = itk::NrrdImageIO::New(); - typedef itk::ImageFileReader FileReaderType; - FileReaderType::Pointer reader = FileReaderType::New(); - reader->SetImageIO(io); - reader->SetFileName(this->m_FileName); - reader->Update(); - ImageType::Pointer img = reader->GetOutput(); - - typedef itk::Image,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->SetRegions( img->GetLargestPossibleRegion()); - vecImg->Allocate(); - - itk::ImageRegionIterator ot (vecImg, vecImg->GetLargestPossibleRegion() ); - ot.GoToBegin(); - - itk::ImageRegionIterator it (img, img->GetLargestPossibleRegion() ); - it.GoToBegin(); - - typedef ImageType::PixelType VarPixType; - typedef VecImgType::PixelType FixPixType; - int numComponents = img->GetNumberOfComponentsPerPixel(); - - itk::MetaDataDictionary imgMetaDictionary = img->GetMetaDataDictionary(); - std::vector imgMetaKeys = imgMetaDictionary.GetKeys(); - std::vector::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 (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(); - } - } - } + itk::DiffusionTensor3D tensor; + ImageType::IndexType idx; + idx[0] = ot.GetIndex()[0]; idx[1] = ot.GetIndex()[1]; idx[2] = ot.GetIndex()[2]; - if (numComponents==6) - { - while (!it.IsAtEnd()) - { - // T'=RTR' - VarPixType vec = it.Get(); - FixPixType fixVec(vec.GetDataPointer()); - - if(readFrame) - { - itk::DiffusionTensor3D 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(); - itk::DiffusionTensor3D 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) + if (size[3]==6) + { + for (unsigned int te=0; te ImageType; - itk::NrrdImageIO::Pointer io = itk::NrrdImageIO::New(); - typedef itk::ImageFileReader FileReaderType; - FileReaderType::Pointer reader = FileReaderType::New(); - reader->SetImageIO(io); - reader->SetFileName(this->m_FileName); - reader->Update(); - ImageType::Pointer img = reader->GetOutput(); - - itk::Size<4> size = img->GetLargestPossibleRegion().GetSize(); - - while (!ot.IsAtEnd()) - { - itk::DiffusionTensor3D 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; teGetPixel(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; - } + idx[3] = te; + tensor.SetElement(te, img->GetPixel(idx)); } - else - { - throw itk::ImageFileReaderException(__FILE__, __LINE__, "Image has wrong number of pixel components!"); - } - - this->GetOutput()->InitializeByItk(vecImg.GetPointer()); - this->GetOutput()->SetVolume(vecImg->GetBufferPointer()); - + } + 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 ImageType; + itk::NrrdImageIO::Pointer io = itk::NrrdImageIO::New(); + typedef itk::ImageFileReader FileReaderType; + FileReaderType::Pointer reader = FileReaderType::New(); + reader->SetImageIO(io); + reader->SetFileName(location); + reader->Update(); + ImageType::Pointer img = reader->GetOutput(); + + typedef itk::Image,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->SetRegions( img->GetLargestPossibleRegion()); + vecImg->Allocate(); + + itk::ImageRegionIterator ot (vecImg, vecImg->GetLargestPossibleRegion() ); + ot.GoToBegin(); + + itk::ImageRegionIterator it (img, img->GetLargestPossibleRegion() ); + it.GoToBegin(); + + typedef ImageType::PixelType VarPixType; + typedef VecImgType::PixelType FixPixType; + int numComponents = img->GetNumberOfComponentsPerPixel(); + + itk::MetaDataDictionary imgMetaDictionary = img->GetMetaDataDictionary(); + std::vector imgMetaKeys = imgMetaDictionary.GetKeys(); + std::vector::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 (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(); + } + } + } - try + if (numComponents==6) + { + while (!it.IsAtEnd()) { - setlocale(LC_ALL, currLocale.c_str()); + // T'=RTR' + VarPixType vec = it.Get(); + FixPixType fixVec(vec.GetDataPointer()); + + if(readFrame) + { + itk::DiffusionTensor3D 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; } - catch(...) + } + else if(numComponents==9) + { + while (!it.IsAtEnd()) { - MITK_INFO << "Could not reset locale " << currLocale; + VarPixType vec = it.Get(); + itk::DiffusionTensor3D 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 ImageType; + itk::NrrdImageIO::Pointer io = itk::NrrdImageIO::New(); + typedef itk::ImageFileReader 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()) + { + itk::DiffusionTensor3D 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; teGetPixel(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) + + try { - throw itk::ImageFileReaderException(__FILE__, __LINE__, e.what()); + setlocale(LC_ALL, currLocale.c_str()); } catch(...) { - throw itk::ImageFileReaderException(__FILE__, __LINE__, "Sorry, an error occurred while reading the requested DTI file!"); + MITK_INFO << "Could not reset locale " << currLocale; } - } -} - -void NrrdTensorImageReader::GenerateOutputInformation() -{ - -} - - - -const char* NrrdTensorImageReader -::GetFileName() const -{ - return m_FileName.c_str(); -} - -void NrrdTensorImageReader -::SetFileName(const char* aFileName) -{ - m_FileName = aFileName; -} - - -const char* NrrdTensorImageReader -::GetFilePrefix() const -{ - return m_FilePrefix.c_str(); -} - - -void NrrdTensorImageReader -::SetFilePrefix(const char* aFilePrefix) -{ - m_FilePrefix = aFilePrefix; -} - - -const char* NrrdTensorImageReader -::GetFilePattern() const -{ - return m_FilePattern.c_str(); -} - - -void NrrdTensorImageReader -::SetFilePattern(const char* aFilePattern) -{ - m_FilePattern = aFilePattern; -} - - -bool NrrdTensorImageReader -::CanReadFile(const std::string filename, const std::string /*filePrefix*/, const std::string /*filePattern*/) -{ - // First check the extension - if( filename == "" ) - { - return false; - } - std::string ext = itksys::SystemTools::GetFilenameLastExtension(filename); - ext = itksys::SystemTools::LowerCase(ext); - - if (ext == ".hdti" || ext == ".dti") - { - return true; + } + 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 false; -} + return result; + } itk::DiffusionTensor3D NrrdTensorImageReader ::ConvertMatrixTypeToFixedArrayType(const itk::DiffusionTensor3D::Superclass::MatrixType & matrix) { /* | 0 1 2 | * | X 3 4 | * | X X 5 | */ itk::DiffusionTensor3D arr; arr.SetElement(0,matrix(0,0)); arr.SetElement(1,matrix(0,1)); arr.SetElement(2,matrix(0,2)); arr.SetElement(3,matrix(1,3)); arr.SetElement(4,matrix(1,4)); arr.SetElement(5,matrix(2,5)); return arr; } } //namespace MITK + +mitk::NrrdTensorImageReader* mitk::NrrdTensorImageReader::Clone() const +{ + return new NrrdTensorImageReader(*this); +} diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdTensorImageReader.h b/Modules/DiffusionImaging/DiffusionIO/mitkNrrdTensorImageReader.h index 8c51504540..22b57938ef 100644 --- a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdTensorImageReader.h +++ b/Modules/DiffusionImaging/DiffusionIO/mitkNrrdTensorImageReader.h @@ -1,73 +1,63 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef __mitkNrrdTensorImageReader_h #define __mitkNrrdTensorImageReader_h #include "mitkCommon.h" #include "itkVectorContainer.h" -#include "mitkFileReader.h" #include "vnl/vnl_vector_fixed.h" #include "mitkTensorImage.h" -#include "mitkTensorImageSource.h" #include "itkVectorImage.h" #include "itkDiffusionTensor3D.h" +#include +#include +#include namespace mitk { /** \brief */ - class NrrdTensorImageReader : public mitk::TensorImageSource, public FileReader + class NrrdTensorImageReader : public mitk::AbstractFileReader { public: typedef mitk::TensorImage OutputType; - typedef mitk::TensorImageSource DTImgSourceType; typedef itk::Matrix< float, 3, 3 > MeasurementFrameType; - mitkClassMacro( NrrdTensorImageReader, DTImgSourceType ); - itkFactorylessNewMacro(Self) - itkCloneMacro(Self) + NrrdTensorImageReader(const NrrdTensorImageReader& other); + NrrdTensorImageReader(); + virtual ~NrrdTensorImageReader(); - const char* GetFileName() const; - void SetFileName(const char* aFileName); - const char* GetFilePrefix() const; - void SetFilePrefix(const char* aFilePrefix); - const char* GetFilePattern() const; - void SetFilePattern(const char* aFilePattern); - - static bool CanReadFile(const std::string filename, const std::string filePrefix, const std::string filePattern); + using AbstractFileReader::Read; + virtual std::vector > Read(); protected: - /** Does the real work. */ - virtual void GenerateData(); - virtual void GenerateOutputInformation(); - - std::string m_FileName; - std::string m_FilePrefix; - std::string m_FilePattern; private: - void operator=(const Self&); //purposely not implemented + NrrdTensorImageReader* Clone() const; + + us::ServiceRegistration m_ServiceReg; + itk::DiffusionTensor3D ConvertMatrixTypeToFixedArrayType(const itk::DiffusionTensor3D::Superclass::MatrixType & matrix); }; } //namespace MITK #endif // __mitkNrrdTensorImageReader_h diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdTensorImageWriter.cpp b/Modules/DiffusionImaging/DiffusionIO/mitkNrrdTensorImageWriter.cpp index 816af51a52..6acfddf2d9 100644 --- a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdTensorImageWriter.cpp +++ b/Modules/DiffusionImaging/DiffusionIO/mitkNrrdTensorImageWriter.cpp @@ -1,132 +1,122 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkNrrdTensorImageWriter.h" #include "itkMetaDataDictionary.h" #include "itkMetaDataObject.h" #include "itkNrrdImageIO.h" #include "itkImageFileWriter.h" #include "itkDiffusionTensor3D.h" #include "mitkImageCast.h" +#include "mitkDiffusionIOMimeTypes.h" mitk::NrrdTensorImageWriter::NrrdTensorImageWriter() - : m_FileName(""), m_FilePrefix(""), m_FilePattern(""), m_Success(false) + : AbstractFileWriter(mitk::TensorImage::GetStaticNameOfClass(), CustomMimeType( mitk::DiffusionIOMimeTypes::DTI_MIMETYPE_NAME() ), mitk::DiffusionIOMimeTypes::DTI_MIMETYPE_DESCRIPTION ) +{ + RegisterService(); +} + +mitk::NrrdTensorImageWriter::NrrdTensorImageWriter(const mitk::NrrdTensorImageWriter& other) + : AbstractFileWriter(other) { - this->SetNumberOfRequiredInputs( 1 ); } mitk::NrrdTensorImageWriter::~NrrdTensorImageWriter() {} -void mitk::NrrdTensorImageWriter::GenerateData() +void mitk::NrrdTensorImageWriter::Write() { - m_Success = false; - InputType* input = this->GetInput(); - if (input == NULL) - { - itkWarningMacro(<<"Sorry, input to NrrdTensorImageWriter is NULL!"); - return; - } - if ( m_FileName == "" ) - { - itkWarningMacro( << "Sorry, filename has not been set!" ); - return ; - } - 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; - } - } - - itk::NrrdImageIO::Pointer io = itk::NrrdImageIO::New(); - io->SetFileType( itk::ImageIOBase::Binary ); - io->UseCompressionOn(); - - typedef itk::Image,3> ImageType; - typedef itk::ImageFileWriter WriterType; - WriterType::Pointer nrrdWriter = WriterType::New(); - - ImageType::Pointer outimage = ImageType::New(); - CastToItkImage(input, outimage); - - nrrdWriter->SetInput( outimage ); - nrrdWriter->SetImageIO(io); - nrrdWriter->SetFileName(m_FileName); - nrrdWriter->UseCompressionOn(); - - try - { - nrrdWriter->Update(); - } - catch (itk::ExceptionObject e) - { - std::cout << e << std::endl; - } - + InputType::ConstPointer input = dynamic_cast(this->GetInput()); + if (input.IsNull() ) + { + MITK_ERROR <<"Sorry, input to NrrdTensorImageWriter is NULL!"; + return; + } + if ( this->GetOutputLocation().c_str() == "" ) + { + MITK_ERROR << "Sorry, filename has not been set!" ; + return ; + } + const std::string& locale = "C"; + const std::string& currLocale = setlocale( LC_ALL, NULL ); + if ( locale.compare(currLocale)!=0 ) + { try { - setlocale(LC_ALL, currLocale.c_str()); + setlocale(LC_ALL, locale.c_str()); } catch(...) { - MITK_INFO << "Could not reset locale " << currLocale; + MITK_INFO << "Could not set locale " << locale; } - m_Success = true; -} - - -void mitk::NrrdTensorImageWriter::SetInput( InputType* diffVolumes ) -{ - this->ProcessObject::SetNthInput( 0, diffVolumes ); -} - + } + + itk::NrrdImageIO::Pointer io = itk::NrrdImageIO::New(); + io->SetFileType( itk::ImageIOBase::Binary ); + io->UseCompressionOn(); + + typedef itk::Image,3> ImageType; + typedef itk::ImageFileWriter WriterType; + WriterType::Pointer nrrdWriter = WriterType::New(); + + ImageType::Pointer outimage = ImageType::New(); + CastToItkImage(input, outimage); + + nrrdWriter->SetInput( outimage ); + nrrdWriter->SetImageIO(io); + nrrdWriter->SetFileName(this->GetOutputLocation().c_str()); + nrrdWriter->UseCompressionOn(); + + try + { + nrrdWriter->Update(); + } + catch (itk::ExceptionObject e) + { + std::cout << e << std::endl; + } + + try + { + setlocale(LC_ALL, currLocale.c_str()); + } + catch(...) + { + MITK_INFO << "Could not reset locale " << currLocale; + } -mitk::TensorImage* mitk::NrrdTensorImageWriter::GetInput() -{ - if ( this->GetNumberOfInputs() < 1 ) - { - return NULL; - } - else - { - return dynamic_cast ( this->ProcessObject::GetInput( 0 ) ); - } } - -std::vector mitk::NrrdTensorImageWriter::GetPossibleFileExtensions() +mitk::NrrdTensorImageWriter* mitk::NrrdTensorImageWriter::Clone() const { - std::vector possibleFileExtensions; - possibleFileExtensions.push_back(".dti"); - possibleFileExtensions.push_back(".hdti"); - return possibleFileExtensions; + return new NrrdTensorImageWriter(*this); } -std::string mitk::NrrdTensorImageWriter::GetSupportedBaseData() const +mitk::IFileWriter::ConfidenceLevel mitk::NrrdTensorImageWriter::GetConfidenceLevel() const { - return InputType::GetStaticNameOfClass(); + InputType::ConstPointer input = dynamic_cast(this->GetInput()); + if (input.IsNull() ) + { + return Unsupported; + } + else + { + return Supported; + } } diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdTensorImageWriter.h b/Modules/DiffusionImaging/DiffusionIO/mitkNrrdTensorImageWriter.h index 15af42a65f..12bf455042 100644 --- a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdTensorImageWriter.h +++ b/Modules/DiffusionImaging/DiffusionIO/mitkNrrdTensorImageWriter.h @@ -1,133 +1,54 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef _MITK_NRRDDTI_WRITER__H_ #define _MITK_NRRDDTI_WRITER__H_ -#include -#include +#include #include namespace mitk { /** * Writes diffusion volumes to a file * @ingroup Process */ -class NrrdTensorImageWriter : public mitk::FileWriterWithInformation +class NrrdTensorImageWriter : public mitk::AbstractFileWriter { public: - mitkClassMacro( NrrdTensorImageWriter, mitk::FileWriterWithInformation ); - - mitkWriterMacro; - - itkFactorylessNewMacro(Self) - itkCloneMacro(Self) - typedef mitk::TensorImage InputType; - /** - * Sets the filename of the file to write. - * @param FileName the name of the file to write. - */ - itkSetStringMacro( FileName ); - - /** - * @returns the name of the file to be written to disk. - */ - itkGetStringMacro( FileName ); - - /** - * @warning multiple write not (yet) supported - */ - itkSetStringMacro( FilePrefix ); - - /** - * @warning multiple write not (yet) supported - */ - itkGetStringMacro( FilePrefix ); - - /** - * @warning multiple write not (yet) supported - */ - itkSetStringMacro( FilePattern ); - - /** - * @warning multiple write not (yet) supported - */ - itkGetStringMacro( FilePattern ); - - /** - * Sets the input object for the filter. - * @param input the diffusion volumes to write to file. - */ - using itk::ProcessObject::SetInput; - void SetInput( InputType* input ); - - /** - * @returns the 0'th input object of the filter. - */ - InputType* GetInput(); - - /** - * Returns false if an error happened during writing - */ - itkGetMacro( Success, bool ); - - /** - * @return possible file extensions for the data type associated with the writer - */ - virtual std::vector GetPossibleFileExtensions(); - - std::string GetSupportedBaseData() const; - - // FileWriterWithInformation methods - virtual const char * GetDefaultFilename() { return "Tensors.dti"; } - virtual const char * GetFileDialogPattern() { return "Tensor Images (*.dti *.hdti)"; } - virtual const char * GetDefaultExtension() { return ".dti"; } - virtual bool CanWriteBaseDataType(BaseData::Pointer data) { return (dynamic_cast(data.GetPointer()) != NULL); }; - virtual void DoWrite(BaseData::Pointer data) { - if (CanWriteBaseDataType(data)) { - this->SetInput(dynamic_cast(data.GetPointer())); - this->Update(); - } - }; - -protected: - NrrdTensorImageWriter(); - virtual ~NrrdTensorImageWriter(); - virtual void GenerateData(); - - std::string m_FileName; + using AbstractFileWriter::Write; + virtual void Write(); - std::string m_FilePrefix; + virtual ConfidenceLevel GetConfidenceLevel() const; - std::string m_FilePattern; - - bool m_Success; +protected: + NrrdTensorImageWriter(const NrrdTensorImageWriter& other); + virtual mitk::NrrdTensorImageWriter* Clone() const; }; } // end of namespace mitk #endif //_MITK_NRRDDTI_WRITER__H_ diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdTensorImageWriterFactory.cpp b/Modules/DiffusionImaging/DiffusionIO/mitkNrrdTensorImageWriterFactory.cpp deleted file mode 100644 index 7dc6ce5bca..0000000000 --- a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdTensorImageWriterFactory.cpp +++ /dev/null @@ -1,76 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "mitkNrrdTensorImageWriterFactory.h" - -#include "itkCreateObjectFunction.h" -#include "itkVersion.h" - -#include - -namespace mitk -{ - -//template -//class CreateNrrdTensorImageWriter : public itk::CreateObjectFunctionBase -//{ -//public: - -// /** Standard class typedefs. */ -// typedef CreateNrrdTensorImageWriter Self; -// typedef itk::SmartPointer Pointer; - -// /** Methods from itk:LightObject. */ -// itkFactorylessNewMacro(Self); -// LightObject::Pointer CreateObject() { typename T::Pointer p = T::New(); -// p->Register(); -// return p.GetPointer(); -// } - -//protected: -// CreateNrrdTensorImageWriter() {} -// ~CreateNrrdTensorImageWriter() {} - -//private: -// CreateNrrdTensorImageWriter(const Self&); //purposely not implemented -// void operator=(const Self&); //purposely not implemented -//}; - -NrrdTensorImageWriterFactory::NrrdTensorImageWriterFactory() -{ - typedef short DiffusionPixelType; - this->RegisterOverride("IOWriter", - "NrrdTensorImageWriter", - "NrrdTensorImage Writer", - 1, - itk::CreateObjectFunction< mitk::NrrdTensorImageWriter >::New()); -} - -NrrdTensorImageWriterFactory::~NrrdTensorImageWriterFactory() -{ -} - -const char* NrrdTensorImageWriterFactory::GetITKSourceVersion() const -{ - return ITK_SOURCE_VERSION; -} - -const char* NrrdTensorImageWriterFactory::GetDescription() const -{ - return "NrrdTensorImageWriterFactory"; -} - -} // end namespace mitk diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdTensorImageWriterFactory.h b/Modules/DiffusionImaging/DiffusionIO/mitkNrrdTensorImageWriterFactory.h deleted file mode 100644 index 7917b57c9d..0000000000 --- a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdTensorImageWriterFactory.h +++ /dev/null @@ -1,66 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#ifndef NRRDDTI_WRITERFACTORY_H_HEADER_INCLUDED -#define NRRDDTI_WRITERFACTORY_H_HEADER_INCLUDED - -#include "itkObjectFactoryBase.h" -#include "mitkBaseData.h" - -namespace mitk -{ - -class NrrdTensorImageWriterFactory : public itk::ObjectFactoryBase -{ -public: - - mitkClassMacro( mitk::NrrdTensorImageWriterFactory, itk::ObjectFactoryBase ) - - /** Class methods used to interface with the registered factories. */ - virtual const char* GetITKSourceVersion(void) const; - virtual const char* GetDescription(void) const; - - /** Method for class instantiation. */ - itkFactorylessNewMacro(Self); - - /** Register one factory of this type */ - static void RegisterOneFactory(void) - { - static bool IsRegistered = false; - if ( !IsRegistered ) - { - NrrdTensorImageWriterFactory::Pointer ugVtkWriterFactory = NrrdTensorImageWriterFactory::New(); - ObjectFactoryBase::RegisterFactory( ugVtkWriterFactory ); - IsRegistered = true; - } - } - -protected: - NrrdTensorImageWriterFactory(); - ~NrrdTensorImageWriterFactory(); - -private: - NrrdTensorImageWriterFactory(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - -}; - -} // end namespace mitk - -#endif // NRRDDTI_WRITERFACTORY_H_HEADER_INCLUDED - - - diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkQBallImageSerializer.cpp b/Modules/DiffusionImaging/DiffusionIO/mitkQBallImageSerializer.cpp index 015af4773e..94065ae642 100644 --- a/Modules/DiffusionImaging/DiffusionIO/mitkQBallImageSerializer.cpp +++ b/Modules/DiffusionImaging/DiffusionIO/mitkQBallImageSerializer.cpp @@ -1,74 +1,74 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkQBallImageSerializer.h" #include "mitkQBallImage.h" #include "mitkNrrdQBallImageWriter.h" #include MITK_REGISTER_SERIALIZER(QBallImageSerializer) mitk::QBallImageSerializer::QBallImageSerializer() { } mitk::QBallImageSerializer::~QBallImageSerializer() { } std::string mitk::QBallImageSerializer::Serialize() { const QBallImage* image = dynamic_cast( m_Data.GetPointer() ); if (image == NULL) { MITK_ERROR << " Object at " << (const void*) this->m_Data << " is not an mitk::NrrdQBallImage. Cannot serialize as NrrdQBallImage."; return ""; } std::string filename( this->GetUniqueFilenameInWorkingDirectory() ); filename += "_"; filename += m_FilenameHint; filename += ".qbi"; std::string fullname(m_WorkingDirectory); fullname += "/"; fullname += itksys::SystemTools::ConvertToOutputPath(filename.c_str()); try { - NrrdQBallImageWriter::Pointer writer = NrrdQBallImageWriter::New(); - writer->SetFileName(fullname); - writer->SetInput(const_cast(image)); - writer->Write(); + NrrdQBallImageWriter writer; + writer.SetOutputLocation(fullname); + writer.SetInput(const_cast(image)); + writer.Write(); } catch (std::exception& e) { MITK_ERROR << " Error serializing object at " << (const void*) this->m_Data << " to " << fullname << ": " << e.what(); return ""; } return filename; } diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkTensorImageSerializer.cpp b/Modules/DiffusionImaging/DiffusionIO/mitkTensorImageSerializer.cpp index a74fc216b2..9df84889b9 100644 --- a/Modules/DiffusionImaging/DiffusionIO/mitkTensorImageSerializer.cpp +++ b/Modules/DiffusionImaging/DiffusionIO/mitkTensorImageSerializer.cpp @@ -1,74 +1,74 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkTensorImageSerializer.h" #include "mitkTensorImage.h" #include "mitkNrrdTensorImageWriter.h" #include MITK_REGISTER_SERIALIZER(TensorImageSerializer) mitk::TensorImageSerializer::TensorImageSerializer() { } mitk::TensorImageSerializer::~TensorImageSerializer() { } std::string mitk::TensorImageSerializer::Serialize() { const TensorImage* image = dynamic_cast( m_Data.GetPointer() ); if (image == NULL) { MITK_ERROR << " Object at " << (const void*) this->m_Data << " is not an mitk::NrrdTensorImage. Cannot serialize as NrrdTensorImage."; return ""; } std::string filename( this->GetUniqueFilenameInWorkingDirectory() ); filename += "_"; filename += m_FilenameHint; filename += ".dti"; std::string fullname(m_WorkingDirectory); fullname += "/"; fullname += itksys::SystemTools::ConvertToOutputPath(filename.c_str()); try { - NrrdTensorImageWriter::Pointer writer = NrrdTensorImageWriter::New(); - writer->SetFileName(fullname); - writer->SetInput(const_cast(image)); - writer->Write(); + NrrdTensorImageWriter writer; + writer.SetOutputLocation(fullname); + writer.SetInput(const_cast(image)); + writer.Write(); } catch (std::exception& e) { MITK_ERROR << " Error serializing object at " << (const void*) this->m_Data << " to " << fullname << ": " << e.what(); return ""; } return filename; } diff --git a/Modules/DiffusionImaging/FiberTracking/Testing/mitkFiberBundleXReaderWriterTest.cpp b/Modules/DiffusionImaging/FiberTracking/Testing/mitkFiberBundleXReaderWriterTest.cpp index 8e36f84548..cc2a56745f 100644 --- a/Modules/DiffusionImaging/FiberTracking/Testing/mitkFiberBundleXReaderWriterTest.cpp +++ b/Modules/DiffusionImaging/FiberTracking/Testing/mitkFiberBundleXReaderWriterTest.cpp @@ -1,75 +1,74 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkTestingMacros.h" #include -#include #include #include #include #include #include #include "mitkTestFixture.h" class mitkFiberBundleXReaderWriterTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkFiberBundleXReaderWriterTestSuite); MITK_TEST(Equal_SaveLoad_ReturnsTrue); CPPUNIT_TEST_SUITE_END(); private: /** Members used inside the different (sub-)tests. All members are initialized via setUp().*/ mitk::FiberBundleX::Pointer fib1; mitk::FiberBundleX::Pointer fib2; public: void setUp() { fib1 = NULL; fib2 = NULL; const std::string s1="", s2=""; std::string filename = GetTestDataFilePath("DiffusionImaging/fiberBundleX.fib"); std::vector fibInfile = mitk::BaseDataIO::LoadBaseDataFromFile( filename, s1, s2, false ); mitk::BaseData::Pointer baseData = fibInfile.at(0); fib1 = dynamic_cast(baseData.GetPointer()); } void tearDown() { fib1 = NULL; fib2 = NULL; } void Equal_SaveLoad_ReturnsTrue() { const std::string s1="", s2=""; mitk::IOUtil::Save(fib1.GetPointer(), std::string(MITK_TEST_OUTPUT_DIR)+"/writerTest.fib"); std::vector fibInfile = mitk::BaseDataIO::LoadBaseDataFromFile( std::string(MITK_TEST_OUTPUT_DIR)+"/writerTest.fib", s1, s2, false ); mitk::BaseData::Pointer baseData = fibInfile.at(0); fib2 = dynamic_cast(baseData.GetPointer()); CPPUNIT_ASSERT_MESSAGE("Should be equal", fib1->Equals(fib2)); //MITK_ASSERT_EQUAL(fib1, fib2, "A saved and re-loaded file should be equal"); } }; MITK_TEST_SUITE_REGISTRATION(mitkFiberBundleXReaderWriter) diff --git a/Modules/DiffusionImaging/FiberTracking/Testing/mitkFiberExtractionTest.cpp b/Modules/DiffusionImaging/FiberTracking/Testing/mitkFiberExtractionTest.cpp index e8aaee34b0..66823a77b9 100644 --- a/Modules/DiffusionImaging/FiberTracking/Testing/mitkFiberExtractionTest.cpp +++ b/Modules/DiffusionImaging/FiberTracking/Testing/mitkFiberExtractionTest.cpp @@ -1,106 +1,105 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include #include #include #include #include #include -#include #include /**Documentation * Test if fiber transfortaiom methods work correctly */ int mitkFiberExtractionTest(int argc, char* argv[]) { MITK_TEST_BEGIN("mitkFiberExtractionTest"); /// \todo Fix VTK memory leaks. Bug 18097. vtkDebugLeaks::SetExitError(0); MITK_INFO << "argc: " << argc; MITK_TEST_CONDITION_REQUIRED(argc==13,"check for input data") try{ mitk::FiberBundleX::Pointer groundTruthFibs = dynamic_cast(mitk::IOUtil::LoadDataNode(argv[1])->GetData()); mitk::FiberBundleX::Pointer testFibs = dynamic_cast(mitk::IOUtil::LoadDataNode(argv[2])->GetData()); // test planar figure based extraction mitk::PlanarFigure::Pointer pf1 = dynamic_cast(mitk::IOUtil::LoadDataNode(argv[3])->GetData()); mitk::PlanarFigure::Pointer pf2 = dynamic_cast(mitk::IOUtil::LoadDataNode(argv[4])->GetData()); mitk::PlanarFigure::Pointer pf3 = dynamic_cast(mitk::IOUtil::LoadDataNode(argv[5])->GetData()); MITK_INFO << "TEST1"; mitk::PlanarFigureComposite::Pointer pfc1 = mitk::PlanarFigureComposite::New(); pfc1->setOperationType(mitk::PFCOMPOSITION_AND_OPERATION); pfc1->addPlanarFigure(dynamic_cast(pf2.GetPointer())); pfc1->addPlanarFigure(dynamic_cast(pf3.GetPointer())); MITK_INFO << "TEST2"; mitk::PlanarFigureComposite::Pointer pfc2 = mitk::PlanarFigureComposite::New(); pfc2->setOperationType(mitk::PFCOMPOSITION_OR_OPERATION); pfc2->addPlanarFigure(dynamic_cast(pf1.GetPointer())); pfc2->addPlanarFigure(pfc1.GetPointer()); MITK_INFO << "TEST3"; mitk::FiberBundleX::Pointer extractedFibs = groundTruthFibs->ExtractFiberSubset(pfc2); MITK_INFO << "TEST4"; MITK_TEST_CONDITION_REQUIRED(extractedFibs->Equals(testFibs),"check planar figure extraction") MITK_INFO << "TEST5"; // test subtraction and addition mitk::FiberBundleX::Pointer notExtractedFibs = groundTruthFibs->SubtractBundle(extractedFibs); MITK_INFO << argv[11]; testFibs = dynamic_cast(mitk::IOUtil::LoadDataNode(argv[11])->GetData()); MITK_TEST_CONDITION_REQUIRED(notExtractedFibs->Equals(testFibs),"check bundle subtraction") mitk::FiberBundleX::Pointer joinded = extractedFibs->AddBundle(notExtractedFibs); testFibs = dynamic_cast(mitk::IOUtil::LoadDataNode(argv[12])->GetData()); MITK_TEST_CONDITION_REQUIRED(joinded->Equals(testFibs),"check bundle addition") // test binary image based extraction mitk::Image::Pointer mitkRoiImage = dynamic_cast(mitk::IOUtil::LoadDataNode(argv[6])->GetData()); typedef itk::Image< unsigned char, 3 > itkUCharImageType; itkUCharImageType::Pointer itkRoiImage = itkUCharImageType::New(); mitk::CastToItkImage(mitkRoiImage, itkRoiImage); mitk::FiberBundleX::Pointer inside = groundTruthFibs->RemoveFibersOutside(itkRoiImage, false); mitk::FiberBundleX::Pointer outside = groundTruthFibs->RemoveFibersOutside(itkRoiImage, true); mitk::FiberBundleX::Pointer passing = groundTruthFibs->ExtractFiberSubset(itkRoiImage, true); mitk::FiberBundleX::Pointer ending = groundTruthFibs->ExtractFiberSubset(itkRoiImage, false); testFibs = dynamic_cast(mitk::IOUtil::LoadDataNode(argv[7])->GetData()); MITK_TEST_CONDITION_REQUIRED(inside->Equals(testFibs),"check inside mask extraction") testFibs = dynamic_cast(mitk::IOUtil::LoadDataNode(argv[8])->GetData()); MITK_TEST_CONDITION_REQUIRED(outside->Equals(testFibs),"check outside mask extraction") testFibs = dynamic_cast(mitk::IOUtil::LoadDataNode(argv[9])->GetData()); MITK_TEST_CONDITION_REQUIRED(passing->Equals(testFibs),"check passing mask extraction") testFibs = dynamic_cast(mitk::IOUtil::LoadDataNode(argv[10])->GetData()); MITK_TEST_CONDITION_REQUIRED(ending->Equals(testFibs),"check ending in mask extraction") } catch(...) { return EXIT_FAILURE; } // always end with this! MITK_TEST_END(); } diff --git a/Modules/DiffusionImaging/FiberTracking/Testing/mitkFiberfoxAddArtifactsToDwiTest.cpp b/Modules/DiffusionImaging/FiberTracking/Testing/mitkFiberfoxAddArtifactsToDwiTest.cpp index bef3714322..54293a4b5c 100644 --- a/Modules/DiffusionImaging/FiberTracking/Testing/mitkFiberfoxAddArtifactsToDwiTest.cpp +++ b/Modules/DiffusionImaging/FiberTracking/Testing/mitkFiberfoxAddArtifactsToDwiTest.cpp @@ -1,181 +1,180 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include #include #include #include #include -#include #include #include #include #include #include #include #include #include #include #include #include /**Documentation * Test the Fiberfox simulation functions (diffusion weighted image -> diffusion weighted image) */ class mitkFiberfoxAddArtifactsToDwiTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkFiberfoxAddArtifactsToDwiTestSuite); MITK_TEST(Spikes); MITK_TEST(GibbsRinging); MITK_TEST(Ghost); MITK_TEST(Aliasing); MITK_TEST(Eddy); MITK_TEST(RicianNoise); MITK_TEST(ChiSquareNoise); MITK_TEST(Distortions); CPPUNIT_TEST_SUITE_END(); private: mitk::DiffusionImage::Pointer m_InputDwi; FiberfoxParameters m_Parameters; public: void setUp() { // reference files m_InputDwi = dynamic_cast*>(mitk::IOUtil::LoadDataNode(GetTestDataFilePath("DiffusionImaging/Fiberfox/StickBall_RELAX.dwi"))->GetData()); // parameter setup m_Parameters = FiberfoxParameters(); m_Parameters.m_SignalGen.m_ImageRegion = m_InputDwi->GetVectorImage()->GetLargestPossibleRegion(); m_Parameters.m_SignalGen.m_ImageSpacing = m_InputDwi->GetVectorImage()->GetSpacing(); m_Parameters.m_SignalGen.m_ImageOrigin = m_InputDwi->GetVectorImage()->GetOrigin(); m_Parameters.m_SignalGen.m_ImageDirection = m_InputDwi->GetVectorImage()->GetDirection(); m_Parameters.m_SignalGen.m_Bvalue = m_InputDwi->GetReferenceBValue(); m_Parameters.m_SignalGen.SetGradienDirections(m_InputDwi->GetDirections()); } bool CompareDwi(itk::VectorImage< short, 3 >* dwi1, itk::VectorImage< short, 3 >* dwi2) { typedef itk::VectorImage< short, 3 > DwiImageType; try{ itk::ImageRegionIterator< DwiImageType > it1(dwi1, dwi1->GetLargestPossibleRegion()); itk::ImageRegionIterator< DwiImageType > it2(dwi2, dwi2->GetLargestPossibleRegion()); while(!it1.IsAtEnd()) { if (it1.Get()!=it2.Get()) return false; ++it1; ++it2; } } catch(...) { return false; } return true; } void StartSimulation(string testFileName) { mitk::DiffusionImage::Pointer refImage = NULL; if (!testFileName.empty()) CPPUNIT_ASSERT(refImage = dynamic_cast*>(mitk::IOUtil::LoadDataNode(testFileName)->GetData())); itk::AddArtifactsToDwiImageFilter< short >::Pointer artifactsToDwiFilter = itk::AddArtifactsToDwiImageFilter< short >::New(); artifactsToDwiFilter->SetUseConstantRandSeed(true); artifactsToDwiFilter->SetInput(m_InputDwi->GetVectorImage()); artifactsToDwiFilter->SetParameters(m_Parameters); CPPUNIT_ASSERT_NO_THROW(artifactsToDwiFilter->Update()); mitk::DiffusionImage::Pointer testImage = mitk::DiffusionImage::New(); testImage->SetVectorImage( artifactsToDwiFilter->GetOutput() ); testImage->SetReferenceBValue( m_Parameters.m_SignalGen.m_Bvalue); testImage->SetDirections( m_Parameters.m_SignalGen.GetGradientDirections()); testImage->InitializeFromVectorImage(); if (refImage.IsNotNull()) { CPPUNIT_ASSERT_MESSAGE(testFileName, CompareDwi(testImage->GetVectorImage(), refImage->GetVectorImage())); } } void Spikes() { m_Parameters.m_SignalGen.m_Spikes = 5; m_Parameters.m_SignalGen.m_SpikeAmplitude = 1; StartSimulation( GetTestDataFilePath("DiffusionImaging/Fiberfox/spikes2.dwi") ); } void GibbsRinging() { m_Parameters.m_SignalGen.m_DoAddGibbsRinging = true; StartSimulation( GetTestDataFilePath("DiffusionImaging/Fiberfox/gibbsringing2.dwi") ); } void Ghost() { m_Parameters.m_SignalGen.m_KspaceLineOffset = 0.25; StartSimulation( GetTestDataFilePath("DiffusionImaging/Fiberfox/ghost2.dwi") ); } void Aliasing() { m_Parameters.m_SignalGen.m_CroppingFactor = 0.4; StartSimulation( GetTestDataFilePath("DiffusionImaging/Fiberfox/aliasing2.dwi") ); } void Eddy() { m_Parameters.m_SignalGen.m_EddyStrength = 0.05; StartSimulation( GetTestDataFilePath("DiffusionImaging/Fiberfox/eddy2.dwi") ); } void RicianNoise() { mitk::RicianNoiseModel* ricianNoiseModel = new mitk::RicianNoiseModel(); ricianNoiseModel->SetNoiseVariance(1000000); ricianNoiseModel->SetSeed(0); m_Parameters.m_NoiseModel = ricianNoiseModel; StartSimulation( GetTestDataFilePath("DiffusionImaging/Fiberfox/riciannoise2.dwi") ); delete m_Parameters.m_NoiseModel; } void ChiSquareNoise() { mitk::ChiSquareNoiseModel* chiSquareNoiseModel = new mitk::ChiSquareNoiseModel(); chiSquareNoiseModel->SetNoiseVariance(1000000); chiSquareNoiseModel->SetSeed(0); m_Parameters.m_NoiseModel = chiSquareNoiseModel; StartSimulation( GetTestDataFilePath("DiffusionImaging/Fiberfox/chisquarenoise2.dwi") ); delete m_Parameters.m_NoiseModel; } void Distortions() { mitk::Image::Pointer mitkFMap = dynamic_cast(mitk::IOUtil::LoadDataNode( GetTestDataFilePath("DiffusionImaging/Fiberfox/Fieldmap.nrrd") )->GetData()); typedef itk::Image ItkDoubleImgType; ItkDoubleImgType::Pointer fMap = ItkDoubleImgType::New(); mitk::CastToItkImage(mitkFMap, fMap); m_Parameters.m_SignalGen.m_FrequencyMap = fMap; StartSimulation( GetTestDataFilePath("DiffusionImaging/Fiberfox/distortions2.dwi") ); } }; MITK_TEST_SUITE_REGISTRATION(mitkFiberfoxAddArtifactsToDwi) diff --git a/Modules/DiffusionImaging/FiberTracking/Testing/mitkFiberfoxSignalGenerationTest.cpp b/Modules/DiffusionImaging/FiberTracking/Testing/mitkFiberfoxSignalGenerationTest.cpp index 15ba467847..2e0ae2c4b5 100644 --- a/Modules/DiffusionImaging/FiberTracking/Testing/mitkFiberfoxSignalGenerationTest.cpp +++ b/Modules/DiffusionImaging/FiberTracking/Testing/mitkFiberfoxSignalGenerationTest.cpp @@ -1,274 +1,273 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include #include #include #include #include -#include #include #include #include #include #include #include #include #include #include #include #include /**Documentation * Test the Fiberfox simulation functions (fiberBundle -> diffusion weighted image) */ bool CompareDwi(itk::VectorImage< short, 3 >* dwi1, itk::VectorImage< short, 3 >* dwi2) { typedef itk::VectorImage< short, 3 > DwiImageType; try{ itk::ImageRegionIterator< DwiImageType > it1(dwi1, dwi1->GetLargestPossibleRegion()); itk::ImageRegionIterator< DwiImageType > it2(dwi2, dwi2->GetLargestPossibleRegion()); while(!it1.IsAtEnd()) { if (it1.Get()!=it2.Get()) return false; ++it1; ++it2; } } catch(...) { return false; } return true; } void StartSimulation(FiberfoxParameters parameters, FiberBundleX::Pointer fiberBundle, mitk::DiffusionImage::Pointer refImage, string message) { itk::TractsToDWIImageFilter< short >::Pointer tractsToDwiFilter = itk::TractsToDWIImageFilter< short >::New(); tractsToDwiFilter->SetUseConstantRandSeed(true); tractsToDwiFilter->SetParameters(parameters); tractsToDwiFilter->SetFiberBundle(fiberBundle); tractsToDwiFilter->Update(); mitk::DiffusionImage::Pointer testImage = mitk::DiffusionImage::New(); testImage->SetVectorImage( tractsToDwiFilter->GetOutput() ); testImage->SetReferenceBValue(parameters.m_SignalGen.m_Bvalue); testImage->SetDirections(parameters.m_SignalGen.GetGradientDirections()); testImage->InitializeFromVectorImage(); if (refImage.IsNotNull()) { bool cond = CompareDwi(testImage->GetVectorImage(), refImage->GetVectorImage()); if (!cond) { MITK_INFO << "Saving test and rference image to " << mitk::IOUtil::GetTempPath(); mitk::IOUtil::SaveBaseData(testImage, mitk::IOUtil::GetTempPath()+"testImage.dwi"); mitk::IOUtil::SaveBaseData(refImage, mitk::IOUtil::GetTempPath()+"refImage.dwi"); } MITK_TEST_CONDITION_REQUIRED(cond, message); } } int mitkFiberfoxSignalGenerationTest(int argc, char* argv[]) { MITK_TEST_BEGIN("mitkFiberfoxSignalGenerationTest"); MITK_TEST_CONDITION_REQUIRED(argc>=19,"check for input data"); // input fiber bundle FiberBundleX::Pointer fiberBundle = dynamic_cast(mitk::IOUtil::Load(argv[1])[0].GetPointer()); // reference diffusion weighted images mitk::DiffusionImage::Pointer stickBall = dynamic_cast*>(mitk::IOUtil::LoadDataNode(argv[2])->GetData()); mitk::DiffusionImage::Pointer stickAstrosticks = dynamic_cast*>(mitk::IOUtil::LoadDataNode(argv[3])->GetData()); mitk::DiffusionImage::Pointer stickDot = dynamic_cast*>(mitk::IOUtil::LoadDataNode(argv[4])->GetData()); mitk::DiffusionImage::Pointer tensorBall = dynamic_cast*>(mitk::IOUtil::LoadDataNode(argv[5])->GetData()); mitk::DiffusionImage::Pointer stickTensorBall = dynamic_cast*>(mitk::IOUtil::LoadDataNode(argv[6])->GetData()); mitk::DiffusionImage::Pointer stickTensorBallAstrosticks = dynamic_cast*>(mitk::IOUtil::LoadDataNode(argv[7])->GetData()); mitk::DiffusionImage::Pointer gibbsringing = dynamic_cast*>(mitk::IOUtil::LoadDataNode(argv[8])->GetData()); mitk::DiffusionImage::Pointer ghost = dynamic_cast*>(mitk::IOUtil::LoadDataNode(argv[9])->GetData()); mitk::DiffusionImage::Pointer aliasing = dynamic_cast*>(mitk::IOUtil::LoadDataNode(argv[10])->GetData()); mitk::DiffusionImage::Pointer eddy = dynamic_cast*>(mitk::IOUtil::LoadDataNode(argv[11])->GetData()); mitk::DiffusionImage::Pointer linearmotion = dynamic_cast*>(mitk::IOUtil::LoadDataNode(argv[12])->GetData()); mitk::DiffusionImage::Pointer randommotion = dynamic_cast*>(mitk::IOUtil::LoadDataNode(argv[13])->GetData()); mitk::DiffusionImage::Pointer spikes = dynamic_cast*>(mitk::IOUtil::LoadDataNode(argv[14])->GetData()); mitk::DiffusionImage::Pointer riciannoise = dynamic_cast*>(mitk::IOUtil::LoadDataNode(argv[15])->GetData()); mitk::DiffusionImage::Pointer chisquarenoise = dynamic_cast*>(mitk::IOUtil::LoadDataNode(argv[16])->GetData()); mitk::DiffusionImage::Pointer distortions = dynamic_cast*>(mitk::IOUtil::LoadDataNode(argv[17])->GetData()); mitk::Image::Pointer mitkFMap = dynamic_cast(mitk::IOUtil::LoadDataNode(argv[18])->GetData()); typedef itk::Image ItkDoubleImgType; ItkDoubleImgType::Pointer fMap = ItkDoubleImgType::New(); mitk::CastToItkImage(mitkFMap, fMap); FiberfoxParameters parameters; parameters.m_SignalGen.m_SimulateKspaceAcquisition = true; parameters.m_SignalGen.m_SignalScale = 10000; parameters.m_SignalGen.m_ImageRegion = stickBall->GetVectorImage()->GetLargestPossibleRegion(); parameters.m_SignalGen.m_ImageSpacing = stickBall->GetVectorImage()->GetSpacing(); parameters.m_SignalGen.m_ImageOrigin = stickBall->GetVectorImage()->GetOrigin(); parameters.m_SignalGen.m_ImageDirection = stickBall->GetVectorImage()->GetDirection(); parameters.m_SignalGen.m_Bvalue = stickBall->GetReferenceBValue(); parameters.m_SignalGen.SetGradienDirections(stickBall->GetDirections()); // intra and inter axonal compartments mitk::StickModel stickModel; stickModel.SetBvalue(parameters.m_SignalGen.m_Bvalue); stickModel.SetT2(110); stickModel.SetDiffusivity(0.001); stickModel.SetGradientList(parameters.m_SignalGen.GetGradientDirections()); mitk::TensorModel tensorModel; tensorModel.SetT2(110); stickModel.SetBvalue(parameters.m_SignalGen.m_Bvalue); tensorModel.SetDiffusivity1(0.001); tensorModel.SetDiffusivity2(0.00025); tensorModel.SetDiffusivity3(0.00025); tensorModel.SetGradientList(parameters.m_SignalGen.GetGradientDirections()); // extra axonal compartment models mitk::BallModel ballModel; ballModel.SetT2(80); ballModel.SetBvalue(parameters.m_SignalGen.m_Bvalue); ballModel.SetDiffusivity(0.001); ballModel.SetGradientList(parameters.m_SignalGen.GetGradientDirections()); mitk::AstroStickModel astrosticksModel; astrosticksModel.SetT2(80); astrosticksModel.SetBvalue(parameters.m_SignalGen.m_Bvalue); astrosticksModel.SetDiffusivity(0.001); astrosticksModel.SetRandomizeSticks(true); astrosticksModel.SetSeed(0); astrosticksModel.SetGradientList(parameters.m_SignalGen.GetGradientDirections()); mitk::DotModel dotModel; dotModel.SetT2(80); dotModel.SetGradientList(parameters.m_SignalGen.GetGradientDirections()); // noise models mitk::RicianNoiseModel* ricianNoiseModel = new mitk::RicianNoiseModel(); ricianNoiseModel->SetNoiseVariance(1000000); ricianNoiseModel->SetSeed(0); // Rician noise mitk::ChiSquareNoiseModel* chiSquareNoiseModel = new mitk::ChiSquareNoiseModel(); chiSquareNoiseModel->SetNoiseVariance(1000000); chiSquareNoiseModel->SetSeed(0); try{ // Stick-Ball parameters.m_FiberModelList.push_back(&stickModel); parameters.m_NonFiberModelList.push_back(&ballModel); StartSimulation(parameters, fiberBundle, stickBall, argv[2]); // Srick-Astrosticks parameters.m_NonFiberModelList.clear(); parameters.m_NonFiberModelList.push_back(&astrosticksModel); StartSimulation(parameters, fiberBundle, stickAstrosticks, argv[3]); // Stick-Dot parameters.m_NonFiberModelList.clear(); parameters.m_NonFiberModelList.push_back(&dotModel); StartSimulation(parameters, fiberBundle, stickDot, argv[4]); // Tensor-Ball parameters.m_FiberModelList.clear(); parameters.m_FiberModelList.push_back(&tensorModel); parameters.m_NonFiberModelList.clear(); parameters.m_NonFiberModelList.push_back(&ballModel); StartSimulation(parameters, fiberBundle, tensorBall, argv[5]); // Stick-Tensor-Ball parameters.m_FiberModelList.clear(); parameters.m_FiberModelList.push_back(&stickModel); parameters.m_FiberModelList.push_back(&tensorModel); parameters.m_NonFiberModelList.clear(); parameters.m_NonFiberModelList.push_back(&ballModel); StartSimulation(parameters, fiberBundle, stickTensorBall, argv[6]); // Stick-Tensor-Ball-Astrosticks parameters.m_NonFiberModelList.push_back(&astrosticksModel); StartSimulation(parameters, fiberBundle, stickTensorBallAstrosticks, argv[7]); // Gibbs ringing parameters.m_FiberModelList.clear(); parameters.m_FiberModelList.push_back(&stickModel); parameters.m_NonFiberModelList.clear(); parameters.m_NonFiberModelList.push_back(&ballModel); parameters.m_SignalGen.m_DoAddGibbsRinging = true; StartSimulation(parameters, fiberBundle, gibbsringing, argv[8]); // Ghost parameters.m_SignalGen.m_DoAddGibbsRinging = false; parameters.m_SignalGen.m_KspaceLineOffset = 0.25; StartSimulation(parameters, fiberBundle, ghost, argv[9]); // Aliasing parameters.m_SignalGen.m_KspaceLineOffset = 0; parameters.m_SignalGen.m_CroppingFactor = 0.4; parameters.m_SignalGen.m_SignalScale = 1000; StartSimulation(parameters, fiberBundle, aliasing, argv[10]); // Eddy currents parameters.m_SignalGen.m_CroppingFactor = 1; parameters.m_SignalGen.m_SignalScale = 10000; parameters.m_SignalGen.m_EddyStrength = 0.05; StartSimulation(parameters, fiberBundle, eddy, argv[11]); // Motion (linear) parameters.m_SignalGen.m_EddyStrength = 0.0; parameters.m_SignalGen.m_DoAddMotion = true; parameters.m_SignalGen.m_DoRandomizeMotion = false; parameters.m_SignalGen.m_Translation[1] = 10; parameters.m_SignalGen.m_Rotation[2] = 90; StartSimulation(parameters, fiberBundle, linearmotion, argv[12]); // Motion (random) parameters.m_SignalGen.m_DoRandomizeMotion = true; parameters.m_SignalGen.m_Translation[1] = 5; parameters.m_SignalGen.m_Rotation[2] = 45; StartSimulation(parameters, fiberBundle, randommotion, argv[13]); // Spikes parameters.m_SignalGen.m_DoAddMotion = false; parameters.m_SignalGen.m_Spikes = 5; parameters.m_SignalGen.m_SpikeAmplitude = 1; StartSimulation(parameters, fiberBundle, spikes, argv[14]); // Rician noise parameters.m_SignalGen.m_Spikes = 0; parameters.m_NoiseModel = ricianNoiseModel; StartSimulation(parameters, fiberBundle, riciannoise, argv[15]); delete parameters.m_NoiseModel; // Chi-square noise parameters.m_NoiseModel = chiSquareNoiseModel; StartSimulation(parameters, fiberBundle, chisquarenoise, argv[16]); delete parameters.m_NoiseModel; // Distortions parameters.m_NoiseModel = NULL; parameters.m_SignalGen.m_FrequencyMap = fMap; StartSimulation(parameters, fiberBundle, distortions, argv[17]); } catch (std::exception &e) { MITK_TEST_CONDITION_REQUIRED(false, e.what()); } // always end with this! MITK_TEST_END(); } diff --git a/Modules/DiffusionImaging/FiberTracking/Testing/mitkLocalFiberPlausibilityTest.cpp b/Modules/DiffusionImaging/FiberTracking/Testing/mitkLocalFiberPlausibilityTest.cpp index 38bad8fa0e..d507c48488 100755 --- a/Modules/DiffusionImaging/FiberTracking/Testing/mitkLocalFiberPlausibilityTest.cpp +++ b/Modules/DiffusionImaging/FiberTracking/Testing/mitkLocalFiberPlausibilityTest.cpp @@ -1,191 +1,190 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include -#include #include #define _USE_MATH_DEFINES #include using namespace std; int mitkLocalFiberPlausibilityTest(int argc, char* argv[]) { MITK_TEST_BEGIN("mitkLocalFiberPlausibilityTest"); MITK_TEST_CONDITION_REQUIRED(argc==8,"check for input data") string fibFile = argv[1]; vector< string > referenceImages; referenceImages.push_back(argv[2]); referenceImages.push_back(argv[3]); string LDFP_ERROR_IMAGE = argv[4]; string LDFP_NUM_DIRECTIONS = argv[5]; string LDFP_VECTOR_FIELD = argv[6]; string LDFP_ERROR_IMAGE_IGNORE = argv[7]; float angularThreshold = 25; try { typedef itk::Image ItkUcharImgType; typedef itk::Image< itk::Vector< float, 3>, 3 > ItkDirectionImage3DType; typedef itk::VectorContainer< unsigned int, ItkDirectionImage3DType::Pointer > ItkDirectionImageContainerType; typedef itk::EvaluateDirectionImagesFilter< float > EvaluationFilterType; // load fiber bundle mitk::FiberBundleX::Pointer inputTractogram = dynamic_cast(mitk::IOUtil::LoadDataNode(fibFile)->GetData()); // load reference directions ItkDirectionImageContainerType::Pointer referenceImageContainer = ItkDirectionImageContainerType::New(); for (unsigned int i=0; i(mitk::IOUtil::LoadDataNode(referenceImages.at(i))->GetData()); typedef mitk::ImageToItk< ItkDirectionImage3DType > CasterType; CasterType::Pointer caster = CasterType::New(); caster->SetInput(img); caster->Update(); ItkDirectionImage3DType::Pointer itkImg = caster->GetOutput(); referenceImageContainer->InsertElement(referenceImageContainer->Size(),itkImg); } catch(...){ MITK_INFO << "could not load: " << referenceImages.at(i); } } ItkUcharImgType::Pointer itkMaskImage = ItkUcharImgType::New(); ItkDirectionImage3DType::Pointer dirImg = referenceImageContainer->GetElement(0); itkMaskImage->SetSpacing( dirImg->GetSpacing() ); itkMaskImage->SetOrigin( dirImg->GetOrigin() ); itkMaskImage->SetDirection( dirImg->GetDirection() ); itkMaskImage->SetLargestPossibleRegion( dirImg->GetLargestPossibleRegion() ); itkMaskImage->SetBufferedRegion( dirImg->GetLargestPossibleRegion() ); itkMaskImage->SetRequestedRegion( dirImg->GetLargestPossibleRegion() ); itkMaskImage->Allocate(); itkMaskImage->FillBuffer(1); // extract directions from fiber bundle itk::TractsToVectorImageFilter::Pointer fOdfFilter = itk::TractsToVectorImageFilter::New(); fOdfFilter->SetFiberBundle(inputTractogram); fOdfFilter->SetMaskImage(itkMaskImage); fOdfFilter->SetAngularThreshold(cos(angularThreshold*M_PI/180)); fOdfFilter->SetNormalizeVectors(true); //fOdfFilter->SetMaxNumDirections(1); fOdfFilter->SetSizeThreshold(0.0); fOdfFilter->SetUseWorkingCopy(false); fOdfFilter->SetNumberOfThreads(1); fOdfFilter->Update(); ItkDirectionImageContainerType::Pointer directionImageContainer = fOdfFilter->GetDirectionImageContainer(); // Get directions and num directions image ItkUcharImgType::Pointer numDirImage = fOdfFilter->GetNumDirectionsImage(); mitk::Image::Pointer mitkNumDirImage = mitk::Image::New(); mitkNumDirImage->InitializeByItk( numDirImage.GetPointer() ); mitkNumDirImage->SetVolume( numDirImage->GetBufferPointer() ); mitk::FiberBundleX::Pointer testDirections = fOdfFilter->GetOutputFiberBundle(); // evaluate directions with missing directions EvaluationFilterType::Pointer evaluationFilter = EvaluationFilterType::New(); evaluationFilter->SetImageSet(directionImageContainer); evaluationFilter->SetReferenceImageSet(referenceImageContainer); evaluationFilter->SetMaskImage(itkMaskImage); evaluationFilter->SetIgnoreMissingDirections(false); evaluationFilter->Update(); EvaluationFilterType::OutputImageType::Pointer angularErrorImage = evaluationFilter->GetOutput(0); mitk::Image::Pointer mitkAngularErrorImage = mitk::Image::New(); mitkAngularErrorImage->InitializeByItk( angularErrorImage.GetPointer() ); mitkAngularErrorImage->SetVolume( angularErrorImage->GetBufferPointer() ); // evaluate directions without missing directions evaluationFilter->SetIgnoreMissingDirections(true); evaluationFilter->Update(); EvaluationFilterType::OutputImageType::Pointer angularErrorImageIgnore = evaluationFilter->GetOutput(0); mitk::Image::Pointer mitkAngularErrorImageIgnore = mitk::Image::New(); mitkAngularErrorImageIgnore->InitializeByItk( angularErrorImageIgnore.GetPointer() ); mitkAngularErrorImageIgnore->SetVolume( angularErrorImageIgnore->GetBufferPointer() ); mitk::Image::Pointer gtAngularErrorImageIgnore = dynamic_cast(mitk::IOUtil::LoadDataNode(LDFP_ERROR_IMAGE_IGNORE)->GetData()); mitk::Image::Pointer gtAngularErrorImage = dynamic_cast(mitk::IOUtil::LoadDataNode(LDFP_ERROR_IMAGE)->GetData()); mitk::Image::Pointer gtNumTestDirImage = dynamic_cast(mitk::IOUtil::LoadDataNode(LDFP_NUM_DIRECTIONS)->GetData()); mitk::FiberBundleX::Pointer gtTestDirections = dynamic_cast(mitk::IOUtil::LoadDataNode(LDFP_VECTOR_FIELD)->GetData()); // if (!testDirections->Equals(gtTestDirections)) // { // MITK_INFO << "SAVING FILES TO " << mitk::IOUtil::GetTempPath(); // std::string out1 = mitk::IOUtil::GetTempPath().append("test.nrrd"); // std::string out2 = mitk::IOUtil::GetTempPath().append("reference.nrrd"); // mitk::CoreObjectFactory::FileWriterList fileWriters = mitk::CoreObjectFactory::GetInstance()->GetFileWriters(); // for (mitk::CoreObjectFactory::FileWriterList::iterator it = fileWriters.begin() ; it != fileWriters.end() ; ++it) // { // if ( (*it)->CanWriteBaseDataType(testDirections.GetPointer()) ) { // (*it)->SetFileName( (mitk::IOUtil::GetTempPath()+"test.fib").c_str() ); // (*it)->DoWrite( testDirections.GetPointer() ); // } // } // for (mitk::CoreObjectFactory::FileWriterList::iterator it = fileWriters.begin() ; it != fileWriters.end() ; ++it) // { // if ( (*it)->CanWriteBaseDataType(gtTestDirections.GetPointer()) ) { // (*it)->SetFileName( "/local/gt.fib" ); // (*it)->DoWrite( gtTestDirections.GetPointer() ); // } // } // mitk::IOUtil::SaveBaseData(mitkNumDirImage, mitk::IOUtil::GetTempPath()+"testImage.nrrd"); // mitk::IOUtil::SaveBaseData(gtNumTestDirImage, mitk::IOUtil::GetTempPath()+"refImage.nrrd"); // return EXIT_FAILURE; // } MITK_TEST_CONDITION_REQUIRED(mitk::Equal(gtAngularErrorImageIgnore, mitkAngularErrorImageIgnore, 0.01, true), "Check if error images are equal (ignored missing directions)."); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(gtAngularErrorImage, mitkAngularErrorImage, 0.01, true), "Check if error images are equal."); MITK_TEST_CONDITION_REQUIRED(testDirections->Equals(gtTestDirections), "Check if vector fields are equal."); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(gtNumTestDirImage, mitkNumDirImage, 0.1, true), "Check if num direction images are equal."); } catch (itk::ExceptionObject e) { MITK_INFO << e; return EXIT_FAILURE; } catch (std::exception e) { MITK_INFO << e.what(); return EXIT_FAILURE; } catch (...) { MITK_INFO << "ERROR!?!"; return EXIT_FAILURE; } MITK_TEST_END(); } diff --git a/Modules/DiffusionImaging/FiberTracking/Testing/mitkPeakExtractionTest.cpp b/Modules/DiffusionImaging/FiberTracking/Testing/mitkPeakExtractionTest.cpp index 8fb94da1f4..4ee5ff9d27 100755 --- a/Modules/DiffusionImaging/FiberTracking/Testing/mitkPeakExtractionTest.cpp +++ b/Modules/DiffusionImaging/FiberTracking/Testing/mitkPeakExtractionTest.cpp @@ -1,110 +1,109 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include #include #include #include #include #include #include #include #include #include -#include #include #include #include #include #include #include using namespace std; int mitkPeakExtractionTest(int argc, char* argv[]) { MITK_TEST_BEGIN("mitkStreamlineTrackingTest"); MITK_TEST_CONDITION_REQUIRED(argc>3,"check for input data") string shCoeffFileName = argv[1]; string maskFileName = argv[2]; string referenceFileName = argv[3]; MITK_INFO << "SH-coefficient file: " << shCoeffFileName; MITK_INFO << "Mask file: " << maskFileName; MITK_INFO << "Reference fiber file: " << referenceFileName; try { mitk::CoreObjectFactory::GetInstance(); mitk::Image::Pointer image = mitk::IOUtil::LoadImage(shCoeffFileName); mitk::Image::Pointer mitkMaskImage = mitk::IOUtil::LoadImage(maskFileName); typedef itk::Image ItkUcharImgType; typedef itk::FiniteDiffOdfMaximaExtractionFilter< float, 4, 20242 > MaximaExtractionFilterType; MaximaExtractionFilterType::Pointer filter = MaximaExtractionFilterType::New(); MITK_INFO << "Casting mask image ..."; ItkUcharImgType::Pointer itkMask = ItkUcharImgType::New(); mitk::CastToItkImage(mitkMaskImage, itkMask); filter->SetMaskImage(itkMask); MITK_INFO << "Casting SH image ..."; typedef mitk::ImageToItk< MaximaExtractionFilterType::CoefficientImageType > CasterType; CasterType::Pointer caster = CasterType::New(); caster->SetInput(image); caster->Update(); filter->SetInput(caster->GetOutput()); filter->SetMaxNumPeaks(2); filter->SetPeakThreshold(0.4); filter->SetAbsolutePeakThreshold(0.01); filter->SetAngularThreshold(25); filter->SetNormalizationMethod(MaximaExtractionFilterType::MAX_VEC_NORM); filter->SetNumberOfThreads(1); MITK_INFO << "Starting extraction ..."; filter->Update(); mitk::FiberBundleX::Pointer fib1 = filter->GetOutputFiberBundle(); MITK_INFO << "Loading reference ..."; const std::string s1="", s2=""; std::vector infile = mitk::BaseDataIO::LoadBaseDataFromFile( referenceFileName, s1, s2, false ); mitk::FiberBundleX::Pointer fib2 = dynamic_cast(infile.at(0).GetPointer()); // TODO: reduce epsilon. strange issues with differing values between windows and linux. MITK_TEST_CONDITION_REQUIRED(fib1->Equals(fib2), "Check if tractograms are equal."); } catch (itk::ExceptionObject e) { MITK_INFO << e; return EXIT_FAILURE; } catch (std::exception e) { MITK_INFO << e.what(); return EXIT_FAILURE; } catch (...) { MITK_INFO << "ERROR!?!"; return EXIT_FAILURE; } MITK_TEST_END(); } diff --git a/Modules/DiffusionImaging/FiberTracking/Testing/mitkStreamlineTrackingTest.cpp b/Modules/DiffusionImaging/FiberTracking/Testing/mitkStreamlineTrackingTest.cpp index a0ec04f4ff..32c55d131b 100755 --- a/Modules/DiffusionImaging/FiberTracking/Testing/mitkStreamlineTrackingTest.cpp +++ b/Modules/DiffusionImaging/FiberTracking/Testing/mitkStreamlineTrackingTest.cpp @@ -1,129 +1,128 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include #include #include #include #include #include #include #include -#include using namespace std; int mitkStreamlineTrackingTest(int argc, char* argv[]) { MITK_TEST_BEGIN("mitkStreamlineTrackingTest"); MITK_TEST_CONDITION_REQUIRED(argc>3,"check for input data") string dtiFileName = argv[1]; string maskFileName = argv[2]; string referenceFileName = argv[3]; MITK_INFO << "DTI file: " << dtiFileName; MITK_INFO << "Mask file: " << maskFileName; MITK_INFO << "Reference fiber file: " << referenceFileName; float minFA = 0.05; float minCurv = -1; float stepSize = -1; float tendf = 1; float tendg = 0; float minLength = 20; int numSeeds = 1; bool interpolate = true; try { MITK_INFO << "Loading tensor image ..."; typedef itk::Image< itk::DiffusionTensor3D, 3 > ItkTensorImage; mitk::TensorImage::Pointer mitkTensorImage = dynamic_cast(mitk::IOUtil::LoadDataNode(dtiFileName)->GetData()); ItkTensorImage::Pointer itk_dti = ItkTensorImage::New(); mitk::CastToItkImage(mitkTensorImage, itk_dti); MITK_INFO << "Loading seed image ..."; typedef itk::Image< unsigned char, 3 > ItkUCharImageType; mitk::Image::Pointer mitkSeedImage = mitk::IOUtil::LoadImage(maskFileName); MITK_INFO << "Loading mask image ..."; mitk::Image::Pointer mitkMaskImage = mitk::IOUtil::LoadImage(maskFileName); // instantiate tracker typedef itk::StreamlineTrackingFilter< float > FilterType; FilterType::Pointer filter = FilterType::New(); filter->SetInput(itk_dti); filter->SetSeedsPerVoxel(numSeeds); filter->SetFaThreshold(minFA); filter->SetMinCurvatureRadius(minCurv); filter->SetStepSize(stepSize); filter->SetF(tendf); filter->SetG(tendg); filter->SetInterpolate(interpolate); filter->SetMinTractLength(minLength); filter->SetNumberOfThreads(1); if (mitkSeedImage.IsNotNull()) { ItkUCharImageType::Pointer mask = ItkUCharImageType::New(); mitk::CastToItkImage(mitkSeedImage, mask); filter->SetSeedImage(mask); } if (mitkMaskImage.IsNotNull()) { ItkUCharImageType::Pointer mask = ItkUCharImageType::New(); mitk::CastToItkImage(mitkMaskImage, mask); filter->SetMaskImage(mask); } filter->Update(); vtkSmartPointer fiberBundle = filter->GetFiberPolyData(); mitk::FiberBundleX::Pointer fib1 = mitk::FiberBundleX::New(fiberBundle); mitk::FiberBundleX::Pointer fib2 = dynamic_cast(mitk::IOUtil::LoadDataNode(referenceFileName)->GetData()); MITK_TEST_CONDITION_REQUIRED(fib2.IsNotNull(), "Check if reference tractogram is not null."); bool ok = fib1->Equals(fib2); if (!ok) { MITK_WARN << "TEST FAILED. TRACTOGRAMS ARE NOT EQUAL!"; mitk::IOUtil::SaveBaseData(fib1, mitk::IOUtil::GetTempPath()+"testBundle.fib"); mitk::IOUtil::SaveBaseData(fib2, mitk::IOUtil::GetTempPath()+"refBundle.fib"); MITK_INFO << "OUTPUT: " << mitk::IOUtil::GetTempPath(); } MITK_TEST_CONDITION_REQUIRED(ok, "Check if tractograms are equal."); } catch (itk::ExceptionObject e) { MITK_INFO << e; return EXIT_FAILURE; } catch (std::exception e) { MITK_INFO << e.what(); return EXIT_FAILURE; } catch (...) { MITK_INFO << "ERROR!?!"; return EXIT_FAILURE; } MITK_TEST_END(); } diff --git a/Modules/DiffusionImaging/FiberTracking/files.cmake b/Modules/DiffusionImaging/FiberTracking/files.cmake index 8997e4424d..19b7001331 100644 --- a/Modules/DiffusionImaging/FiberTracking/files.cmake +++ b/Modules/DiffusionImaging/FiberTracking/files.cmake @@ -1,83 +1,77 @@ set(CPP_FILES mitkFiberTrackingModuleActivator.cpp ## IO datastructures IODataStructures/FiberBundleX/mitkFiberBundleX.cpp - IODataStructures/FiberBundleX/mitkFiberBundleXWriter.cpp - IODataStructures/FiberBundleX/mitkFiberBundleXReader.cpp - IODataStructures/FiberBundleX/mitkFiberBundleXSerializer.cpp IODataStructures/FiberBundleX/mitkTrackvis.cpp IODataStructures/PlanarFigureComposite/mitkPlanarFigureComposite.cpp # Interactions Interactions/mitkFiberBundleInteractor.cpp # Tractography Algorithms/GibbsTracking/mitkParticleGrid.cpp Algorithms/GibbsTracking/mitkMetropolisHastingsSampler.cpp Algorithms/GibbsTracking/mitkEnergyComputer.cpp Algorithms/GibbsTracking/mitkGibbsEnergyComputer.cpp Algorithms/GibbsTracking/mitkFiberBuilder.cpp Algorithms/GibbsTracking/mitkSphereInterpolator.cpp ) set(H_FILES # DataStructures -> FiberBundleX IODataStructures/FiberBundleX/mitkFiberBundleX.h - IODataStructures/FiberBundleX/mitkFiberBundleXWriter.h - IODataStructures/FiberBundleX/mitkFiberBundleXReader.h - IODataStructures/FiberBundleX/mitkFiberBundleXSerializer.h IODataStructures/FiberBundleX/mitkTrackvis.h IODataStructures/mitkFiberfoxParameters.h # Algorithms Algorithms/itkTractDensityImageFilter.h Algorithms/itkTractsToFiberEndingsImageFilter.h Algorithms/itkTractsToRgbaImageFilter.h # moved to DiffusionCore #Algorithms/itkElectrostaticRepulsionDiffusionGradientReductionFilter.h Algorithms/itkFibersFromPlanarFiguresFilter.h Algorithms/itkTractsToDWIImageFilter.h Algorithms/itkTractsToVectorImageFilter.h Algorithms/itkKspaceImageFilter.h Algorithms/itkDftImageFilter.h Algorithms/itkAddArtifactsToDwiImageFilter.h Algorithms/itkFieldmapGeneratorFilter.h Algorithms/itkEvaluateDirectionImagesFilter.h Algorithms/itkEvaluateTractogramDirectionsFilter.h # (old) Tractography Algorithms/itkGibbsTrackingFilter.h Algorithms/itkStochasticTractographyFilter.h Algorithms/itkStreamlineTrackingFilter.h Algorithms/GibbsTracking/mitkParticle.h Algorithms/GibbsTracking/mitkParticleGrid.h Algorithms/GibbsTracking/mitkMetropolisHastingsSampler.h Algorithms/GibbsTracking/mitkSimpSamp.h Algorithms/GibbsTracking/mitkEnergyComputer.h Algorithms/GibbsTracking/mitkGibbsEnergyComputer.h Algorithms/GibbsTracking/mitkSphereInterpolator.h Algorithms/GibbsTracking/mitkFiberBuilder.h # Signal Models SignalModels/mitkDiffusionSignalModel.h SignalModels/mitkTensorModel.h SignalModels/mitkBallModel.h SignalModels/mitkDotModel.h SignalModels/mitkAstroStickModel.h SignalModels/mitkStickModel.h SignalModels/mitkRawShModel.h SignalModels/mitkDiffusionNoiseModel.h SignalModels/mitkRicianNoiseModel.h SignalModels/mitkChiSquareNoiseModel.h ) set(RESOURCE_FILES # Binary directory resources FiberTrackingLUTBaryCoords.bin FiberTrackingLUTIndices.bin # Shaders Shaders/mitkShaderFiberClipping.xml ) diff --git a/Modules/DiffusionImaging/FiberTracking/mitkFiberTrackingModuleActivator.cpp b/Modules/DiffusionImaging/FiberTracking/mitkFiberTrackingModuleActivator.cpp index a35475f8a1..f8acb70240 100644 --- a/Modules/DiffusionImaging/FiberTracking/mitkFiberTrackingModuleActivator.cpp +++ b/Modules/DiffusionImaging/FiberTracking/mitkFiberTrackingModuleActivator.cpp @@ -1,50 +1,43 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include -#include -#include - namespace mitk { /** \brief Registers services for segmentation module. */ class FiberTrackingModuleActivator : public us::ModuleActivator { public: void Load(us::ModuleContext* /*context*/) { - m_FiberBundleXReader = new FiberBundleXReader(); - m_FiberBundleXWriter = new FiberBundleXWriter(); + } void Unload(us::ModuleContext*) { - delete m_FiberBundleXReader; - delete m_FiberBundleXWriter; + } private: - FiberBundleXReader * m_FiberBundleXReader; - FiberBundleXWriter * m_FiberBundleXWriter; }; } US_EXPORT_MODULE_ACTIVATOR(mitk::FiberTrackingModuleActivator) diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkDiffusionRegistrationView.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkDiffusionRegistrationView.cpp index dd721c7515..5c1af3fdda 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkDiffusionRegistrationView.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkDiffusionRegistrationView.cpp @@ -1,489 +1,488 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ //misc #define _USE_MATH_DEFINES #include // Blueberry #include #include // Qmitk #include "QmitkDiffusionRegistrationView.h" #include // MITK #include #include #include #include -#include // Qt #include #include #include #include #include #include #define _USE_MATH_DEFINES #include QmitkRegistrationWorker::QmitkRegistrationWorker(QmitkDiffusionRegistrationView* view) : m_View(view) { } void QmitkRegistrationWorker::run() { typedef mitk::DiffusionImage DiffusionImageType; typedef DiffusionImageType::BValueMap BValueMap; unsigned int totalImagesCount; if( !m_View->m_IsBatch ) { totalImagesCount = m_View->m_SelectedDiffusionNodes.size(); } else { totalImagesCount = m_View->m_BatchList.size(); } m_View->m_TotalFiles = totalImagesCount; QString inputPath = m_View->m_Controls->m_InputFolderTextbox->text(); QString outputPath = m_View->m_Controls->m_OutputFolderTextbox->text(); for(unsigned int i=0; i< totalImagesCount; i++) { if(m_View->m_IsAborted){ m_View->m_RegistrationThread.quit(); return; } m_View->m_CurrentFile = i+1; m_View->m_GlobalRegisterer = QmitkDiffusionRegistrationView::DWIHeadMotionCorrectionFilterType::New(); //mitk::DataNode::Pointer node = m_View->m_SelectedDiffusionNodes.at(i); DiffusionImageType::Pointer inImage; mitk::DataNode::Pointer node; if( !m_View->m_IsBatch ) { node = m_View->m_SelectedDiffusionNodes.at(i); inImage = dynamic_cast*>(node->GetData()); } else { mitk::Image::Pointer inputImage = mitk::IOUtil::LoadImage( m_View->m_BatchList.at(i).toStdString() ); inImage = static_cast( inputImage.GetPointer() ); } if(inImage.IsNull()) { MITK_ERROR << "Error occured: can't get input image. \nAborting"; return; } m_View->m_GlobalRegisterer->SetInput(inImage); try { m_View->m_GlobalRegisterer->Update(); } catch( mitk::Exception e ) { MITK_ERROR << "Internal error occured: " << e.what() << "\nAborting"; } if( m_View->m_GlobalRegisterer->GetIsInValidState() ) { if(! m_View->m_IsBatch) { DiffusionImageType::Pointer image = m_View->m_GlobalRegisterer->GetOutput(); mitk::DataNode::Pointer imageNode = mitk::DataNode::New(); imageNode->SetData( image ); QString name = node->GetName().c_str(); imageNode->SetName((name+"_MC").toStdString().c_str()); m_View->GetDataStorage()->Add(imageNode); } else { mitk::NrrdDiffusionImageWriter< DiffusionPixelType >::Pointer dwiwriter = mitk::NrrdDiffusionImageWriter< DiffusionPixelType >::New(); dwiwriter->SetInput( m_View->m_GlobalRegisterer->GetOutput() ); QString name = m_View->m_BatchList.at(i); name = name.replace(".dwi", "_MC.dwi", Qt::CaseInsensitive); name = name.replace(inputPath, outputPath, Qt::CaseInsensitive); dwiwriter->SetFileName( name.toStdString().c_str() ); try { dwiwriter->Update(); } catch( const itk::ExceptionObject& e) { MITK_ERROR << "Catched exception: " << e.what(); mitkThrow() << "Failed with exception from subprocess!"; } } } } m_View->m_RegistrationThread.quit(); } const std::string QmitkDiffusionRegistrationView::VIEW_ID = "org.mitk.views.diffusionregistrationview"; QmitkDiffusionRegistrationView::QmitkDiffusionRegistrationView() : QmitkAbstractView() , m_Controls( 0 ) , m_DiffusionImage( NULL ) , m_ThreadIsRunning(false) , m_Steps(100) , m_LastStep(0) , m_GlobalRegisterer(NULL) , m_RegistrationWorker(this) { m_RegistrationWorker.moveToThread(&m_RegistrationThread); connect(&m_RegistrationThread, SIGNAL(started()), this, SLOT(BeforeThread())); connect(&m_RegistrationThread, SIGNAL(started()), &m_RegistrationWorker, SLOT(run())); connect(&m_RegistrationThread, SIGNAL(finished()), this, SLOT(AfterThread())); connect(&m_RegistrationThread, SIGNAL(terminated()), this, SLOT(AfterThread())); m_RegistrationTimer = new QTimer(this); } // Destructor QmitkDiffusionRegistrationView::~QmitkDiffusionRegistrationView() { delete m_RegistrationTimer; } // update Registration status and generate fiber bundle void QmitkDiffusionRegistrationView::TimerUpdate() { int currentStep = m_GlobalRegisterer->GetCurrentStep(); mitk::ProgressBar::GetInstance()->Progress(currentStep-m_LastStep); UpdateRegistrationStatus(); m_LastStep = currentStep; } // update gui elements after registration is finished void QmitkDiffusionRegistrationView::AfterThread() { m_ThreadIsRunning = false; m_RegistrationTimer->stop(); mitk::ProgressBar::GetInstance()->Progress(m_GlobalRegisterer->GetSteps()-m_LastStep+1); UpdateGUI(); if( !m_GlobalRegisterer->GetIsInValidState() ) { QMessageBox::critical( NULL, "Registration", "An internal error occured, or user canceled the Registration.\n Please check the log for details." ); return; } UpdateRegistrationStatus(); m_GlobalRegisterer = 0; } // start Registration timer and update gui elements before Registration is started void QmitkDiffusionRegistrationView::BeforeThread() { m_ThreadIsRunning = true; m_RegistrationTime = QTime::currentTime(); m_ElapsedTime = 0; m_RegistrationTimer->start(1000); m_LastStep = 0; UpdateGUI(); } void QmitkDiffusionRegistrationView::CreateQtPartControl( QWidget *parent ) { // build up qt view, unless already done if ( !m_Controls ) { // create GUI widgets from the Qt Designer's .ui file m_Controls = new Ui::QmitkDiffusionRegistrationViewControls; m_Controls->setupUi( parent ); AdvancedSettings(); connect( m_RegistrationTimer, SIGNAL(timeout()), this, SLOT(TimerUpdate()) ); connect( m_Controls->m_RegistrationStopButton, SIGNAL(clicked()), this, SLOT(StopRegistration()) ); connect( m_Controls->m_RegistrationStartButton, SIGNAL(clicked()), this, SLOT(StartRegistration()) ); connect( m_Controls->m_AdvancedSettingsCheckbox, SIGNAL(clicked()), this, SLOT(AdvancedSettings()) ); connect( m_Controls->m_SelectInputButton, SIGNAL(clicked()), this, SLOT(AddInputFolderName()) ); connect( m_Controls->m_SelectOutputButton, SIGNAL(clicked()), this, SLOT(AddOutputFolderName()) ); connect( m_Controls->m_StartBatchButton, SIGNAL(clicked()), this, SLOT(StartBatch()) ); this->m_Parent = parent; } } // show/hide advanced settings frame void QmitkDiffusionRegistrationView::AdvancedSettings() { m_Controls->m_AdvancedFrame->setVisible(m_Controls->m_AdvancedSettingsCheckbox->isChecked()); } void QmitkDiffusionRegistrationView::OnSelectionChanged( berry::IWorkbenchPart::Pointer, const QList& nodes ) { if (m_ThreadIsRunning) return; bool foundDwiVolume = false; QString tempSelectedNames = ""; m_DiffusionImage = NULL; m_SelectedDiffusionNodes.clear(); // iterate selection for( int i=0; i*>(node->GetData()) ) { foundDwiVolume = true; m_SelectedDiffusionNodes.push_back(node); if(m_SelectedDiffusionNodes.size() > 0){tempSelectedNames += "\n";} tempSelectedNames += (node->GetName().c_str()); } } m_Controls->m_RegistrationStartButton->setEnabled(foundDwiVolume); if (foundDwiVolume) { m_Controls->m_DiffusionImageLabel->setText(tempSelectedNames); m_Controls->m_InputData->setTitle("Input Data"); } else { m_Controls->m_DiffusionImageLabel->setText("mandatory"); m_Controls->m_InputData->setTitle("Please Select Input Data"); } UpdateGUI(); } // update gui elements displaying Registrations status void QmitkDiffusionRegistrationView::UpdateRegistrationStatus() { if (m_GlobalRegisterer.IsNull()) return; m_ElapsedTime += m_RegistrationTime.elapsed()/1000; m_RegistrationTime.restart(); unsigned long hours = m_ElapsedTime/3600; unsigned long minutes = (m_ElapsedTime%3600)/60; unsigned long seconds = m_ElapsedTime%60; m_Controls->m_RegistrationTimeLabel->setText( QString::number(hours)+QString("h ")+QString::number(minutes)+QString("m ")+QString::number(seconds)+QString("s") ); m_Controls->m_CurrentStepLabel->setText( QString::number((int)(100*(float)(m_GlobalRegisterer->GetCurrentStep()-1)/m_GlobalRegisterer->GetSteps()))+"%" ); m_Controls->m_CurrentFileLabel->setText( QString::number(m_CurrentFile)+" / "+QString::number(m_TotalFiles) ); } void QmitkDiffusionRegistrationView::UpdateGUI() { if (!m_ThreadIsRunning && (m_SelectedDiffusionNodes.size() > 0) ) { m_Controls->m_RegistrationStopButton->setEnabled(false); m_Controls->m_RegistrationStartButton->setEnabled(true); m_Controls->m_StartBatchButton->setEnabled(true); m_Controls->m_AdvancedFrame->setEnabled(true); m_Controls->m_RegistrationStopButton->setText("Stop"); m_Controls->m_RegistrationStartButton->setToolTip("Start Registration"); m_Controls->m_RegistrationStopButton->setToolTip(""); } else if (!m_ThreadIsRunning) { m_Controls->m_RegistrationStopButton->setEnabled(false); m_Controls->m_RegistrationStartButton->setEnabled(false); m_Controls->m_StartBatchButton->setEnabled(true); m_Controls->m_AdvancedFrame->setEnabled(true); m_Controls->m_RegistrationStopButton->setText("Stop"); m_Controls->m_RegistrationStartButton->setToolTip("No Diffusion image selected."); m_Controls->m_RegistrationStopButton->setToolTip(""); } else { m_Controls->m_RegistrationStopButton->setEnabled(true); m_Controls->m_RegistrationStartButton->setEnabled(false); m_Controls->m_StartBatchButton->setEnabled(false); m_Controls->m_AdvancedFrame->setEnabled(false); m_Controls->m_RegistrationStartButton->setToolTip("Registration in progress."); m_Controls->m_RegistrationStopButton->setToolTip("Cancel Registration"); } } void QmitkDiffusionRegistrationView::SetFocus() { m_Controls->m_RegistrationStartButton->setFocus(); } void QmitkDiffusionRegistrationView::StartRegistration() { if(m_ThreadIsRunning) { MITK_WARN("QmitkDiffusionRegistrationView")<<"Thread already running!"; return; } m_GlobalRegisterer = NULL; if (m_SelectedDiffusionNodes.size()<1) { QMessageBox::information( NULL, "Warning", "Please load and select a diffusion image before starting image processing."); return; } m_IsBatch = false; m_IsAborted = false; m_Controls->m_RegistrationStartButton->setEnabled(false); m_Controls->m_StartBatchButton->setEnabled(false); // start worker thread m_RegistrationThread.start(QThread::NormalPriority); return; } void QmitkDiffusionRegistrationView::StopRegistration() { if (m_GlobalRegisterer.IsNull()) return; m_IsAborted = true; m_GlobalRegisterer->SetAbortRegistration(true); m_Controls->m_RegistrationStopButton->setEnabled(false); m_Controls->m_RegistrationStopButton->setText("Stopping ..."); return; } void QmitkDiffusionRegistrationView::AddInputFolderName() { // SELECT FOLDER DIALOG QFileDialog* w = new QFileDialog( m_Parent, QString("Select the input folder with DWI files within") ); w->setFileMode( QFileDialog::Directory ); // RETRIEVE SELECTION if ( w->exec() != QDialog::Accepted ) return; m_Controls->m_InputFolderTextbox->setText(w->selectedFiles()[0]); } void QmitkDiffusionRegistrationView::AddOutputFolderName() { // SELECT FOLDER DIALOG QFileDialog* w = new QFileDialog( m_Parent, QString("Select the output folder") ); w->setFileMode( QFileDialog::Directory ); // RETRIEVE SELECTION if ( w->exec() != QDialog::Accepted ) return; m_Controls->m_OutputFolderTextbox->setText(w->selectedFiles()[0]); } void QmitkDiffusionRegistrationView::StartBatch() { QString inputPath = m_Controls->m_InputFolderTextbox->text(); QString outputPath = m_Controls->m_OutputFolderTextbox->text(); if(inputPath == outputPath){ QMessageBox::information( NULL, "Error", "Input and Output folders can't be the same"); return; } QStringList list, filters; filters<<"*.dwi"; QDirIterator dirIterator(inputPath, filters, QDir::Files|QDir::NoSymLinks); while (dirIterator.hasNext()) { dirIterator.next(); list.append(dirIterator.fileInfo().absoluteFilePath()); std::cout << dirIterator.fileInfo().absoluteFilePath().toStdString() << endl; m_BatchList = list; m_IsBatch = true; m_IsAborted = false; if(m_ThreadIsRunning) { MITK_WARN("QmitkDiffusionRegistrationView")<<"Thread already running!"; return; } m_GlobalRegisterer = NULL; if (m_BatchList.size()<1) { QMessageBox::information( NULL, "Error", "No diffusion images were found in the selected input folder."); return; } m_Controls->m_RegistrationStartButton->setEnabled(false); m_Controls->m_StartBatchButton->setEnabled(false); // start worker thread m_RegistrationThread.start(QThread::NormalPriority); } }