diff --git a/Modules/Classification/DataCollection/CMakeLists.txt b/Modules/Classification/DataCollection/CMakeLists.txt index 58a4ce8197..709794098d 100644 --- a/Modules/Classification/DataCollection/CMakeLists.txt +++ b/Modules/Classification/DataCollection/CMakeLists.txt @@ -1,11 +1,11 @@ MITK_CREATE_MODULE(DataCollection #<-- module name SUBPROJECTS INCLUDE_DIRS DataHolder ReaderWriter Iterators Utilities#<-- sub-folders of module INTERNAL_INCLUDE_DIRS ${INCLUDE_DIRS_INTERNAL} - DEPENDS MitkCore #<-- modules on which your module depends on + DEPENDS MitkCore # MitkLegacyIO #<-- modules on which your module depends on PACKAGE_DEPENDS Qt5|Core Eigen ) if(BUILD_TESTING) ADD_SUBDIRECTORY(Testing) endif() diff --git a/Modules/Core/test/mitkPreferenceListReaderOptionsFunctorTest.cpp b/Modules/Core/test/mitkPreferenceListReaderOptionsFunctorTest.cpp index d00b0b454f..aca2eb35d2 100644 --- a/Modules/Core/test/mitkPreferenceListReaderOptionsFunctorTest.cpp +++ b/Modules/Core/test/mitkPreferenceListReaderOptionsFunctorTest.cpp @@ -1,129 +1,129 @@ /*=================================================================== 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 "mitkPreferenceListReaderOptionsFunctor.h" #include "mitkTestFixture.h" #include "mitkTestingMacros.h" #include class mitkPreferenceListReaderOptionsFunctorTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkPreferenceListReaderOptionsFunctorTestSuite); MITK_TEST(UsePreferenceList); MITK_TEST(UseBlackList); MITK_TEST(UseNoList); MITK_TEST(UseBlackAndPreferenceList); MITK_TEST(UseOverlappingBlackAndPreferenceList); MITK_TEST(UsePreferenceListWithInexistantReaders); MITK_TEST(UseAllBlackedList); CPPUNIT_TEST_SUITE_END(); private: std::string m_ImagePath; mitk::PreferenceListReaderOptionsFunctor::ListType preference; mitk::PreferenceListReaderOptionsFunctor::ListType black; mitk::PreferenceListReaderOptionsFunctor::ListType emptyList; public: void setUp() override { m_ImagePath = GetTestDataFilePath("TinyCTAbdomen_DICOMReader/100"); - + preference = { "MITK DICOM Reader v2 (classic config)" }; black = { "MITK DICOM Reader" }; emptyList = {}; } void tearDown() override { } void UsePreferenceList() { mitk::IOUtil::LoadInfo info(m_ImagePath); mitk::PreferenceListReaderOptionsFunctor functor = mitk::PreferenceListReaderOptionsFunctor(preference, emptyList); CPPUNIT_ASSERT(true == functor(info)); CPPUNIT_ASSERT_EQUAL(std::string("MITK DICOM Reader v2 (classic config)"), info.m_ReaderSelector.GetSelected().GetDescription()); } void UseNoList() { mitk::IOUtil::LoadInfo info(m_ImagePath); mitk::PreferenceListReaderOptionsFunctor functor = mitk::PreferenceListReaderOptionsFunctor(emptyList, emptyList); CPPUNIT_ASSERT(true == functor(info)); CPPUNIT_ASSERT_EQUAL(std::string("MITK DICOM Reader"), info.m_ReaderSelector.GetSelected().GetDescription()); } void UseBlackList() { mitk::IOUtil::LoadInfo info(m_ImagePath); mitk::PreferenceListReaderOptionsFunctor functor = mitk::PreferenceListReaderOptionsFunctor(emptyList, black); CPPUNIT_ASSERT(true == functor(info)); CPPUNIT_ASSERT(info.m_ReaderSelector.GetSelected().GetDescription() != "MITK DICOM Reader"); } void UseBlackAndPreferenceList() { mitk::IOUtil::LoadInfo info(m_ImagePath); mitk::PreferenceListReaderOptionsFunctor functor = mitk::PreferenceListReaderOptionsFunctor(preference, black); CPPUNIT_ASSERT(true == functor(info)); CPPUNIT_ASSERT_EQUAL(std::string("MITK DICOM Reader v2 (classic config)"), info.m_ReaderSelector.GetSelected().GetDescription()); } void UseOverlappingBlackAndPreferenceList() { mitk::IOUtil::LoadInfo info(m_ImagePath); black.push_back("MITK DICOM Reader v2 (classic config)"); mitk::PreferenceListReaderOptionsFunctor functor = mitk::PreferenceListReaderOptionsFunctor(preference, black); CPPUNIT_ASSERT(true == functor(info)); - CPPUNIT_ASSERT_EQUAL(std::string("MITK DICOM Reader v2 (autoselect)"), info.m_ReaderSelector.GetSelected().GetDescription()); + CPPUNIT_ASSERT_EQUAL(std::string("MITK Simple Volume Importer"), info.m_ReaderSelector.GetSelected().GetDescription()); } void UsePreferenceListWithInexistantReaders() { mitk::IOUtil::LoadInfo info(m_ImagePath); preference.push_back("InexistantReader"); mitk::PreferenceListReaderOptionsFunctor functor = mitk::PreferenceListReaderOptionsFunctor(preference, emptyList); CPPUNIT_ASSERT(true == functor(info)); CPPUNIT_ASSERT_EQUAL(std::string("MITK DICOM Reader v2 (classic config)"), info.m_ReaderSelector.GetSelected().GetDescription()); } void UseAllBlackedList() { mitk::IOUtil::LoadInfo info(m_ImagePath); for (auto reader : info.m_ReaderSelector.Get()) { black.push_back(reader.GetDescription()); } mitk::PreferenceListReaderOptionsFunctor functor = mitk::PreferenceListReaderOptionsFunctor(emptyList, black); CPPUNIT_ASSERT_THROW(functor(info), mitk::Exception); } }; MITK_TEST_SUITE_REGISTRATION(mitkPreferenceListReaderOptionsFunctor) diff --git a/Modules/CppMicroServices/core/test/usModuleResourceTest.cpp b/Modules/CppMicroServices/core/test/usModuleResourceTest.cpp index 2f5fab2a97..f465d88919 100644 --- a/Modules/CppMicroServices/core/test/usModuleResourceTest.cpp +++ b/Modules/CppMicroServices/core/test/usModuleResourceTest.cpp @@ -1,483 +1,483 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include #include #include #include #include #include #include #include #include "usTestingMacros.h" #include #include #ifdef US_PLATFORM_WINDOWS static const std::string LIB_PATH = US_RUNTIME_OUTPUT_DIRECTORY; #else static const std::string LIB_PATH = US_LIBRARY_OUTPUT_DIRECTORY; #endif US_USE_NAMESPACE namespace { // Please confirm that a character count differing from the following targets is not due to // a misconfiguration of your versioning software (Correct line endings for your system) // See issue #18 ( https://github.com/saschazelzer/CppMicroServices/issues/18 ) void checkResourceInfo(const ModuleResource& res, const std::string& path, const std::string& baseName, const std::string& completeBaseName, const std::string& suffix, const std::string& completeSuffix, int size, bool children = false) { US_TEST_CONDITION_REQUIRED(res.IsValid(), "Valid resource") US_TEST_CONDITION(res.GetBaseName() == baseName, "GetBaseName()") US_TEST_CONDITION(res.GetChildren().empty() == !children, "No children") US_TEST_CONDITION(res.GetCompleteBaseName() == completeBaseName, "GetCompleteBaseName()") US_TEST_CONDITION(res.GetName() == completeBaseName + "." + suffix, "GetName()") US_TEST_CONDITION(res.GetResourcePath() == path + completeBaseName + "." + suffix, "GetResourcePath()") US_TEST_CONDITION(res.GetPath() == path, "GetPath()") US_TEST_CONDITION(res.GetSize() == size, "Data size") US_TEST_CONDITION(res.GetSuffix() == suffix, "Suffix") US_TEST_CONDITION(res.GetCompleteSuffix() == completeSuffix, "Complete suffix") } void testTextResource(Module* module) { ModuleResource res = module->GetResource("foo.txt"); #ifdef US_PLATFORM_WINDOWS checkResourceInfo(res, "/", "foo", "foo", "txt", "txt", 16, false); const std::streampos ssize(13); const std::string fileData = "foo and\nbar\n\n"; #else checkResourceInfo(res, "/", "foo", "foo", "txt", "txt", 13, false); const std::streampos ssize(12); const std::string fileData = "foo and\nbar\n"; #endif ModuleResourceStream rs(res); rs.seekg(0, std::ios::end); US_TEST_CONDITION(rs.tellg() == ssize, "Stream content length"); rs.seekg(0, std::ios::beg); std::string content; content.reserve(res.GetSize()); char buffer[1024]; while (rs.read(buffer, sizeof(buffer))) { content.append(buffer, sizeof(buffer)); } content.append(buffer, static_cast(rs.gcount())); US_TEST_CONDITION(rs.eof(), "EOF check"); US_TEST_CONDITION(content == fileData, "Resource content"); rs.clear(); rs.seekg(0); US_TEST_CONDITION_REQUIRED(rs.tellg() == std::streampos(0), "Move to start") US_TEST_CONDITION_REQUIRED(rs.good(), "Start re-reading"); std::vector lines; std::string line; while (std::getline(rs, line)) { lines.push_back(line); } US_TEST_CONDITION_REQUIRED(lines.size() > 1, "Number of lines") US_TEST_CONDITION(lines[0] == "foo and", "Check first line") US_TEST_CONDITION(lines[1] == "bar", "Check second line") } void testTextResourceAsBinary(Module* module) { ModuleResource res = module->GetResource("foo.txt"); #ifdef US_PLATFORM_WINDOWS checkResourceInfo(res, "/", "foo", "foo", "txt", "txt", 16, false); const std::streampos ssize(16); const std::string fileData = "foo and\r\nbar\r\n\r\n"; #else checkResourceInfo(res, "/", "foo", "foo", "txt", "txt", 13, false); const std::streampos ssize(13); const std::string fileData = "foo and\nbar\n\n"; #endif ModuleResourceStream rs(res, std::ios_base::binary); rs.seekg(0, std::ios::end); US_TEST_CONDITION(rs.tellg() == ssize, "Stream content length"); rs.seekg(0, std::ios::beg); std::string content; content.reserve(res.GetSize()); char buffer[1024]; while (rs.read(buffer, sizeof(buffer))) { content.append(buffer, sizeof(buffer)); } content.append(buffer, static_cast(rs.gcount())); US_TEST_CONDITION(rs.eof(), "EOF check"); US_TEST_CONDITION(content == fileData, "Resource content"); } void testInvalidResource(Module* module) { ModuleResource res = module->GetResource("invalid"); US_TEST_CONDITION_REQUIRED(res.IsValid() == false, "Check invalid resource") US_TEST_CONDITION(res.GetName().empty(), "Check empty name") US_TEST_CONDITION(res.GetPath().empty(), "Check empty path") US_TEST_CONDITION(res.GetResourcePath().empty(), "Check empty resource path") US_TEST_CONDITION(res.GetBaseName().empty(), "Check empty base name") US_TEST_CONDITION(res.GetCompleteBaseName().empty(), "Check empty complete base name") US_TEST_CONDITION(res.GetSuffix().empty(), "Check empty suffix") US_TEST_CONDITION(res.GetChildren().empty(), "Check empty children") US_TEST_CONDITION(res.GetSize() == 0, "Check zero size") ModuleResourceStream rs(res); US_TEST_CONDITION(rs.good() == true, "Check invalid resource stream") rs.ignore(); US_TEST_CONDITION(rs.good() == false, "Check invalid resource stream") US_TEST_CONDITION(rs.eof() == true, "Check invalid resource stream") } void testSpecialCharacters(Module* module) { ModuleResource res = module->GetResource("special_chars.dummy.txt"); #ifdef US_PLATFORM_WINDOWS checkResourceInfo(res, "/", "special_chars", "special_chars.dummy", "txt", "dummy.txt", 56, false); const std::streampos ssize(54); const std::string fileData = "German Füße (feet)\nFrench garçon de café (waiter)\n"; #else checkResourceInfo(res, "/", "special_chars", "special_chars.dummy", "txt", "dummy.txt", 54, false); const std::streampos ssize(53); const std::string fileData = "German Füße (feet)\nFrench garçon de café (waiter)"; #endif ModuleResourceStream rs(res); rs.seekg(0, std::ios_base::end); US_TEST_CONDITION(rs.tellg() == ssize, "Stream content length"); rs.seekg(0, std::ios_base::beg); std::string content; content.reserve(res.GetSize()); char buffer[1024]; while (rs.read(buffer, sizeof(buffer))) { content.append(buffer, sizeof(buffer)); } content.append(buffer, static_cast(rs.gcount())); US_TEST_CONDITION(rs.eof(), "EOF check"); US_TEST_CONDITION(content == fileData, "Resource content"); } void testBinaryResource(Module* module) { ModuleResource res = module->GetResource("/icons/cppmicroservices.png"); - checkResourceInfo(res, "/icons/", "cppmicroservices", "cppmicroservices", "png", "png", 2424, false); + checkResourceInfo(res, "/icons/", "cppmicroservices", "cppmicroservices", "png", "png", 2598, false); ModuleResourceStream rs(res, std::ios_base::binary); rs.seekg(0, std::ios_base::end); std::streampos resLength = rs.tellg(); rs.seekg(0); std::ifstream png(US_CORE_SOURCE_DIR "/test/modules/libRWithResources/resources/icons/cppmicroservices.png", std::ifstream::in | std::ifstream::binary); US_TEST_CONDITION_REQUIRED(png.is_open(), "Open reference file") png.seekg(0, std::ios_base::end); std::streampos pngLength = png.tellg(); png.seekg(0); US_TEST_CONDITION(res.GetSize() == resLength, "Check resource size") US_TEST_CONDITION_REQUIRED(resLength == pngLength, "Compare sizes") char c1 = 0; char c2 = 0; bool isEqual = true; int count = 0; while (png.get(c1) && rs.get(c2)) { ++count; if (c1 != c2) { isEqual = false; break; } } US_TEST_CONDITION_REQUIRED(count == pngLength, "Check if everything was read"); US_TEST_CONDITION_REQUIRED(isEqual, "Equal binary contents"); US_TEST_CONDITION(png.eof(), "EOF check"); } void testCompressedResource(Module* module) { ModuleResource res = module->GetResource("/icons/compressable.bmp"); checkResourceInfo(res, "/icons/", "compressable", "compressable", "bmp", "bmp", 300122, false); ModuleResourceStream rs(res, std::ios_base::binary); rs.seekg(0, std::ios_base::end); std::streampos resLength = rs.tellg(); rs.seekg(0); std::ifstream bmp(US_CORE_SOURCE_DIR "/test/modules/libRWithResources/resources/icons/compressable.bmp", std::ifstream::in | std::ifstream::binary); US_TEST_CONDITION_REQUIRED(bmp.is_open(), "Open reference file") bmp.seekg(0, std::ios_base::end); std::streampos bmpLength = bmp.tellg(); bmp.seekg(0); US_TEST_CONDITION(300122 == resLength, "Check resource size") US_TEST_CONDITION_REQUIRED(resLength == bmpLength, "Compare sizes") char c1 = 0; char c2 = 0; bool isEqual = true; int count = 0; while (bmp.get(c1) && rs.get(c2)) { ++count; if (c1 != c2) { isEqual = false; break; } } US_TEST_CONDITION_REQUIRED(count == bmpLength, "Check if everything was read"); US_TEST_CONDITION_REQUIRED(isEqual, "Equal binary contents"); US_TEST_CONDITION(bmp.eof(), "EOF check"); } struct ResourceComparator { bool operator()(const ModuleResource& mr1, const ModuleResource& mr2) const { return mr1 < mr2; } }; void testResourceTree(Module* module) { ModuleResource res = module->GetResource(""); US_TEST_CONDITION(res.GetResourcePath() == "/", "Check root file path") US_TEST_CONDITION(res.IsDir() == true, "Check type") std::vector children = res.GetChildren(); std::sort(children.begin(), children.end()); US_TEST_CONDITION_REQUIRED(children.size() == 5, "Check child count") US_TEST_CONDITION(children[0] == "foo.txt", "Check child name") US_TEST_CONDITION(children[1] == "foo2.txt", "Check child name") US_TEST_CONDITION(children[2] == "icons/", "Check child name") US_TEST_CONDITION(children[3] == "special_chars.dummy.txt", "Check child name") US_TEST_CONDITION(children[4] == "test.xml", "Check child name") US_TEST_CONDITION(module->FindResources("!$noexist=?", std::string(), "true").empty(), "Check not existant path"); ModuleResource readme = module->GetResource("/icons/readme.txt"); US_TEST_CONDITION(readme.IsFile() && readme.GetChildren().empty(), "Check file resource") ModuleResource icons = module->GetResource("icons/"); US_TEST_CONDITION(icons.IsDir() && !icons.IsFile() && !icons.GetChildren().empty(), "Check directory resource") children = icons.GetChildren(); US_TEST_CONDITION_REQUIRED(children.size() == 3, "Check icons child count") std::sort(children.begin(), children.end()); US_TEST_CONDITION(children[0] == "compressable.bmp", "Check child name") US_TEST_CONDITION(children[1] == "cppmicroservices.png", "Check child name") US_TEST_CONDITION(children[2] == "readme.txt", "Check child name") ResourceComparator resourceComparator; // find all .txt files std::vector nodes = module->FindResources("", "*.txt", false); std::sort(nodes.begin(), nodes.end(), resourceComparator); US_TEST_CONDITION_REQUIRED(nodes.size() == 3, "Found child count") US_TEST_CONDITION(nodes[0].GetResourcePath() == "/foo.txt", "Check child name") US_TEST_CONDITION(nodes[1].GetResourcePath() == "/foo2.txt", "Check child name") US_TEST_CONDITION(nodes[2].GetResourcePath() == "/special_chars.dummy.txt", "Check child name") nodes = module->FindResources("", "*.txt", true); std::sort(nodes.begin(), nodes.end(), resourceComparator); US_TEST_CONDITION_REQUIRED(nodes.size() == 4, "Found child count") US_TEST_CONDITION(nodes[0].GetResourcePath() == "/foo.txt", "Check child name") US_TEST_CONDITION(nodes[1].GetResourcePath() == "/foo2.txt", "Check child name") US_TEST_CONDITION(nodes[2].GetResourcePath() == "/icons/readme.txt", "Check child name") US_TEST_CONDITION(nodes[3].GetResourcePath() == "/special_chars.dummy.txt", "Check child name") // find all resources nodes = module->FindResources("", "", true); US_TEST_CONDITION(nodes.size() == 8, "Total resource number") nodes = module->FindResources("", "**", true); US_TEST_CONDITION(nodes.size() == 8, "Total resource number") // test pattern matching nodes.clear(); nodes = module->FindResources("/icons", "*micro*.png", false); US_TEST_CONDITION(nodes.size() == 1 && nodes[0].GetResourcePath() == "/icons/cppmicroservices.png", "Check file pattern matches") nodes.clear(); nodes = module->FindResources("", "*.txt", true); US_TEST_CONDITION(nodes.size() == 4, "Check recursive pattern matches") } void testResourceOperators(Module* module) { ModuleResource invalid = module->GetResource("invalid"); ModuleResource foo = module->GetResource("foo.txt"); US_TEST_CONDITION_REQUIRED(foo.IsValid() && foo, "Check valid resource") ModuleResource foo2(foo); US_TEST_CONDITION(foo == foo, "Check equality operator") US_TEST_CONDITION(foo == foo2, "Check copy constructor and equality operator") US_TEST_CONDITION(foo != invalid, "Check inequality with invalid resource") ModuleResource xml = module->GetResource("/test.xml"); US_TEST_CONDITION_REQUIRED(xml.IsValid() && xml, "Check valid resource") US_TEST_CONDITION(foo != xml, "Check inequality") US_TEST_CONDITION(foo < xml, "Check operator<") // check operator< by using a set std::set resources; resources.insert(foo); resources.insert(foo); resources.insert(xml); US_TEST_CONDITION(resources.size() == 2, "Check operator< with set") // check hash function specialization US_UNORDERED_SET_TYPE resources2; resources2.insert(foo); resources2.insert(foo); resources2.insert(xml); US_TEST_CONDITION(resources2.size() == 2, "Check operator< with unordered set") // check operator<< std::ostringstream oss; oss << foo; US_TEST_CONDITION(oss.str() == foo.GetResourcePath(), "Check operator<<") } void testResourceFromExecutable(Module* module) { ModuleResource resource = module->GetResource("usTestResource.txt"); US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid executable resource") std::string line; ModuleResourceStream rs(resource); std::getline(rs, line); US_TEST_CONDITION(line == "meant to be compiled into the test driver", "Check executable resource content") } void testResourcesFrom(const std::string& moduleName) { #ifdef US_BUILD_SHARED_LIBS SharedLibrary libR(LIB_PATH, moduleName); try { libR.Load(); } catch (const std::exception& e) { US_TEST_FAILED_MSG(<< "Load module exception: " << e.what()) } #endif Module* moduleR = ModuleRegistry::GetModule(moduleName); US_TEST_CONDITION_REQUIRED(moduleR != nullptr, "Test for existing module") US_TEST_CONDITION(moduleR->GetName() == moduleName, "Test module name") US_TEST_CONDITION(moduleR->FindResources("", "*.txt", true).size() == 2, "Resource count") #ifdef US_BUILD_SHARED_LIBS libR.Unload(); #endif } } // end unnamed namespace int usModuleResourceTest(int /*argc*/, char* /*argv*/[]) { US_TEST_BEGIN("ModuleResourceTest"); ModuleContext* mc = GetModuleContext(); assert(mc); #ifdef US_BUILD_SHARED_LIBS SharedLibrary libR(LIB_PATH, "TestModuleR"); try { libR.Load(); } catch (const std::exception& e) { US_TEST_FAILED_MSG(<< "Load module exception: " << e.what()) } #endif Module* moduleR = ModuleRegistry::GetModule("TestModuleR"); US_TEST_CONDITION_REQUIRED(moduleR != nullptr, "Test for existing module TestModuleR") US_TEST_CONDITION(moduleR->GetName() == "TestModuleR", "Test module name") testInvalidResource(moduleR); testResourceFromExecutable(mc->GetModule()); testResourceTree(moduleR); testResourceOperators(moduleR); testTextResource(moduleR); testTextResourceAsBinary(moduleR); testSpecialCharacters(moduleR); testBinaryResource(moduleR); testCompressedResource(moduleR); ModuleResource foo = moduleR->GetResource("foo.txt"); US_TEST_CONDITION(foo.IsValid() == true, "Valid resource") #ifdef US_BUILD_SHARED_LIBS libR.Unload(); US_TEST_CONDITION(foo.IsValid() == true, "Still valid resource") #endif testResourcesFrom("TestModuleRL"); testResourcesFrom("TestModuleRA"); US_TEST_END() } diff --git a/Modules/DicomRT/CMakeLists.txt b/Modules/DicomRT/CMakeLists.txt index 91a992314e..4b74df9614 100644 --- a/Modules/DicomRT/CMakeLists.txt +++ b/Modules/DicomRT/CMakeLists.txt @@ -1,10 +1,10 @@ if(NOT DEFINED DCMTK_dcmrt_LIBRARY OR DCMTK_dcmrt_LIBRARY) mitk_create_module( - DEPENDS MitkSegmentation MitkSceneSerializationBase MitkDICOMReader MitkDICOMReaderServices + DEPENDS MitkSegmentation MitkSceneSerializationBase MitkLegacyIO MitkDICOMReader MitkDICOMReaderServices PACKAGE_DEPENDS PUBLIC Qt5|Core DCMTK ) add_subdirectory(autoload/IO) add_subdirectory(test) else() message("MITK DicomRT Support disabled because the DCMTK dcmrt library not found") endif() diff --git a/Modules/IOExt/CMakeLists.txt b/Modules/IOExt/CMakeLists.txt new file mode 100644 index 0000000000..ccfb990d3c --- /dev/null +++ b/Modules/IOExt/CMakeLists.txt @@ -0,0 +1,4 @@ +MITK_CREATE_MODULE(DEPENDS MitkDataTypesExt MitkMapperExt MitkSceneSerialization MitkLegacyIO + PACKAGE_DEPENDS PRIVATE ITK|ITKIOImageBase VTK|vtkIOPLY+vtkIOExport+vtkIOParallelXML + AUTOLOAD_WITH MitkCore + ) diff --git a/Modules/IOExt/Documentation/Doxygen/Modules.dox b/Modules/IOExt/Documentation/Doxygen/Modules.dox new file mode 100644 index 0000000000..e8b578c186 --- /dev/null +++ b/Modules/IOExt/Documentation/Doxygen/Modules.dox @@ -0,0 +1,15 @@ +/** + \defgroup MitkIOExtModule IOExt + \ingroup MITKModules + + \brief Reader, writer, and mapper extensions for MITK + + This module provides reader and writer implementations for + data types defined in the \ref MitkDataTypesExtModule module. + It also provides registration code for mappers define in the + \ref MitkMapperExtModule module. + + The module does not provide any public API. It is loaded + automatically with the Mitk Core and registers the reader, + writer, and mapper classes. +*/ diff --git a/Modules/IOExt/Internal/mitkIOExtActivator.cpp b/Modules/IOExt/Internal/mitkIOExtActivator.cpp new file mode 100644 index 0000000000..ce44c1b7bc --- /dev/null +++ b/Modules/IOExt/Internal/mitkIOExtActivator.cpp @@ -0,0 +1,41 @@ +/*=================================================================== + +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 "mitkIOExtActivator.h" + +#include "mitkObjFileReaderService.h" +#include "mitkPlyFileReaderService.h" +#include "mitkPlyFileWriterService.h" +#include "mitkSceneFileReader.h" +#include "mitkVtkUnstructuredGridReader.h" + +namespace mitk +{ + void IOExtActivator::Load(us::ModuleContext *) + { + m_SceneReader.reset(new SceneFileReader()); + + m_VtkUnstructuredGridReader.reset(new VtkUnstructuredGridReader()); + m_ObjReader.reset(new ObjFileReaderService()); + + m_PlyReader.reset(new PlyFileReaderService()); + m_ObjWriter.reset(new PlyFileWriterService()); + } + + void IOExtActivator::Unload(us::ModuleContext *) {} +} + +US_EXPORT_MODULE_ACTIVATOR(mitk::IOExtActivator) diff --git a/Modules/IOExt/Internal/mitkIOExtActivator.h b/Modules/IOExt/Internal/mitkIOExtActivator.h new file mode 100644 index 0000000000..09e231bb70 --- /dev/null +++ b/Modules/IOExt/Internal/mitkIOExtActivator.h @@ -0,0 +1,45 @@ +/*=================================================================== + +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 MITKIOEXTACTIVATOR_H +#define MITKIOEXTACTIVATOR_H + +#include + +#include + +namespace mitk +{ + struct IFileReader; + struct IFileWriter; + + class IOExtActivator : public us::ModuleActivator + { + public: + void Load(us::ModuleContext *context) override; + void Unload(us::ModuleContext *context) override; + + private: + std::unique_ptr m_SceneReader; + std::unique_ptr m_VtkUnstructuredGridReader; + std::unique_ptr m_ObjReader; + std::unique_ptr m_ObjWriter; + + std::unique_ptr m_PlyReader; + }; +} + +#endif // MITKIOEXTACTIVATOR_H diff --git a/Modules/IOExt/Internal/mitkIOExtObjectFactory.cpp b/Modules/IOExt/Internal/mitkIOExtObjectFactory.cpp new file mode 100644 index 0000000000..c5871d1a1a --- /dev/null +++ b/Modules/IOExt/Internal/mitkIOExtObjectFactory.cpp @@ -0,0 +1,184 @@ +/*=================================================================== + +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 "mitkIOExtObjectFactory.h" + +#include "mitkCoreObjectFactory.h" + +#include "mitkParRecFileIOFactory.h" +//#include "mitkObjFileIOFactory.h" +#include "mitkStlVolumeTimeSeriesIOFactory.h" +#include "mitkVtkVolumeTimeSeriesIOFactory.h" + +#include "mitkUnstructuredGridVtkWriter.h" +#include "mitkUnstructuredGridVtkWriterFactory.h" + +#include "mitkVolumeMapperVtkSmart3D.h" +#include "mitkMesh.h" +#include "mitkMeshMapper2D.h" +#include "mitkMeshVtkMapper3D.h" +#include "mitkUnstructuredGridMapper2D.h" +#include "mitkUnstructuredGridVtkMapper3D.h" +#include "mitkVtkGLMapperWrapper.h" + +#include +#include +#include + +mitk::IOExtObjectFactory::IOExtObjectFactory() + : CoreObjectFactoryBase(), + m_ParRecFileIOFactory(ParRecFileIOFactory::New().GetPointer()) + //, m_ObjFileIOFactory(ObjFileIOFactory::New().GetPointer()) + , + m_StlVolumeTimeSeriesIOFactory(StlVolumeTimeSeriesIOFactory::New().GetPointer()), + m_VtkVolumeTimeSeriesIOFactory(VtkVolumeTimeSeriesIOFactory::New().GetPointer()), + m_UnstructuredGridVtkWriterFactory(UnstructuredGridVtkWriterFactory::New().GetPointer()) +{ + static bool alreadyDone = false; + if (!alreadyDone) + { + MITK_DEBUG << "IOExtObjectFactory c'tor" << std::endl; + + itk::ObjectFactoryBase::RegisterFactory(m_ParRecFileIOFactory); + itk::ObjectFactoryBase::RegisterFactory(m_StlVolumeTimeSeriesIOFactory); + itk::ObjectFactoryBase::RegisterFactory(m_VtkVolumeTimeSeriesIOFactory); + + itk::ObjectFactoryBase::RegisterFactory(m_UnstructuredGridVtkWriterFactory); + + m_FileWriters.push_back(mitk::UnstructuredGridVtkWriter::New().GetPointer()); + m_FileWriters.push_back(mitk::UnstructuredGridVtkWriter::New().GetPointer()); + m_FileWriters.push_back(mitk::UnstructuredGridVtkWriter::New().GetPointer()); + + CreateFileExtensionsMap(); + + alreadyDone = true; + } +} + +mitk::IOExtObjectFactory::~IOExtObjectFactory() +{ + itk::ObjectFactoryBase::UnRegisterFactory(m_ParRecFileIOFactory); + itk::ObjectFactoryBase::UnRegisterFactory(m_StlVolumeTimeSeriesIOFactory); + itk::ObjectFactoryBase::UnRegisterFactory(m_VtkVolumeTimeSeriesIOFactory); + + itk::ObjectFactoryBase::UnRegisterFactory(m_UnstructuredGridVtkWriterFactory); +} + +mitk::Mapper::Pointer mitk::IOExtObjectFactory::CreateMapper(mitk::DataNode *node, MapperSlotId id) +{ + mitk::Mapper::Pointer newMapper = nullptr; + mitk::BaseData *data = node->GetData(); + + if (id == mitk::BaseRenderer::Standard2D) + { + if ((dynamic_cast(data) != nullptr)) + { + newMapper = mitk::MeshMapper2D::New(); + newMapper->SetDataNode(node); + } + else if ((dynamic_cast(data) != nullptr)) + { + newMapper = mitk::VtkGLMapperWrapper::New(mitk::UnstructuredGridMapper2D::New().GetPointer()); + newMapper->SetDataNode(node); + } + } + else if (id == mitk::BaseRenderer::Standard3D) + { + if ((dynamic_cast(data) != nullptr)) + { + newMapper = mitk::VolumeMapperVtkSmart3D::New(); + newMapper->SetDataNode(node); + } + else if ((dynamic_cast(data) != nullptr)) + { + newMapper = mitk::MeshVtkMapper3D::New(); + newMapper->SetDataNode(node); + } + else if ((dynamic_cast(data) != nullptr)) + { + newMapper = mitk::UnstructuredGridVtkMapper3D::New(); + newMapper->SetDataNode(node); + } + } + return newMapper; +} + +void mitk::IOExtObjectFactory::SetDefaultProperties(mitk::DataNode *node) +{ + if (node == nullptr) + return; + + mitk::DataNode::Pointer nodePointer = node; + + mitk::Image::Pointer image = dynamic_cast(node->GetData()); + if (image.IsNotNull() && image->IsInitialized()) + { + mitk::VolumeMapperVtkSmart3D::SetDefaultProperties(node); + } + + if (dynamic_cast(node->GetData())) + { + mitk::UnstructuredGridVtkMapper3D::SetDefaultProperties(node); + } +} + +const char *mitk::IOExtObjectFactory::GetFileExtensions() +{ + std::string fileExtension; + this->CreateFileExtensions(m_FileExtensionsMap, fileExtension); + return fileExtension.c_str(); +} + +mitk::CoreObjectFactoryBase::MultimapType mitk::IOExtObjectFactory::GetFileExtensionsMap() +{ + return m_FileExtensionsMap; +} + +mitk::CoreObjectFactoryBase::MultimapType mitk::IOExtObjectFactory::GetSaveFileExtensionsMap() +{ + return m_SaveFileExtensionsMap; +} + +void mitk::IOExtObjectFactory::CreateFileExtensionsMap() +{ + m_FileExtensionsMap.insert(std::pair("*.vtu", "VTK Unstructured Grid")); + m_FileExtensionsMap.insert(std::pair("*.vtk", "VTK Unstructured Grid")); + m_FileExtensionsMap.insert(std::pair("*.pvtu", "VTK Unstructured Grid")); + + m_SaveFileExtensionsMap.insert(std::pair("*.pvtu", "VTK Parallel XML Unstructured Grid")); + m_SaveFileExtensionsMap.insert(std::pair("*.vtu", "VTK XML Unstructured Grid")); + m_SaveFileExtensionsMap.insert(std::pair("*.vtk", "VTK Legacy Unstructured Grid")); +} + +const char *mitk::IOExtObjectFactory::GetSaveFileExtensions() +{ + std::string fileExtension; + this->CreateFileExtensions(m_SaveFileExtensionsMap, fileExtension); + return fileExtension.c_str(); +} + +struct RegisterIOExtObjectFactory +{ + RegisterIOExtObjectFactory() : m_Factory(mitk::IOExtObjectFactory::New()) + { + mitk::CoreObjectFactory::GetInstance()->RegisterExtraFactory(m_Factory); + } + + ~RegisterIOExtObjectFactory() { mitk::CoreObjectFactory::GetInstance()->UnRegisterExtraFactory(m_Factory); } + mitk::IOExtObjectFactory::Pointer m_Factory; +}; + +static RegisterIOExtObjectFactory registerIOExtObjectFactory; diff --git a/Modules/IOExt/Internal/mitkIOExtObjectFactory.h b/Modules/IOExt/Internal/mitkIOExtObjectFactory.h new file mode 100644 index 0000000000..356070a1dd --- /dev/null +++ b/Modules/IOExt/Internal/mitkIOExtObjectFactory.h @@ -0,0 +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 COREEXTOBJECTFACTORY_H_INCLUDED +#define COREEXTOBJECTFACTORY_H_INCLUDED + +#include "mitkCoreObjectFactoryBase.h" + +namespace mitk +{ + class IOExtObjectFactory : public CoreObjectFactoryBase + { + public: + mitkClassMacro(IOExtObjectFactory, CoreObjectFactoryBase) itkFactorylessNewMacro(Self) itkCloneMacro(Self) + + virtual Mapper::Pointer CreateMapper(mitk::DataNode *node, MapperSlotId slotId) override; + virtual void SetDefaultProperties(mitk::DataNode *node) override; + virtual const char *GetFileExtensions() override; + virtual mitk::CoreObjectFactoryBase::MultimapType GetFileExtensionsMap() override; + virtual const char *GetSaveFileExtensions() override; + virtual mitk::CoreObjectFactoryBase::MultimapType GetSaveFileExtensionsMap() override; + + private: + IOExtObjectFactory(); + ~IOExtObjectFactory(); + + void CreateFileExtensionsMap(); + MultimapType m_FileExtensionsMap; + MultimapType m_SaveFileExtensionsMap; + + itk::ObjectFactoryBase::Pointer m_ParRecFileIOFactory; + itk::ObjectFactoryBase::Pointer m_VtkUnstructuredGridIOFactory; + itk::ObjectFactoryBase::Pointer m_StlVolumeTimeSeriesIOFactory; + itk::ObjectFactoryBase::Pointer m_VtkVolumeTimeSeriesIOFactory; + + itk::ObjectFactoryBase::Pointer m_UnstructuredGridVtkWriterFactory; + }; +} + +#endif diff --git a/Modules/IOExt/Internal/mitkObjFileReaderService.cpp b/Modules/IOExt/Internal/mitkObjFileReaderService.cpp new file mode 100644 index 0000000000..05ba01e7c0 --- /dev/null +++ b/Modules/IOExt/Internal/mitkObjFileReaderService.cpp @@ -0,0 +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. + +===================================================================*/ + +// MITK +#include "mitkObjFileReaderService.h" +#include +#include +#include + +// VTK +#include +#include + +mitk::ObjFileReaderService::ObjFileReaderService() + : AbstractFileReader(CustomMimeType(IOMimeTypes::WAVEFRONT_OBJ_MIMETYPE()), "Wavefront OBJ Reader") +{ + this->RegisterService(); +} + +mitk::ObjFileReaderService::~ObjFileReaderService() +{ +} + +std::vector> mitk::ObjFileReaderService::Read() +{ + std::vector> result; + + vtkSmartPointer reader = vtkSmartPointer::New(); + reader->SetFileName(GetInputLocation().c_str()); + reader->Update(); + + if (reader->GetOutput() != nullptr) + { + mitk::Surface::Pointer surface = mitk::Surface::New(); + surface->SetVtkPolyData(reader->GetOutput()); + result.push_back(dynamic_cast(surface.GetPointer())); + } + return result; +} + +mitk::ObjFileReaderService *mitk::ObjFileReaderService::Clone() const +{ + return new ObjFileReaderService(*this); +} diff --git a/Modules/IOExt/Internal/mitkObjFileReaderService.h b/Modules/IOExt/Internal/mitkObjFileReaderService.h new file mode 100644 index 0000000000..7a6afeb10c --- /dev/null +++ b/Modules/IOExt/Internal/mitkObjFileReaderService.h @@ -0,0 +1,49 @@ +/*=================================================================== + +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 ObjFileReaderService_h +#define ObjFileReaderService_h + +#include +#include + +namespace mitk +{ + class BaseData; + + /** + * @brief Used to read surfaces from Wavefront OBJ files. + * + * @ingroup IOExt + */ + class ObjFileReaderService : public AbstractFileReader + { + public: + ObjFileReaderService(); + virtual ~ObjFileReaderService(); + + using AbstractFileReader::Read; + virtual std::vector> Read() override; + + static mitk::CustomMimeType mimeType; + + private: + ObjFileReaderService *Clone() const override; + }; + +} // namespace mitk + +#endif /* ObjFileReaderService_h */ diff --git a/Modules/IOExt/Internal/mitkParRecFileIOFactory.cpp b/Modules/IOExt/Internal/mitkParRecFileIOFactory.cpp new file mode 100644 index 0000000000..8a07f12078 --- /dev/null +++ b/Modules/IOExt/Internal/mitkParRecFileIOFactory.cpp @@ -0,0 +1,41 @@ +/*=================================================================== + +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 "mitkParRecFileIOFactory.h" +#include "mitkIOAdapter.h" +#include "mitkParRecFileReader.h" + +#include "itkVersion.h" + +namespace mitk +{ + ParRecFileIOFactory::ParRecFileIOFactory() + { + this->RegisterOverride("mitkIOAdapter", + "mitkParRecFileReader", + "mitk ParRec Image IO", + 1, + itk::CreateObjectFunction>::New()); + } + + ParRecFileIOFactory::~ParRecFileIOFactory() {} + const char *ParRecFileIOFactory::GetITKSourceVersion() const { return ITK_SOURCE_VERSION; } + const char *ParRecFileIOFactory::GetDescription() const + { + return "ParRecFile IO Factory, allows the loading of ParRec images"; + } + +} // end namespace mitk diff --git a/Modules/IOExt/Internal/mitkParRecFileIOFactory.h b/Modules/IOExt/Internal/mitkParRecFileIOFactory.h new file mode 100644 index 0000000000..ea416f31ad --- /dev/null +++ b/Modules/IOExt/Internal/mitkParRecFileIOFactory.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 __mitkParRecFileIOFactory_h +#define __mitkParRecFileIOFactory_h + +#ifdef _MSC_VER +#pragma warning(disable : 4786) +#endif + +#include "itkObjectFactoryBase.h" +#include "mitkBaseData.h" + +namespace mitk +{ + //##Documentation + //## @brief Create instances of ParRecFileReader objects using an object factory. + //## + class ParRecFileIOFactory : public itk::ObjectFactoryBase + { + public: + /** Standard class typedefs. */ + typedef ParRecFileIOFactory 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 override; + virtual const char *GetDescription(void) const override; + + /** Method for class instantiation. */ + itkFactorylessNewMacro(Self); + static ParRecFileIOFactory *FactoryNew() { return new ParRecFileIOFactory; } + /** Run-time type information (and related methods). */ + itkTypeMacro(ParRecFileIOFactory, ObjectFactoryBase); + + /** + * Register one factory of this type + * \deprecatedSince{2013_09} + */ + DEPRECATED(static void RegisterOneFactory(void)) + { + ParRecFileIOFactory::Pointer ParRecFileIOFactory = ParRecFileIOFactory::New(); + ObjectFactoryBase::RegisterFactory(ParRecFileIOFactory); + } + + protected: + ParRecFileIOFactory(); + ~ParRecFileIOFactory(); + + private: + ParRecFileIOFactory(const Self &); // purposely not implemented + void operator=(const Self &); // purposely not implemented + }; + +} // end namespace mitk + +#endif diff --git a/Modules/IOExt/Internal/mitkParRecFileReader.cpp b/Modules/IOExt/Internal/mitkParRecFileReader.cpp new file mode 100644 index 0000000000..62bde82397 --- /dev/null +++ b/Modules/IOExt/Internal/mitkParRecFileReader.cpp @@ -0,0 +1,284 @@ +/*=================================================================== + +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 "mitkParRecFileReader.h" +#include +#include + +#ifdef __GNUC__ +#define stricmp strcasecmp +#endif + +void mitk::ParRecFileReader::GenerateOutputInformation() +{ + mitk::Image::Pointer output = this->GetOutput(); + + if ((output->IsInitialized()) && (this->GetMTime() <= m_ReadHeaderTime.GetMTime())) + return; + + itkDebugMacro(<< "Reading PAR file for GenerateOutputInformation()" << m_FileName); + + // Check to see if we can read the file given the name or prefix + // + if (m_FileName == "" && m_FilePrefix == "") + { + throw itk::ImageFileReaderException(__FILE__, __LINE__, "One of FileName or FilePrefix must be non-empty"); + } + + m_RecFileName = ""; + if (m_FileName != "") + { + int extPos = m_FileName.find_last_of("."); + if (extPos >= -1) + { + const char *ext = m_FileName.c_str() + extPos + 1; + if (stricmp(ext, "par") == 0) + m_RecFileName = m_FileName.substr(0, extPos); + else + m_RecFileName = m_FileName; + } + else + m_RecFileName = m_FileName; + + m_RecFileName.append(".rec"); + + bool headerRead = false; + + bool signedCharType = true; + unsigned int dimension = 0; + unsigned int dimensions[4] = {0, 0, 1, 1}; + float sliceThickness = 0.0; + float sliceGap = 0.0; + float sliceSpacing = 0.0; + mitk::Vector3D thickness; + thickness.Fill(1.0); + mitk::Vector3D gap; + gap.Fill(0.0); + mitk::Vector3D spacing; + + FILE *f; + f = fopen(m_FileName.c_str(), "r"); + if (f != nullptr) + { + while (!feof(f)) + { + char s[300], *p; + char *ignored = fgets(s, 200, f); + ++ignored; + if (strstr(s, "Max. number of cardiac phases")) + { + p = strchr(s, ':') + 1; + dimensions[3] = atoi(p); + if (dimensions[3] > 1) + dimension = 4; + } + else if (strstr(s, "Max. number of slices/locations")) + { + p = strchr(s, ':') + 1; + dimensions[2] = atoi(p); + if (dimension == 0) + { + if (dimensions[2] > 1) + dimension = 3; + else + dimension = 2; + } + } + else if (strstr(s, "Image pixel size")) + { + p = strchr(s, ':') + 1; + int bpe = atoi(p); + if (bpe != 8) + signedCharType = false; + } + else if (strstr(s, "Recon resolution")) + { + p = s + strcspn(s, "0123456789"); + sscanf(p, "%u %u", dimensions, dimensions + 1); + } + else if (strstr(s, "FOV (ap,fh,rl) [mm]")) + { + p = s + strcspn(s, "0123456789"); + mitk::LocaleSwitch localeSwitch("C"); + sscanf(p, "%lf %lf %lf", &thickness[0], &thickness[1], &thickness[2]); + } + else if (strstr(s, "Slice thickness [mm]")) + { + p = s + strcspn(s, "0123456789"); + mitk::LocaleSwitch localeSwitch("C"); + sscanf(p, "%f", &sliceThickness); + } + else if (strstr(s, "Slice gap [mm]")) + { + p = s + strcspn(s, "-0123456789"); + mitk::LocaleSwitch localeSwitch("C"); + sscanf(p, "%f", &sliceGap); + } + } + fclose(f); + + // C:\home\ivo\data\coronaries\ucsf-wholeheart-2.par + sliceSpacing = sliceThickness + sliceGap; + if ((dimension > 0) && (dimensions[0] > 0) && (dimensions[1] > 0) && (sliceThickness > 0) && (sliceSpacing > 0)) + { + headerRead = true; + if (fabs(thickness[0] / dimensions[2] - sliceSpacing) < 0.0001) + thickness[0] = thickness[1]; + else if (fabs(thickness[1] / dimensions[2] - sliceSpacing) < 0.0001) + thickness[1] = thickness[0]; + thickness[2] = sliceSpacing; + + thickness[0] /= dimensions[0]; + thickness[1] /= dimensions[1]; + spacing = thickness + gap; + } + } + + if (headerRead == false) + { + itk::ImageFileReaderException e(__FILE__, __LINE__); + std::ostringstream msg; + msg << " Could not read file " << m_FileName.c_str(); + e.SetDescription(msg.str().c_str()); + throw e; + return; + } + + // define types + mitk::PixelType SCType = mitk::MakeScalarPixelType(); + mitk::PixelType SSType = mitk::MakeScalarPixelType(); + + if (signedCharType) + output->Initialize(SCType, dimension, dimensions); + else + output->Initialize(SSType, dimension, dimensions); + + output->GetSlicedGeometry()->SetSpacing(spacing); + + // output->GetSlicedGeometry()->SetPlaneGeometry(mitk::Image::BuildStandardPlanePlaneGeometry(output->GetSlicedGeometry(), + // dimensions).GetPointer(), 0); + output->GetSlicedGeometry()->SetEvenlySpaced(); + } + + m_ReadHeaderTime.Modified(); +} + +void mitk::ParRecFileReader::GenerateData() +{ + mitk::Image::Pointer output = this->GetOutput(); + + // Check to see if we can read the file given the name or prefix + // + if (m_RecFileName == "") + { + throw itk::ImageFileReaderException(__FILE__, __LINE__, "FileName for rec-file empty"); + } + + if (m_RecFileName != "") + { + FILE *f = fopen(m_RecFileName.c_str(), "r"); + if (f == nullptr) + { + throw itk::ImageFileReaderException(__FILE__, __LINE__, "Could not open rec-file."); + } + + int zstart, zmax; + int tstart, tmax; + + zstart = output->GetRequestedRegion().GetIndex(2); + tstart = output->GetRequestedRegion().GetIndex(3); + + zmax = zstart + output->GetRequestedRegion().GetSize(2); + tmax = tstart + output->GetRequestedRegion().GetSize(3); + + int sliceSize = output->GetDimension(0) * output->GetDimension(1) * output->GetPixelType().GetBpe() / 8; + void *data = malloc(sliceSize); + + bool ignore4Dtopogram = false; + { + int slicePlusTimeSize = output->GetDimension(0) * output->GetDimension(1) * output->GetDimension(3) * + output->GetPixelType().GetBpe() / 8; + if (output->GetDimension(3) > 1) + ignore4Dtopogram = true; + + int z, t; + for (t = tstart; t < tmax; ++t) + for (z = zstart; z < zmax; ++z) + { + if (ignore4Dtopogram) + fseek(f, slicePlusTimeSize * z + (sliceSize + 1) * t, SEEK_SET); + else + fseek(f, slicePlusTimeSize * z + sliceSize * t, SEEK_SET); + size_t ignored = fread(data, sliceSize, 1, f); + ++ignored; + output->SetSlice(data, z, t, 0); + } + } + // else + //{ + // for(;zSetSlice(data,z,0,0); + // } + //} + free(data); + + fclose(f); + } +} + +bool mitk::ParRecFileReader::CanReadFile(const std::string filename, + const std::string /*filePrefix*/, + const std::string /*filePattern*/) +{ + // First check the extension + if (filename == "") + { + // MITK_INFO<<"No filename specified."< +#include +#include + +// VTK +#include +#include + +mitk::PlyFileReaderService::PlyFileReaderService() + : AbstractFileReader(CustomMimeType(IOMimeTypes::STANFORD_PLY_MIMETYPE()), "Stanford Triangle PLY Reader") +{ + this->RegisterService(); +} + +mitk::PlyFileReaderService::~PlyFileReaderService() +{ +} + +std::vector> mitk::PlyFileReaderService::Read() +{ + std::vector> result; + + vtkSmartPointer reader = vtkSmartPointer::New(); + reader->SetFileName(GetInputLocation().c_str()); + reader->Update(); + + if (reader->GetOutput() != nullptr) + { + mitk::Surface::Pointer surface = mitk::Surface::New(); + surface->SetVtkPolyData(reader->GetOutput()); + result.push_back(dynamic_cast(surface.GetPointer())); + } + return result; +} + +mitk::PlyFileReaderService *mitk::PlyFileReaderService::Clone() const +{ + return new PlyFileReaderService(*this); +} diff --git a/Modules/IOExt/Internal/mitkPlyFileReaderService.h b/Modules/IOExt/Internal/mitkPlyFileReaderService.h new file mode 100644 index 0000000000..5fa433131f --- /dev/null +++ b/Modules/IOExt/Internal/mitkPlyFileReaderService.h @@ -0,0 +1,51 @@ +/*=================================================================== + +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 PlyFileReaderService_h +#define PlyFileReaderService_h + +#include +#include + +namespace mitk +{ + class BaseData; + + /** + * @brief Used to read surfaces from the PLY format. + * + * This reader can read binary and ASCII versions of the format transparently. + * + * @ingroup IOExt + */ + class PlyFileReaderService : public AbstractFileReader + { + public: + PlyFileReaderService(); + virtual ~PlyFileReaderService(); + + using AbstractFileReader::Read; + virtual std::vector> Read() override; + + static mitk::CustomMimeType mimeType; + + private: + PlyFileReaderService *Clone() const override; + }; + +} // namespace mitk + +#endif /* PlyFileReaderService_h */ diff --git a/Modules/IOExt/Internal/mitkPlyFileWriterService.cpp b/Modules/IOExt/Internal/mitkPlyFileWriterService.cpp new file mode 100644 index 0000000000..09bc6d9e6d --- /dev/null +++ b/Modules/IOExt/Internal/mitkPlyFileWriterService.cpp @@ -0,0 +1,59 @@ +/*=================================================================== + +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. + +===================================================================*/ + +// MITK +#include "mitkPlyFileWriterService.h" +#include +#include + +// VTK +#include +#include +#include +#include + +mitk::PlyFileWriterService::PlyFileWriterService() + : AbstractFileWriter(mitk::Surface::GetStaticNameOfClass(), + CustomMimeType(IOMimeTypes::STANFORD_PLY_MIMETYPE()), + "Stanford Triangle PLY Writer") +{ + RegisterService(); +} + +mitk::PlyFileWriterService::PlyFileWriterService(const mitk::PlyFileWriterService &other) : AbstractFileWriter(other) +{ +} + +mitk::PlyFileWriterService::~PlyFileWriterService() +{ +} + +void mitk::PlyFileWriterService::Write() +{ + vtkSmartPointer writer = vtkSmartPointer::New(); + writer->SetFileTypeToBinary(); + writer->SetFileName(GetOutputLocation().c_str()); + + const mitk::Surface *surface = static_cast(this->GetInput()); + writer->SetInputDataObject(surface->GetVtkPolyData()); + + writer->Write(); +} + +mitk::PlyFileWriterService *mitk::PlyFileWriterService::Clone() const +{ + return new PlyFileWriterService(*this); +} diff --git a/Modules/IOExt/Internal/mitkPlyFileWriterService.h b/Modules/IOExt/Internal/mitkPlyFileWriterService.h new file mode 100644 index 0000000000..bda67e4e6b --- /dev/null +++ b/Modules/IOExt/Internal/mitkPlyFileWriterService.h @@ -0,0 +1,48 @@ +/*=================================================================== + +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 PlyFileWriterService_h +#define PlyFileWriterService_h + +#include + +namespace mitk +{ + /** + * @brief Used to write Surfaces to the PLY format. + * + * Currently, this writer uses the binary format as standard. Should the ASCII Format be required, + * it is suggested to incorporate Options. + * + * @ingroup IOExt + */ + class PlyFileWriterService : public AbstractFileWriter + { + public: + PlyFileWriterService(); + virtual ~PlyFileWriterService(); + + using AbstractFileWriter::Write; + virtual void Write() override; + + private: + PlyFileWriterService(const PlyFileWriterService &other); + + virtual mitk::PlyFileWriterService *Clone() const override; + }; +} + +#endif diff --git a/Modules/IOExt/Internal/mitkSceneFileReader.cpp b/Modules/IOExt/Internal/mitkSceneFileReader.cpp new file mode 100644 index 0000000000..e712eb923c --- /dev/null +++ b/Modules/IOExt/Internal/mitkSceneFileReader.cpp @@ -0,0 +1,69 @@ +/*=================================================================== + +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 "mitkSceneFileReader.h" + +#include +#include +#include + +namespace mitk +{ + SceneFileReader::SceneFileReader() : AbstractFileReader() + { + CustomMimeType mimeType(IOMimeTypes::DEFAULT_BASE_NAME() + ".scene"); + mimeType.SetComment("MITK Scene Files"); + mimeType.SetCategory("MITK Scenes"); + mimeType.AddExtension("mitk"); + + this->SetDescription("MITK Scene Reader"); + this->SetMimeType(mimeType); + + this->RegisterService(); + } + + DataStorage::SetOfObjects::Pointer SceneFileReader::Read(DataStorage &ds) + { + // const DataStorage::SetOfObjects::STLContainerType& oldNodes = ds.GetAll()->CastToSTLConstContainer(); + DataStorage::SetOfObjects::ConstPointer oldNodes = ds.GetAll(); + SceneIO::Pointer sceneIO = SceneIO::New(); + sceneIO->LoadScene(this->GetLocalFileName(), &ds, false); + DataStorage::SetOfObjects::ConstPointer newNodes = ds.GetAll(); + + // Compute the difference + DataStorage::SetOfObjects::Pointer result = DataStorage::SetOfObjects::New(); + + unsigned int index = 0; + for (DataStorage::SetOfObjects::ConstIterator iter = newNodes->Begin(), iterEnd = newNodes->End(); iter != iterEnd; + ++iter) + { + if (!oldNodes->empty()) + { + if (std::find(oldNodes->begin(), oldNodes->end(), iter.Value()) == oldNodes->end()) + result->InsertElement(index++, iter.Value()); + } + else + { + result->InsertElement(index++, iter.Value()); + } + } + + return result; + } + + std::vector SceneFileReader::Read() { return AbstractFileReader::Read(); } + SceneFileReader *SceneFileReader::Clone() const { return new SceneFileReader(*this); } +} diff --git a/Modules/IOExt/Internal/mitkSceneFileReader.h b/Modules/IOExt/Internal/mitkSceneFileReader.h new file mode 100644 index 0000000000..5856d17856 --- /dev/null +++ b/Modules/IOExt/Internal/mitkSceneFileReader.h @@ -0,0 +1,40 @@ +/*=================================================================== + +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 SceneFileReader_H_HEADER_INCLUDED +#define SceneFileReader_H_HEADER_INCLUDED + +// MITK +#include + +namespace mitk +{ + class SceneFileReader : public mitk::AbstractFileReader + { + public: + SceneFileReader(); + + using AbstractFileReader::Read; + virtual std::vector> Read() override; + virtual DataStorage::SetOfObjects::Pointer Read(DataStorage &ds) override; + + private: + SceneFileReader *Clone() const override; + }; + +} // namespace mitk + +#endif /* SceneFileReader_H_HEADER_INCLUDED_C1E7E521 */ diff --git a/Modules/IOExt/Internal/mitkStlVolumeTimeSeriesIOFactory.cpp b/Modules/IOExt/Internal/mitkStlVolumeTimeSeriesIOFactory.cpp new file mode 100644 index 0000000000..9b93c6031e --- /dev/null +++ b/Modules/IOExt/Internal/mitkStlVolumeTimeSeriesIOFactory.cpp @@ -0,0 +1,41 @@ +/*=================================================================== + +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 "mitkStlVolumeTimeSeriesIOFactory.h" +#include "mitkIOAdapter.h" +#include "mitkStlVolumeTimeSeriesReader.h" + +#include "itkVersion.h" + +namespace mitk +{ + StlVolumeTimeSeriesIOFactory::StlVolumeTimeSeriesIOFactory() + { + this->RegisterOverride("mitkIOAdapter", + "mitkStlVolumeTimeSeriesReader", + "mitk Stl Surface IO", + 1, + itk::CreateObjectFunction>::New()); + } + + StlVolumeTimeSeriesIOFactory::~StlVolumeTimeSeriesIOFactory() {} + const char *StlVolumeTimeSeriesIOFactory::GetITKSourceVersion() const { return ITK_SOURCE_VERSION; } + const char *StlVolumeTimeSeriesIOFactory::GetDescription() const + { + return "StlVolumeTimeSeries IO Factory, allows the loading of Stl surfaces"; + } + +} // end namespace mitk diff --git a/Modules/IOExt/Internal/mitkStlVolumeTimeSeriesIOFactory.h b/Modules/IOExt/Internal/mitkStlVolumeTimeSeriesIOFactory.h new file mode 100644 index 0000000000..629d91e275 --- /dev/null +++ b/Modules/IOExt/Internal/mitkStlVolumeTimeSeriesIOFactory.h @@ -0,0 +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 __mitkStlVolumeTimeSeriesIOFactory_h +#define __mitkStlVolumeTimeSeriesIOFactory_h + +#ifdef _MSC_VER +#pragma warning(disable : 4786) +#endif + +#include "itkObjectFactoryBase.h" +#include "mitkBaseData.h" + +namespace mitk +{ + //##Documentation + //## @brief Create instances of StlVolumeTimeSeriesReader objects using an object factory. + class StlVolumeTimeSeriesIOFactory : public itk::ObjectFactoryBase + { + public: + /** Standard class typedefs. */ + typedef StlVolumeTimeSeriesIOFactory 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 override; + virtual const char *GetDescription(void) const override; + + /** Method for class instantiation. */ + itkFactorylessNewMacro(Self); + static StlVolumeTimeSeriesIOFactory *FactoryNew() { return new StlVolumeTimeSeriesIOFactory; } + /** Run-time type information (and related methods). */ + itkTypeMacro(StlVolumeTimeSeriesIOFactory, ObjectFactoryBase); + + /** + * Register one factory of this type + * \deprecatedSince{2013_09} + */ + DEPRECATED(static void RegisterOneFactory(void)) + { + StlVolumeTimeSeriesIOFactory::Pointer StlVolumeTimeSeriesIOFactory = StlVolumeTimeSeriesIOFactory::New(); + ObjectFactoryBase::RegisterFactory(StlVolumeTimeSeriesIOFactory); + } + + protected: + StlVolumeTimeSeriesIOFactory(); + ~StlVolumeTimeSeriesIOFactory(); + + private: + StlVolumeTimeSeriesIOFactory(const Self &); // purposely not implemented + void operator=(const Self &); // purposely not implemented + }; + +} // end namespace mitk + +#endif diff --git a/Modules/IOExt/Internal/mitkStlVolumeTimeSeriesReader.cpp b/Modules/IOExt/Internal/mitkStlVolumeTimeSeriesReader.cpp new file mode 100644 index 0000000000..07e1c8514b --- /dev/null +++ b/Modules/IOExt/Internal/mitkStlVolumeTimeSeriesReader.cpp @@ -0,0 +1,80 @@ +/*=================================================================== + +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 "mitkStlVolumeTimeSeriesReader.h" +#include "mitkSurface.h" +#include "vtkPolyData.h" +#include + +void mitk::StlVolumeTimeSeriesReader::GenerateData() +{ + if (!this->GenerateFileList()) + { + itkWarningMacro(<< "Sorry, file list could not be determined..."); + return; + } + + mitk::Surface::Pointer result = this->GetOutput(); + MITK_INFO << "prefix: " << m_FilePrefix << ", pattern: " << m_FilePattern << std::endl; + result->Expand(m_MatchedFileNames.size()); + for (unsigned int i = 0; i < m_MatchedFileNames.size(); ++i) + { + std::string fileName = m_MatchedFileNames[i]; + MITK_INFO << "Loading " << fileName << " as stl..." << std::endl; + + mitk::Surface::Pointer timestepSurface = dynamic_cast(IOUtil::Load(fileName.c_str())[0].GetPointer()); + + if (timestepSurface.IsNull()) + { + itkWarningMacro(<< "stlReader returned nullptr while reading " << fileName + << ". Trying to continue with empty vtkPolyData..."); + result->SetVtkPolyData(vtkPolyData::New(), i); + return; + } + + result->SetVtkPolyData(timestepSurface->GetVtkPolyData(), i); + } +} + +bool mitk::StlVolumeTimeSeriesReader::CanReadFile(const std::string /*filename*/, + const std::string filePrefix, + const std::string filePattern) +{ + if (filePattern != "" && filePrefix != "") + return false; + + bool extensionFound = false; + std::string::size_type STLPos = filePattern.rfind(".stl"); + if ((STLPos != std::string::npos) && (STLPos == filePattern.length() - 4)) + extensionFound = true; + + STLPos = filePattern.rfind(".STL"); + if ((STLPos != std::string::npos) && (STLPos == filePattern.length() - 4)) + extensionFound = true; + + if (!extensionFound) + return false; + + return true; +} + +mitk::StlVolumeTimeSeriesReader::StlVolumeTimeSeriesReader() +{ +} + +mitk::StlVolumeTimeSeriesReader::~StlVolumeTimeSeriesReader() +{ +} diff --git a/Modules/IOExt/Internal/mitkStlVolumeTimeSeriesReader.h b/Modules/IOExt/Internal/mitkStlVolumeTimeSeriesReader.h new file mode 100644 index 0000000000..31dc6945f2 --- /dev/null +++ b/Modules/IOExt/Internal/mitkStlVolumeTimeSeriesReader.h @@ -0,0 +1,61 @@ +/*=================================================================== + +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 _Stl_VOLUME_TIME_SERIES_READER__H_ +#define _Stl_VOLUME_TIME_SERIES_READER__H_ + +#include "mitkCommon.h" +#include "mitkFileSeriesReader.h" +#include "mitkSurfaceSource.h" + +namespace mitk +{ + //##Documentation + //## @brief Reader to read a series of volume files in stl-format + class StlVolumeTimeSeriesReader : public SurfaceSource, public FileSeriesReader + { + public: + mitkClassMacro(StlVolumeTimeSeriesReader, FileSeriesReader); + + /** Method for creation through the object factory. */ + itkFactorylessNewMacro(Self) itkCloneMacro(Self) + + itkSetStringMacro(FileName); + itkGetStringMacro(FileName); + + itkSetStringMacro(FilePrefix); + itkGetStringMacro(FilePrefix); + + itkSetStringMacro(FilePattern); + itkGetStringMacro(FilePattern); + + static bool CanReadFile(const std::string filename, const std::string filePrefix, const std::string filePattern); + + protected: + virtual void GenerateData() override; + + StlVolumeTimeSeriesReader(); + + ~StlVolumeTimeSeriesReader(); + + //##Description + //## @brief Time when Header was last read + itk::TimeStamp m_ReadHeaderTime; + }; + +} // namespace mitk + +#endif diff --git a/Modules/IOExt/Internal/mitkUnstructuredGridVtkWriter.cpp b/Modules/IOExt/Internal/mitkUnstructuredGridVtkWriter.cpp new file mode 100644 index 0000000000..e4982b0b19 --- /dev/null +++ b/Modules/IOExt/Internal/mitkUnstructuredGridVtkWriter.cpp @@ -0,0 +1,103 @@ +/*=================================================================== + +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 "mitkUnstructuredGridVtkWriter.h" +#include "mitkUnstructuredGridVtkWriter.txx" + +namespace mitk +{ + template <> + std::vector UnstructuredGridVtkWriter::GetPossibleFileExtensions() + { + std::vector possibleFileExtensions; + possibleFileExtensions.push_back(".vtk"); + return possibleFileExtensions; + } + + template <> + std::vector UnstructuredGridVtkWriter::GetPossibleFileExtensions() + { + std::vector possibleFileExtensions; + possibleFileExtensions.push_back(".vtu"); + return possibleFileExtensions; + } + + template <> + std::vector UnstructuredGridVtkWriter::GetPossibleFileExtensions() + { + std::vector possibleFileExtensions; + possibleFileExtensions.push_back(".pvtu"); + return possibleFileExtensions; + } + + template <> + const char *UnstructuredGridVtkWriter::GetDefaultFilename() + { + return "vtkUnstructuredGrid.vtk"; + } + + template <> + const char *UnstructuredGridVtkWriter::GetDefaultFilename() + { + return "vtkUnstructuredGrid.vtu"; + } + + template <> + const char *UnstructuredGridVtkWriter::GetDefaultFilename() + { + return "vtkUnstructuredGrid.pvtu"; + } + + template <> + const char *UnstructuredGridVtkWriter::GetFileDialogPattern() + { + return "VTK Legacy Unstructured Grid (*.vtk)"; + } + + template <> + const char *UnstructuredGridVtkWriter::GetFileDialogPattern() + { + return "VTK XML Unstructured Grid (*.vtu)"; + } + + template <> + const char *UnstructuredGridVtkWriter::GetFileDialogPattern() + { + return "VTK Parallel XML Unstructured Grid (*.pvtu)"; + } + + template <> + const char *UnstructuredGridVtkWriter::GetDefaultExtension() + { + return ".vtk"; + } + + template <> + const char *UnstructuredGridVtkWriter::GetDefaultExtension() + { + return ".vtu"; + } + + template <> + const char *UnstructuredGridVtkWriter::GetDefaultExtension() + { + return ".pvtu"; + } + + template class UnstructuredGridVtkWriter; + template class UnstructuredGridVtkWriter; + template class UnstructuredGridVtkWriter; +} diff --git a/Modules/IOExt/Internal/mitkUnstructuredGridVtkWriter.h b/Modules/IOExt/Internal/mitkUnstructuredGridVtkWriter.h new file mode 100644 index 0000000000..7831f239ba --- /dev/null +++ b/Modules/IOExt/Internal/mitkUnstructuredGridVtkWriter.h @@ -0,0 +1,141 @@ +/*=================================================================== + +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_UNSTRUCTURED_GRID_VTK_WRITER__H_ +#define _MITK_UNSTRUCTURED_GRID_VTK_WRITER__H_ + +#include +#include + +#include +#include +#include + +#include "mitkUnstructuredGrid.h" + +namespace mitk +{ + /** + * @brief VTK-based writer for mitk::UnstructuredGrid + * + * The mitk::UnstructuredGrid is written using the VTK-writer-type provided as the + * template argument. If the mitk::UnstructuredGrid contains multiple points of + * time, multiple files are written. The life-span (time-bounds) of each + * each point of time is included in the filename according to the + * following scheme: + * <filename>_S<timebounds[0]>E<timebounds[1]>_T<framenumber> + * (S=start, E=end, T=time). + * Writing of multiple files according to a given filename pattern is not + * yet supported. + */ + template + class UnstructuredGridVtkWriter : public mitk::FileWriterWithInformation + { + public: + mitkClassMacro(UnstructuredGridVtkWriter, mitk::FileWriterWithInformation); + + itkFactorylessNewMacro(Self) itkCloneMacro(Self) + + mitkWriterMacro; + + /** + * 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); + + using FileWriter::SetInput; + + /** + * Sets the 0'th input object for the filter. + * @param input the first input for the filter. + */ + void SetInput(BaseData *input); + + /** + * @returns the 0'th input object of the filter. + */ + const UnstructuredGrid *GetInput(); + + /** + * Returns false if an error happened during writing + */ + itkGetMacro(Success, bool); + + /** + * @brief Return the possible file extensions for the data type associated with the writer + */ + virtual std::vector GetPossibleFileExtensions() override; + + virtual std::string GetSupportedBaseData() const override { return UnstructuredGrid::GetStaticNameOfClass(); } + // FileWriterWithInformation methods + virtual const char *GetDefaultFilename() override; + virtual const char *GetFileDialogPattern() override; + virtual const char *GetDefaultExtension() override; + virtual bool CanWriteBaseDataType(BaseData::Pointer data) override; + virtual void DoWrite(BaseData::Pointer data) override; + + protected: + /** + * Constructor. + */ + UnstructuredGridVtkWriter(); + + /** + * Virtual destructor. + */ + virtual ~UnstructuredGridVtkWriter(); + + void ExecuteWrite(VTKWRITER *vtkWriter); + + virtual void GenerateData() override; + + std::string m_FileName; + + std::string m_FilePrefix; + + std::string m_FilePattern; + + bool m_Success; + }; +} + +#endif // _MITK_UNSTRUCTURED_GRID_VTK_WRITER__H_ diff --git a/Modules/IOExt/Internal/mitkUnstructuredGridVtkWriter.txx b/Modules/IOExt/Internal/mitkUnstructuredGridVtkWriter.txx new file mode 100644 index 0000000000..cb53ffc5da --- /dev/null +++ b/Modules/IOExt/Internal/mitkUnstructuredGridVtkWriter.txx @@ -0,0 +1,200 @@ +/*=================================================================== + +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_UNSTRUCTURED_GRID_VTKWRITER_TXX_ +#define _MITK_UNSTRUCTURED_GRID_VTKWRITER_TXX_ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace mitk +{ + template + UnstructuredGridVtkWriter::UnstructuredGridVtkWriter() : m_Success(false) + { + this->SetNumberOfRequiredInputs(1); + } + + template + UnstructuredGridVtkWriter::~UnstructuredGridVtkWriter() + { + } + + template + void UnstructuredGridVtkWriter::GenerateData() + { + m_Success = false; + if (m_FileName == "") + { + itkWarningMacro(<< "Sorry, filename has not been set!"); + return; + } + + mitk::UnstructuredGrid::Pointer input = const_cast(this->GetInput()); + + if (input.IsNull()) + { + itkWarningMacro(<< "Sorry, input to mitk::UnstructuredGridVtkWriter is NULL"); + return; + } + + VTKWRITER *unstructuredGridWriter = VTKWRITER::New(); + vtkTransformFilter *transformPointSet = vtkTransformFilter::New(); + vtkUnstructuredGrid *unstructuredGrid; + BaseGeometry *geometry; + + if (input->GetTimeGeometry()->CountTimeSteps() > 1) + { + int t, timesteps; + + timesteps = input->GetTimeGeometry()->CountTimeSteps(); + for (t = 0; t < timesteps; ++t) + { + std::ostringstream filename; + geometry = input->GetGeometry(t); + if (input->GetTimeGeometry()->IsValidTimeStep(t)) + { + const mitk::TimeBounds &timebounds = input->GetTimeGeometry()->GetTimeBounds(t); + filename << m_FileName.c_str() << "_S" << std::setprecision(0) << timebounds[0] << "_E" + << std::setprecision(0) << timebounds[1] << "_T" << t << GetDefaultExtension(); + } + else + { + itkWarningMacro(<< "Error on write: TimeGeometry invalid of unstructured grid " << filename.str() << "."); + filename << m_FileName.c_str() << "_T" << t << GetDefaultExtension(); + } + transformPointSet->SetInputData(input->GetVtkUnstructuredGrid(t)); + transformPointSet->SetTransform(geometry->GetVtkTransform()); + transformPointSet->UpdateWholeExtent(); + unstructuredGrid = static_cast(transformPointSet->GetOutput()); + + unstructuredGridWriter->SetFileName(filename.str().c_str()); + unstructuredGridWriter->SetInputData(unstructuredGrid); + + ExecuteWrite(unstructuredGridWriter); + } + } + else + { + geometry = input->GetGeometry(); + transformPointSet->SetInputData(input->GetVtkUnstructuredGrid()); + transformPointSet->SetTransform(geometry->GetVtkTransform()); + transformPointSet->UpdateWholeExtent(); + unstructuredGrid = static_cast(transformPointSet->GetOutput()); + + unstructuredGridWriter->SetFileName(m_FileName.c_str()); + unstructuredGridWriter->SetInputData(unstructuredGrid); + + ExecuteWrite(unstructuredGridWriter); + } + transformPointSet->Delete(); + unstructuredGridWriter->Delete(); + + m_Success = true; + } + + template + void UnstructuredGridVtkWriter::ExecuteWrite(VTKWRITER *vtkWriter) + { + struct stat fileStatus; + time_t timeBefore = 0; + if (!stat(vtkWriter->GetFileName(), &fileStatus)) + { + timeBefore = fileStatus.st_mtime; + } + if (!vtkWriter->Write()) + { + itkExceptionMacro(<< "Error during unstructured grid writing."); + } + + // check if file can be written because vtkWriter doesn't check that + if (stat(vtkWriter->GetFileName(), &fileStatus) || (timeBefore == fileStatus.st_mtime)) + { + itkExceptionMacro(<< "Error during unstructured grid writing: file could not be written"); + } + } + + template + void UnstructuredGridVtkWriter::SetInput(BaseData *input) + { + this->ProcessObject::SetNthInput(0, input); + } + + template + const UnstructuredGrid *UnstructuredGridVtkWriter::GetInput() + { + if (this->GetNumberOfInputs() < 1) + { + return nullptr; + } + else + { + return dynamic_cast(this->ProcessObject::GetInput(0)); + } + } + + template + bool UnstructuredGridVtkWriter::CanWriteBaseDataType(BaseData::Pointer data) + { + return (dynamic_cast(data.GetPointer()) != nullptr); + } + + template + void UnstructuredGridVtkWriter::DoWrite(BaseData::Pointer data) + { + if (CanWriteBaseDataType(data)) + { + this->SetInput(dynamic_cast(data.GetPointer())); + this->Update(); + } + } + + template + std::vector UnstructuredGridVtkWriter::GetPossibleFileExtensions() + { + throw std::exception(); // no specialization available! + } + + template + const char *UnstructuredGridVtkWriter::GetDefaultFilename() + { + throw std::exception(); // no specialization available! + } + + template + const char *UnstructuredGridVtkWriter::GetFileDialogPattern() + { + throw std::exception(); // no specialization available! + } + + template + const char *UnstructuredGridVtkWriter::GetDefaultExtension() + { + throw std::exception(); // no specialization available! + } +} + +#endif diff --git a/Modules/IOExt/Internal/mitkUnstructuredGridVtkWriterFactory.cpp b/Modules/IOExt/Internal/mitkUnstructuredGridVtkWriterFactory.cpp new file mode 100644 index 0000000000..b38afce2c4 --- /dev/null +++ b/Modules/IOExt/Internal/mitkUnstructuredGridVtkWriterFactory.cpp @@ -0,0 +1,82 @@ +/*=================================================================== + +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 "mitkUnstructuredGridVtkWriterFactory.h" + +#include "itkCreateObjectFunction.h" +#include "itkVersion.h" + +#include "mitkUnstructuredGridVtkWriter.h" + +#include +#include +#include + +namespace mitk +{ + template + class CreateUnstructuredGridWriter : public itk::CreateObjectFunctionBase + { + public: + /** Standard class typedefs. */ + typedef CreateUnstructuredGridWriter Self; + typedef itk::SmartPointer Pointer; + + /** Methods from itk:LightObject. */ + itkFactorylessNewMacro(Self); + LightObject::Pointer CreateObject() override + { + typename T::Pointer p = T::New(); + p->Register(); + return p.GetPointer(); + } + + protected: + CreateUnstructuredGridWriter() {} + ~CreateUnstructuredGridWriter() override {} + private: + CreateUnstructuredGridWriter(const Self &); // purposely not implemented + void operator=(const Self &); // purposely not implemented + }; + + UnstructuredGridVtkWriterFactory::UnstructuredGridVtkWriterFactory() + { + this->RegisterOverride( + "IOWriter", + "UnstructuredGridVtkWriter", + "VTK Legacy Unstructured Grid Writer", + 1, + mitk::CreateUnstructuredGridWriter>::New()); + + this->RegisterOverride( + "IOWriter", + "UnstructuredGridVtkWriter", + "VTK XML UnstructuredGrid Writer", + 1, + mitk::CreateUnstructuredGridWriter>::New()); + + this->RegisterOverride( + "IOWriter", + "UnstructuredGridVtkWriter", + "VTK Parallel XML UnstructuredGrid Writer", + 1, + mitk::CreateUnstructuredGridWriter>::New()); + } + + UnstructuredGridVtkWriterFactory::~UnstructuredGridVtkWriterFactory() {} + const char *UnstructuredGridVtkWriterFactory::GetITKSourceVersion() const { return ITK_SOURCE_VERSION; } + const char *UnstructuredGridVtkWriterFactory::GetDescription() const { return "UnstructuredGridVtkWriterFactory"; } +} // end namespace mitk diff --git a/Modules/IOExt/Internal/mitkUnstructuredGridVtkWriterFactory.h b/Modules/IOExt/Internal/mitkUnstructuredGridVtkWriterFactory.h new file mode 100644 index 0000000000..08cddeb5c6 --- /dev/null +++ b/Modules/IOExt/Internal/mitkUnstructuredGridVtkWriterFactory.h @@ -0,0 +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 UNSTRUCTURED_GRID_WRITERFACTORY_H_HEADER_INCLUDED +#define UNSTRUCTURED_GRID_WRITERFACTORY_H_HEADER_INCLUDED + +#include "itkObjectFactoryBase.h" +#include "mitkBaseData.h" + +namespace mitk +{ + class UnstructuredGridVtkWriterFactory : public itk::ObjectFactoryBase + { + public: + mitkClassMacroItkParent(mitk::UnstructuredGridVtkWriterFactory, itk::ObjectFactoryBase) + + /** Class methods used to interface with the registered factories. */ + virtual const char *GetITKSourceVersion(void) const override; + virtual const char *GetDescription(void) const override; + + /** Method for class instantiation. */ + itkFactorylessNewMacro(Self); + + /** + * Register one factory of this type + * \deprecatedSince{2013_09} + */ + DEPRECATED(static void RegisterOneFactory(void)) + { + static bool IsRegistered = false; + if (!IsRegistered) + { + UnstructuredGridVtkWriterFactory::Pointer ugVtkWriterFactory = UnstructuredGridVtkWriterFactory::New(); + ObjectFactoryBase::RegisterFactory(ugVtkWriterFactory); + IsRegistered = true; + } + } + + protected: + UnstructuredGridVtkWriterFactory(); + ~UnstructuredGridVtkWriterFactory(); + + private: + UnstructuredGridVtkWriterFactory(const Self &); // purposely not implemented + void operator=(const Self &); // purposely not implemented + }; + +} // end namespace mitk + +#endif // UNSTRUCTURED_GRID_WRITERFACTORY_H_HEADER_INCLUDED diff --git a/Modules/IOExt/Internal/mitkVtkUnstructuredGridReader.cpp b/Modules/IOExt/Internal/mitkVtkUnstructuredGridReader.cpp new file mode 100644 index 0000000000..a5b3b25f92 --- /dev/null +++ b/Modules/IOExt/Internal/mitkVtkUnstructuredGridReader.cpp @@ -0,0 +1,92 @@ +/*=================================================================== + +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 "mitkVtkUnstructuredGridReader.h" +#include +#include +#include +#include + +#include + +#include +#include + +mitk::VtkUnstructuredGridReader::VtkUnstructuredGridReader() : AbstractFileReader() +{ + CustomMimeType mimeType(IOMimeTypes::DEFAULT_BASE_NAME() + ".vtu"); + mimeType.SetComment("Vtk Unstructured Grid Files"); + mimeType.SetCategory("Vtk Unstructured Grid"); + mimeType.AddExtension("vtu"); + mimeType.AddExtension("vtk"); + + this->SetDescription("Vtk Unstructured Grid Files"); + this->SetMimeType(mimeType); + + this->RegisterService(); +} + +mitk::VtkUnstructuredGridReader::~VtkUnstructuredGridReader() +{ +} + +std::vector> mitk::VtkUnstructuredGridReader::Read() +{ + MITK_INFO << "Loading " + << " as vtk unstructured grid"; + std::vector> result; + MITK_INFO << this->GetLocalFileName(); + std::string ext = itksys::SystemTools::GetFilenameLastExtension(GetLocalFileName().c_str()); + ext = itksys::SystemTools::LowerCase(ext); + if (ext == ".vtk") + { + vtkDataReader *chooser = vtkDataReader::New(); + chooser->SetFileName(GetLocalFileName().c_str()); + if (chooser->IsFileUnstructuredGrid()) + { + vtkUnstructuredGridReader *reader = vtkUnstructuredGridReader::New(); + reader->SetFileName(GetLocalFileName().c_str()); + reader->Update(); + + if (reader->GetOutput() != nullptr) + { + mitk::UnstructuredGrid::Pointer grid = mitk::UnstructuredGrid::New(); + grid->SetVtkUnstructuredGrid(reader->GetOutput()); + result.push_back(grid.GetPointer()); + } + reader->Delete(); + } + } + else if (ext == ".vtu") + { + vtkXMLUnstructuredGridReader *reader = vtkXMLUnstructuredGridReader::New(); + reader->SetFileName(GetLocalFileName().c_str()); + reader->Update(); + + if (reader->GetOutput() != nullptr) + { + mitk::UnstructuredGrid::Pointer grid = mitk::UnstructuredGrid::New(); + grid->SetVtkUnstructuredGrid(reader->GetOutput()); + result.push_back(grid.GetPointer()); + } + reader->Delete(); + } + return result; +} + +mitk::VtkUnstructuredGridReader *mitk::VtkUnstructuredGridReader::Clone() const +{ + return new mitk::VtkUnstructuredGridReader(*this); +} diff --git a/Modules/IOExt/Internal/mitkVtkUnstructuredGridReader.h b/Modules/IOExt/Internal/mitkVtkUnstructuredGridReader.h new file mode 100644 index 0000000000..3232242bec --- /dev/null +++ b/Modules/IOExt/Internal/mitkVtkUnstructuredGridReader.h @@ -0,0 +1,40 @@ +/*=================================================================== + +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 VtkUnstructuredGridReader_H_HEADER_INCLUDED +#define VtkUnstructuredGridReader_H_HEADER_INCLUDED + +#include + +namespace mitk +{ + //##Documentation + //## @brief Reader to read unstructured grid files in vtk-format + class VtkUnstructuredGridReader : public AbstractFileReader + { + public: + VtkUnstructuredGridReader(); + virtual ~VtkUnstructuredGridReader(); + + using AbstractFileReader::Read; + virtual std::vector> Read() override; + + protected: + virtual VtkUnstructuredGridReader *Clone() const override; + }; + +} // namespace mitk + +#endif /* VtkUnstructuredGridReader_H_HEADER_INCLUDED */ diff --git a/Modules/IOExt/Internal/mitkVtkVolumeTimeSeriesIOFactory.cpp b/Modules/IOExt/Internal/mitkVtkVolumeTimeSeriesIOFactory.cpp new file mode 100644 index 0000000000..0c6e40cab9 --- /dev/null +++ b/Modules/IOExt/Internal/mitkVtkVolumeTimeSeriesIOFactory.cpp @@ -0,0 +1,41 @@ +/*=================================================================== + +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 "mitkVtkVolumeTimeSeriesIOFactory.h" +#include "mitkIOAdapter.h" +#include "mitkVtkVolumeTimeSeriesReader.h" + +#include "itkVersion.h" + +namespace mitk +{ + VtkVolumeTimeSeriesIOFactory::VtkVolumeTimeSeriesIOFactory() + { + this->RegisterOverride("mitkIOAdapter", + "mitkVtkVolumeTimeSeriesReader", + "mitk Vtk Surface IO", + 1, + itk::CreateObjectFunction>::New()); + } + + VtkVolumeTimeSeriesIOFactory::~VtkVolumeTimeSeriesIOFactory() {} + const char *VtkVolumeTimeSeriesIOFactory::GetITKSourceVersion() const { return ITK_SOURCE_VERSION; } + const char *VtkVolumeTimeSeriesIOFactory::GetDescription() const + { + return "VtkVolumeTimeSeries IO Factory, allows the loading of Vtk surfaces"; + } + +} // end namespace mitk diff --git a/Modules/IOExt/Internal/mitkVtkVolumeTimeSeriesIOFactory.h b/Modules/IOExt/Internal/mitkVtkVolumeTimeSeriesIOFactory.h new file mode 100644 index 0000000000..c189c40157 --- /dev/null +++ b/Modules/IOExt/Internal/mitkVtkVolumeTimeSeriesIOFactory.h @@ -0,0 +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 __mitkVtkVolumeTimeSeriesIOFactory_h +#define __mitkVtkVolumeTimeSeriesIOFactory_h + +#ifdef _MSC_VER +#pragma warning(disable : 4786) +#endif + +#include "itkObjectFactoryBase.h" +#include "mitkBaseData.h" + +namespace mitk +{ + //##Documentation + //## @brief Create instances of VtkVolumeTimeSeriesReader objects using an object factory. + class VtkVolumeTimeSeriesIOFactory : public itk::ObjectFactoryBase + { + public: + /** Standard class typedefs. */ + typedef VtkVolumeTimeSeriesIOFactory 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 override; + virtual const char *GetDescription(void) const override; + + /** Method for class instantiation. */ + itkFactorylessNewMacro(Self); + static VtkVolumeTimeSeriesIOFactory *FactoryNew() { return new VtkVolumeTimeSeriesIOFactory; } + /** Run-time type information (and related methods). */ + itkTypeMacro(VtkVolumeTimeSeriesIOFactory, ObjectFactoryBase); + + /** + * Register one factory of this type + * \deprecatedSince{2013_09} + */ + DEPRECATED(static void RegisterOneFactory(void)) + { + VtkVolumeTimeSeriesIOFactory::Pointer VtkVolumeTimeSeriesIOFactory = VtkVolumeTimeSeriesIOFactory::New(); + ObjectFactoryBase::RegisterFactory(VtkVolumeTimeSeriesIOFactory); + } + + protected: + VtkVolumeTimeSeriesIOFactory(); + ~VtkVolumeTimeSeriesIOFactory(); + + private: + VtkVolumeTimeSeriesIOFactory(const Self &); // purposely not implemented + void operator=(const Self &); // purposely not implemented + }; + +} // end namespace mitk + +#endif diff --git a/Modules/IOExt/Internal/mitkVtkVolumeTimeSeriesReader.cpp b/Modules/IOExt/Internal/mitkVtkVolumeTimeSeriesReader.cpp new file mode 100644 index 0000000000..072ba9dac7 --- /dev/null +++ b/Modules/IOExt/Internal/mitkVtkVolumeTimeSeriesReader.cpp @@ -0,0 +1,83 @@ +/*=================================================================== + +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 "mitkVtkVolumeTimeSeriesReader.h" +#include "mitkSurface.h" +#include "mitkVtkSurfaceReader.h" +#include "vtkPolyData.h" + +void mitk::VtkVolumeTimeSeriesReader::GenerateData() +{ + if (!this->GenerateFileList()) + { + itkWarningMacro(<< "Sorry, file list could not be determined..."); + return; + } + + mitk::Surface::Pointer output = this->GetOutput(); + MITK_INFO << "prefix: " << m_FilePrefix << ", pattern: " << m_FilePattern << std::endl; + output->Expand(m_MatchedFileNames.size()); + for (unsigned int i = 0; i < m_MatchedFileNames.size(); ++i) + { + std::string fileName = m_MatchedFileNames[i]; + MITK_INFO << "Loading " << fileName << " as vtk..." << std::endl; + + VtkSurfaceReader::Pointer vtkReader = VtkSurfaceReader::New(); + vtkReader->SetFileName(fileName.c_str()); + vtkReader->Update(); + + if (vtkReader->GetOutput() != nullptr) + { + output->SetVtkPolyData(vtkReader->GetOutput()->GetVtkPolyData(), i); + } + else + { + itkWarningMacro(<< "vtkPolyDataReader returned nullptr while reading " << fileName + << ". Trying to continue with empty vtkPolyData..."); + output->SetVtkPolyData(vtkPolyData::New(), i); + } + } +} + +bool mitk::VtkVolumeTimeSeriesReader::CanReadFile(const std::string /*filename*/, + const std::string filePrefix, + const std::string filePattern) +{ + if (filePattern != "" && filePrefix != "") + return false; + + bool extensionFound = false; + std::string::size_type VTKPos = filePattern.rfind(".vtk"); + if ((VTKPos != std::string::npos) && (VTKPos == filePattern.length() - 4)) + extensionFound = true; + + VTKPos = filePattern.rfind(".VTK"); + if ((VTKPos != std::string::npos) && (VTKPos == filePattern.length() - 4)) + extensionFound = true; + + if (!extensionFound) + return false; + + return true; +} + +mitk::VtkVolumeTimeSeriesReader::VtkVolumeTimeSeriesReader() +{ +} + +mitk::VtkVolumeTimeSeriesReader::~VtkVolumeTimeSeriesReader() +{ +} diff --git a/Modules/IOExt/Internal/mitkVtkVolumeTimeSeriesReader.h b/Modules/IOExt/Internal/mitkVtkVolumeTimeSeriesReader.h new file mode 100644 index 0000000000..95788a9d5c --- /dev/null +++ b/Modules/IOExt/Internal/mitkVtkVolumeTimeSeriesReader.h @@ -0,0 +1,61 @@ +/*=================================================================== + +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 _Vtk_VOLUME_TIME_SERIES_READER__H_ +#define _Vtk_VOLUME_TIME_SERIES_READER__H_ + +#include "mitkCommon.h" +#include "mitkFileSeriesReader.h" +#include "mitkSurfaceSource.h" + +namespace mitk +{ + //##Documentation + //## @brief Reader to read a series of volume files in Vtk-format + class VtkVolumeTimeSeriesReader : public SurfaceSource, public FileSeriesReader + { + public: + mitkClassMacro(VtkVolumeTimeSeriesReader, FileReader); + + /** Method for creation through the object factory. */ + itkFactorylessNewMacro(Self) itkCloneMacro(Self) + + itkSetStringMacro(FileName); + itkGetStringMacro(FileName); + + itkSetStringMacro(FilePrefix); + itkGetStringMacro(FilePrefix); + + itkSetStringMacro(FilePattern); + itkGetStringMacro(FilePattern); + + static bool CanReadFile(const std::string filename, const std::string filePrefix, const std::string filePattern); + + protected: + virtual void GenerateData() override; + + VtkVolumeTimeSeriesReader(); + + ~VtkVolumeTimeSeriesReader(); + + //##Description + //## @brief Time when Header was last read + itk::TimeStamp m_ReadHeaderTime; + }; + +} // namespace mitk + +#endif diff --git a/Modules/IOExt/files.cmake b/Modules/IOExt/files.cmake new file mode 100644 index 0000000000..da4362ee9e --- /dev/null +++ b/Modules/IOExt/files.cmake @@ -0,0 +1,17 @@ +set(CPP_FILES + Internal/mitkIOExtActivator.cpp + Internal/mitkIOExtObjectFactory.cpp + Internal/mitkObjFileReaderService.cpp + Internal/mitkPlyFileWriterService.cpp + Internal/mitkPlyFileReaderService.cpp + Internal/mitkParRecFileIOFactory.cpp + Internal/mitkParRecFileReader.cpp + Internal/mitkSceneFileReader.cpp + Internal/mitkStlVolumeTimeSeriesIOFactory.cpp + Internal/mitkStlVolumeTimeSeriesReader.cpp + Internal/mitkUnstructuredGridVtkWriter.cpp + Internal/mitkUnstructuredGridVtkWriterFactory.cpp + Internal/mitkVtkUnstructuredGridReader.cpp + Internal/mitkVtkVolumeTimeSeriesIOFactory.cpp + Internal/mitkVtkVolumeTimeSeriesReader.cpp +) diff --git a/Modules/LegacyIO/CMakeLists.txt b/Modules/LegacyIO/CMakeLists.txt new file mode 100644 index 0000000000..d9debfbd64 --- /dev/null +++ b/Modules/LegacyIO/CMakeLists.txt @@ -0,0 +1,8 @@ +mitkFunctionCheckCompilerFlags("/wd4996" CMAKE_CXX_FLAGS) +mitkFunctionCheckCompilerFlags("-Wno-deprecated-declarations" CMAKE_CXX_FLAGS) + +MITK_CREATE_MODULE( + DEPENDS MitkCore + PACKAGE_DEPENDS PRIVATE ITK|ITKIOGDCM+ITKIORAW tinyxml + DEPRECATED_SINCE 2014.10 +) diff --git a/Modules/LegacyIO/Documentation/Doxygen/Modules.dox b/Modules/LegacyIO/Documentation/Doxygen/Modules.dox new file mode 100644 index 0000000000..3aac4026eb --- /dev/null +++ b/Modules/LegacyIO/Documentation/Doxygen/Modules.dox @@ -0,0 +1,11 @@ +/** + \defgroup MitkLegacyIOModule LegacyIO + \ingroup MITKModules + + \brief Legay reader and writer extensions for MITK + + This module provides the legacy reader and writer implementations for + core data types. + + \deprecatedSince{2014_10} Use mitk::IOUtil instead. +*/ diff --git a/Modules/LegacyIO/Testing/files.cmake b/Modules/LegacyIO/Testing/files.cmake new file mode 100644 index 0000000000..0e81f8005f --- /dev/null +++ b/Modules/LegacyIO/Testing/files.cmake @@ -0,0 +1,8 @@ +# test with image filename as an extra command line parameter +set(MODULE_IMAGE_TESTS + mitkDataNodeFactoryTest.cpp #runs on all types of data +) + +set(MODULE_SURFACE_TESTS + mitkDataNodeFactoryTest.cpp #runs on all types of data +) diff --git a/Modules/LegacyIO/Testing/mitkDataNodeFactoryTest.cpp b/Modules/LegacyIO/Testing/mitkDataNodeFactoryTest.cpp new file mode 100644 index 0000000000..f5c2e1219c --- /dev/null +++ b/Modules/LegacyIO/Testing/mitkDataNodeFactoryTest.cpp @@ -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. + +===================================================================*/ + +#include "mitkDataNodeFactory.h" +#include "mitkTestingMacros.h" + +#include "mitkProperties.h" + +#include +#include +/** + * Test for the class "DataNodeFactory". + * + * argc and argv are the command line parameters which were passed to + * the ADD_TEST command in the CMakeLists.txt file. For the automatic + * tests, argv is either empty for the simple tests or contains the filename + * of a test image for the image tests (see CMakeLists.txt). + */ +int mitkDataNodeFactoryTest(int, char *argv[]) +{ + // always start with this! + MITK_TEST_BEGIN("DataNodeFactory") + + mitk::DataNodeFactory::Pointer factory = mitk::DataNodeFactory::New(); + MITK_TEST_OUTPUT(<< "Loading file: " << argv[1]); + + factory->SetFileName(argv[1]); + MITK_TEST_CONDITION_REQUIRED(strcmp(factory->GetFileName(), argv[1]) == 0, "Test for Set/GetFileName()"); + + factory->Update(); + MITK_TEST_CONDITION_REQUIRED(factory->GetNumberOfOutputs() > 0, "file loaded"); + + MITK_TEST_OUTPUT(<< "Test function SetDefaultCommonProperties()"); + mitk::DataNode::Pointer node = factory->GetOutput(0); + + MITK_TEST_CONDITION_REQUIRED(node.IsNotNull(), "DataNodeFactory has returned a non-empty node.") + + factory->SetDefaultCommonProperties(node); + // get file path and property + std::string filePath = itksys::SystemTools::GetFilenamePath(factory->GetFileName()); + mitk::StringProperty::Pointer pathProp = + dynamic_cast(node->GetProperty(mitk::StringProperty::PATH)); + + MITK_TEST_CONDITION_REQUIRED(strcmp(pathProp->GetValue(), filePath.c_str()) == 0, "Test for file path"); + + std::string fileName = factory->GetFileName(); + std::string fileExtension = itksys::SystemTools::GetFilenameExtension(fileName); + if (fileName.substr(fileName.size() - 3) == ".gz") + fileName = fileName.substr(0, fileName.length() - 3); + fileName = fileName.substr(0, fileName.length() - fileExtension.length()); + fileName = fileName.substr(filePath.length() + 1, fileName.length()); + mitk::StringProperty::Pointer nameProp = dynamic_cast(node->GetProperty("name")); + MITK_TEST_CONDITION_REQUIRED(strcmp(nameProp->GetValue(), fileName.c_str()) == 0, "Test for file name"); + + mitk::BoolProperty::Pointer visibleProp = dynamic_cast(node->GetProperty("visible")); + MITK_TEST_CONDITION_REQUIRED(visibleProp->GetValue() == true, "Test for visibility"); + // always end with this! + MITK_TEST_END() +} diff --git a/Modules/LegacyIO/files.cmake b/Modules/LegacyIO/files.cmake new file mode 100644 index 0000000000..5790303f08 --- /dev/null +++ b/Modules/LegacyIO/files.cmake @@ -0,0 +1,30 @@ +set(H_FILES + +) + +set(CPP_FILES + mitkBaseDataIOFactory.cpp + mitkDataNodeFactory.cpp + mitkFileSeriesReader.cpp + mitkImageWriter.cpp + mitkImageWriterFactory.cpp + mitkItkImageFileIOFactory.cpp + mitkItkImageFileReader.cpp + mitkItkPictureWrite.cpp + mitkPointSetIOFactory.cpp + mitkPointSetReader.cpp + mitkPointSetWriter.cpp + mitkPointSetWriterFactory.cpp + mitkRawImageFileReader.cpp + mitkSTLFileIOFactory.cpp + mitkSTLFileReader.cpp + mitkSurfaceVtkWriter.cpp + mitkSurfaceVtkWriterFactory.cpp + mitkVtiFileIOFactory.cpp + mitkVtiFileReader.cpp + mitkVtkImageIOFactory.cpp + mitkVtkImageReader.cpp + mitkVtkSurfaceIOFactory.cpp + mitkVtkSurfaceReader.cpp + vtkPointSetXMLParser.cpp +) diff --git a/Modules/LegacyIO/mitkBaseDataIOFactory.cpp b/Modules/LegacyIO/mitkBaseDataIOFactory.cpp new file mode 100644 index 0000000000..dedc56ba11 --- /dev/null +++ b/Modules/LegacyIO/mitkBaseDataIOFactory.cpp @@ -0,0 +1,35 @@ +/*=================================================================== + +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. + +===================================================================*/ + +#ifdef _MSC_VER +#pragma warning(disable : 4786) +#endif + +#include "mitkBaseDataIOFactory.h" + +#include "mitkIOUtil.h" + +namespace mitk +{ + std::vector BaseDataIO::LoadBaseDataFromFile(const std::string path, + const std::string /*filePrefix*/, + const std::string /*filePattern*/, + bool /*series*/) + { + return IOUtil::Load(path); + } + +} // end namespace itk diff --git a/Modules/LegacyIO/mitkBaseDataIOFactory.h b/Modules/LegacyIO/mitkBaseDataIOFactory.h new file mode 100644 index 0000000000..851ebe5519 --- /dev/null +++ b/Modules/LegacyIO/mitkBaseDataIOFactory.h @@ -0,0 +1,65 @@ +/*=================================================================== + +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 __mitkBaseDataIO_h +#define __mitkBaseDataIO_h + +#include + +#include "mitkBaseData.h" + +#include "itkObject.h" + +namespace mitk +{ + /** + * @brief BaseDataIO creates instances of BaseData objects using an object factory. + * + * @ingroup MitkLegacyIOModule + * @deprecatedSince{2014_10} Use mitk::IOUtils or mitk::FileReaderRegistry instead. + */ + class DEPRECATED() MITKLEGACYIO_EXPORT BaseDataIO : public itk::Object + { + public: + /** Standard class typedefs. */ + typedef BaseDataIO Self; + typedef itk::Object Superclass; + typedef itk::SmartPointer Pointer; + typedef itk::SmartPointer ConstPointer; + + /** Class Methods used to interface with the registered factories */ + + /** Run-time type information (and related methods). */ + itkTypeMacro(BaseDataIO, Object); + + /** Create the appropriate BaseData depending on the particulars of the file. */ + static std::vector LoadBaseDataFromFile(const std::string path, + const std::string filePrefix, + const std::string filePattern, + bool series); + + protected: + BaseDataIO(); + ~BaseDataIO(); + + private: + BaseDataIO(const Self &); // purposely not implemented + void operator=(const Self &); // purposely not implemented + }; + +} // end namespace mitk + +#endif diff --git a/Modules/LegacyIO/mitkDataNodeFactory.cpp b/Modules/LegacyIO/mitkDataNodeFactory.cpp new file mode 100644 index 0000000000..31c213483c --- /dev/null +++ b/Modules/LegacyIO/mitkDataNodeFactory.cpp @@ -0,0 +1,496 @@ +/*=================================================================== + +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 + +// C-Standard library includes +#include +#include + +// STL-related includes +#include +#include +#include +#include +#include + +// VTK-related includes +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include + +// ITK-related includes + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef NOMINMAX +#define DEF_NOMINMAX +#undef NOMINMAX +#endif + +#include + +#ifdef DEF_NOMINMAX +#ifndef NOMINMAX +#define NOMINMAX +#endif +#undef DEF_NOMINMAX +#endif + +#include +#include + +// MITK-related includes +#include "mitkPointSet.h" +#include "mitkProperties.h" +#include "mitkStringProperty.h" +#include "mitkSurface.h" +//#include "mitkMaterialProperty.h" +#include "mitkCoreObjectFactory.h" +#include "mitkImage.h" +#include "mitkImageChannelSelector.h" +#include "mitkImageSliceSelector.h" +#include "mitkLevelWindowProperty.h" +#include "mitkLookupTable.h" +#include "mitkLookupTableProperty.h" +#include "mitkProgressBar.h" +#include "mitkPropertyNameHelper.h" +#include "mitkTransferFunctionProperty.h" +#include "mitkVtkInterpolationProperty.h" +#include "mitkVtkRepresentationProperty.h" +#include "mitkVtkResliceInterpolationProperty.h" +#include "mitkVtkScalarModeProperty.h" +#include + +bool mitk::DataNodeFactory::m_TextureInterpolationActive = + false; // default value for texture interpolation if nothing is defined in global options (see QmitkMainTemplate.ui.h) + +mitk::DataNodeFactory::DataNodeFactory() +{ + m_Serie = false; + m_OldProgress = 0; + this->Modified(); + // ensure that a CoreObjectFactory has been instantiated + mitk::CoreObjectFactory::GetInstance(); +} + +mitk::DataNodeFactory::~DataNodeFactory() +{ +} + +void mitk::DataNodeFactory::SetImageSerie(bool serie) +{ + m_Serie = serie; +} + +void mitk::DataNodeFactory::GenerateData() +{ + // IF filename is something.pic, and something.pic does not exist, try to read something.pic.gz + // if there are both, something.pic and something.pic.gz, only the requested file is read + // not only for images, but for all formats + std::ifstream exists(m_FileName.c_str()); + if (!exists) + { + std::string testfilename = m_FileName + ".gz"; + + std::ifstream exists(testfilename.c_str()); + if (exists.good()) + { + m_FileName += ".gz"; + } + else + { + testfilename = m_FileName + ".GZ"; + std::ifstream exists(testfilename.c_str()); + if (exists.good()) + { + m_FileName += ".GZ"; + } + else + { + std::string message("File does not exist, or cannot be read. Filename = "); + message += m_FileName; + MITK_ERROR << message; + itkExceptionMacro(<< message.str()); + } + } + } + + // part for DICOM + // const char *numbers = "0123456789."; + // std::string::size_type first_non_number; + // first_non_number = itksys::SystemTools::GetFilenameName(m_FileName).find_first_not_of ( numbers ); + + if (DicomSeriesReader::IsDicom(this->m_FileName) /*|| first_non_number == std::string::npos*/) + { + this->ReadFileSeriesTypeDCM(); + } + else + { + bool usedNewDTNF = false; + + // the mitkBaseDataIO class returns a pointer of a vector of BaseData objects + std::vector baseDataVector = + mitk::BaseDataIO::LoadBaseDataFromFile(m_FileName, m_FilePrefix, m_FilePattern, m_Serie); + + if (!baseDataVector.empty()) + this->ResizeOutputs((unsigned int)baseDataVector.size()); + + for (int i = 0; i < (int)baseDataVector.size(); i++) + { + mitk::BaseData::Pointer baseData = baseDataVector.at(i); + + if (baseData.IsNotNull()) + { + usedNewDTNF = true; + mitk::DataNode::Pointer node = mitk::DataNode::New(); + node->SetData(baseData); + this->SetDefaultCommonProperties(node); + + this->SetOutput(this->MakeNameFromOutputIndex(i), node); + } + } + if (!usedNewDTNF && (m_FileName != "") && !(m_Serie == false)) + ReadFileSeriesTypeITKImageSeriesReader(); + } +} + +void mitk::DataNodeFactory::ResizeOutputs(const unsigned int &num) +{ + unsigned int prevNum = this->GetNumberOfOutputs(); + this->SetNumberOfIndexedOutputs(num); + for (unsigned int i = prevNum; i < num; ++i) + { + this->SetNthOutput(i, this->MakeOutput(i).GetPointer()); + } +} + +bool mitk::DataNodeFactory::FileNameEndsWith(const std::string &name) +{ + if (m_FileName.size() < name.size()) + return false; + + return m_FileName.substr(m_FileName.size() - name.size()) == name; +} + +bool mitk::DataNodeFactory::FilePatternEndsWith(const std::string &name) +{ + return m_FilePattern.find(name) != std::string::npos; +} + +std::string mitk::DataNodeFactory::GetBaseFileName() +{ + return itksys::SystemTools::GetFilenameName(m_FileName); +} + +std::string mitk::DataNodeFactory::GetBaseFilePrefix() +{ + return itksys::SystemTools::GetFilenameName(m_FilePrefix); +} + +std::string mitk::DataNodeFactory::GetDirectory() +{ + if (!m_FileName.empty()) + return itksys::SystemTools::GetFilenamePath(m_FileName); + if (!m_FilePrefix.empty()) + return itksys::SystemTools::GetFilenamePath(m_FilePrefix); + + return std::string(); +} + +void mitk::DataNodeFactory::ReadFileSeriesTypeDCM() +{ + mitk::LocaleSwitch localeSwitch("C"); + std::locale previousCppLocale(std::cin.getloc()); + std::locale l("C"); + std::cin.imbue(l); + + if (DicomSeriesReader::IsPhilips3DDicom(this->GetFileName())) + { + MITK_INFO << "it is a Philips3D US Dicom file" << std::endl; + this->ResizeOutputs(1); + DataNode::Pointer node = this->GetOutput(); + mitk::DicomSeriesReader::StringContainer stringvec; + stringvec.push_back(this->GetFileName()); + if (DicomSeriesReader::LoadDicomSeries(stringvec, *node)) + { + node->SetName(this->GetBaseFileName()); + } + std::cin.imbue(previousCppLocale); + return; + } + + DicomSeriesReader::FileNamesGrouping imageBlocks = DicomSeriesReader::GetSeries( + this->GetDirectory(), true, this->m_SeriesRestrictions); // true = group gantry tilt images + const unsigned int size = imageBlocks.size(); + + this->ResizeOutputs(size); + ProgressBar::GetInstance()->AddStepsToDo(size); + ProgressBar::GetInstance()->Progress(); + + unsigned int outputIndex = 0u; + const DicomSeriesReader::FileNamesGrouping::const_iterator n_end = imageBlocks.end(); + + for (DicomSeriesReader::FileNamesGrouping::const_iterator n_it = imageBlocks.begin(); n_it != n_end; ++n_it) + { + const std::string &uid = n_it->first; + DataNode::Pointer node = this->GetOutput(outputIndex); + + const DicomSeriesReader::ImageBlockDescriptor &imageBlockDescriptor(n_it->second); + + MITK_INFO << "--------------------------------------------------------------------------------"; + MITK_INFO << "DataNodeFactory: Loading DICOM series " << outputIndex << ": Series UID " + << imageBlockDescriptor.GetSeriesInstanceUID() << std::endl; + MITK_INFO << " " << imageBlockDescriptor.GetFilenames().size() << " '" << imageBlockDescriptor.GetModality() + << "' files (" << imageBlockDescriptor.GetSOPClassUIDAsString() << ") loaded into 1 mitk::Image"; + MITK_INFO << " multi-frame: " << (imageBlockDescriptor.IsMultiFrameImage() ? "Yes" : "No"); + MITK_INFO << " reader support: " << DicomSeriesReader::ReaderImplementationLevelToString( + imageBlockDescriptor.GetReaderImplementationLevel()); + MITK_INFO << " pixel spacing type: " + << DicomSeriesReader::PixelSpacingInterpretationToString(imageBlockDescriptor.GetPixelSpacingType()); + MITK_INFO << " gantry tilt corrected: " << (imageBlockDescriptor.HasGantryTiltCorrected() ? "Yes" : "No"); + MITK_INFO << " 3D+t: " << (imageBlockDescriptor.HasMultipleTimePoints() ? "Yes" : "No"); + MITK_INFO << "--------------------------------------------------------------------------------"; + + if (DicomSeriesReader::LoadDicomSeries(n_it->second.GetFilenames(), *node, true, true, true)) + { + std::string nodeName(uid); + std::string studyDescription; + + if (GetBackwardsCompatibleDICOMProperty( + 0x0008, 0x1030, "dicom.study.StudyDescription", node->GetPropertyList(), studyDescription)) + { + nodeName = studyDescription; + std::string seriesDescription; + + if (GetBackwardsCompatibleDICOMProperty( + 0x0008, 0x103e, "dicom.study.SeriesDescription", node->GetPropertyList(), seriesDescription)) + { + nodeName += "/" + seriesDescription; + } + } + + node->SetName(nodeName); + + ++outputIndex; + } + else + { + MITK_ERROR << "DataNodeFactory: Skipping series " << outputIndex << " due to some unspecified error..." + << std::endl; + } + + ProgressBar::GetInstance()->Progress(); + } + + std::cin.imbue(previousCppLocale); +} + +void mitk::DataNodeFactory::ReadFileSeriesTypeITKImageSeriesReader() +{ + typedef itk::Image ImageType; + typedef itk::ImageSeriesReader ReaderType; + + if (!this->GenerateFileList()) + { + itkWarningMacro("Sorry, file list could not be generated!"); + return; + } + if (m_MatchedFileNames.size() == 0) + { + itkWarningMacro("Sorry, no files matched the given filename (" << m_FileName << ")!"); + return; + } + + // + // Finally, initialize the ITK-reader and load the files! + // + ReaderType::Pointer reader = ReaderType::New(); + reader->SetFileNames(m_MatchedFileNames); + try + { + reader->Update(); + ResizeOutputs(reader->GetNumberOfOutputs()); + for (unsigned int i = 0; i < reader->GetNumberOfOutputs(); ++i) + { + // Initialize mitk image from itk + mitk::Image::Pointer image = mitk::Image::New(); + image->InitializeByItk(reader->GetOutput(i)); + image->SetVolume(reader->GetOutput(i)->GetBufferPointer()); + + // add the mitk image to the node + mitk::DataNode::Pointer node = this->GetOutput(i); + node->SetData(image); + + mitk::StringProperty::Pointer nameProp = mitk::StringProperty::New(m_FileName); + node->SetProperty("name", nameProp); + } + } + catch (const std::exception &e) + { + itkWarningMacro(<< e.what()); + return; + } +} + +mitk::ColorProperty::Pointer mitk::DataNodeFactory::DefaultColorForOrgan(const std::string &organ) +{ + static bool initialized = false; + static std::map s_ColorMap; + + if (!initialized) + { + // all lowercase here, please! + + s_ColorMap.insert(std::make_pair("ankle", "0xe38686")); + s_ColorMap.insert(std::make_pair("appendix", "0xe38686")); + s_ColorMap.insert(std::make_pair("blood vessels", "0xff3131")); + s_ColorMap.insert(std::make_pair("bronchial tree", "0x3168ff")); + s_ColorMap.insert(std::make_pair("bone", "0xd5d5d5")); + s_ColorMap.insert(std::make_pair("brain", "0xff9cca")); + s_ColorMap.insert(std::make_pair("coccyx", "0xe38686")); + s_ColorMap.insert(std::make_pair("colon", "0xe38686")); + s_ColorMap.insert(std::make_pair("cyst", "0xe38686")); + s_ColorMap.insert(std::make_pair("elbow", "0xe38686")); + s_ColorMap.insert(std::make_pair("eye", "0xe38686")); + s_ColorMap.insert(std::make_pair("fallopian tube", "0xe38686")); + s_ColorMap.insert(std::make_pair("fat", "0xff2bee")); + s_ColorMap.insert(std::make_pair("hand", "0xe38686")); + s_ColorMap.insert(std::make_pair("gall bladder", "0x567f18")); + s_ColorMap.insert(std::make_pair("heart", "0xeb1d32")); + s_ColorMap.insert(std::make_pair("hip", "0xe38686")); + s_ColorMap.insert(std::make_pair("kidney", "0xd33f00")); + s_ColorMap.insert(std::make_pair("knee", "0xe38686")); + s_ColorMap.insert(std::make_pair("larynx", "0xe38686")); + s_ColorMap.insert(std::make_pair("liver", "0xffcc3d")); + s_ColorMap.insert(std::make_pair("lung", "0x6bdcff")); + s_ColorMap.insert(std::make_pair("lymph node", "0xff0000")); + s_ColorMap.insert(std::make_pair("muscle", "0xff456a")); + s_ColorMap.insert(std::make_pair("nerve", "0xffea4f")); + s_ColorMap.insert(std::make_pair("nose", "0xe38686")); + s_ColorMap.insert(std::make_pair("oesophagus", "0xe38686")); + s_ColorMap.insert(std::make_pair("ovaries", "0xe38686")); + s_ColorMap.insert(std::make_pair("pancreas", "0xf9ab3d")); + s_ColorMap.insert(std::make_pair("pelvis", "0xe38686")); + s_ColorMap.insert(std::make_pair("penis", "0xe38686")); + s_ColorMap.insert(std::make_pair("pharynx", "0xe38686")); + s_ColorMap.insert(std::make_pair("prostate", "0xe38686")); + s_ColorMap.insert(std::make_pair("rectum", "0xe38686")); + s_ColorMap.insert(std::make_pair("sacrum", "0xe38686")); + s_ColorMap.insert(std::make_pair("seminal vesicle", "0xe38686")); + s_ColorMap.insert(std::make_pair("shoulder", "0xe38686")); + s_ColorMap.insert(std::make_pair("spinal cord", "0xf5f93d")); + s_ColorMap.insert(std::make_pair("spleen", "0xf96c3d")); + s_ColorMap.insert(std::make_pair("stomach", "0xf96c3d")); + s_ColorMap.insert(std::make_pair("teeth", "0xfffcd8")); + s_ColorMap.insert(std::make_pair("testicles", "0xe38686")); + s_ColorMap.insert(std::make_pair("thyroid", "0xfff694")); + s_ColorMap.insert(std::make_pair("tongue", "0xe38686")); + s_ColorMap.insert(std::make_pair("tumor", "0x937011")); + s_ColorMap.insert(std::make_pair("urethra", "0xf8ff32")); + s_ColorMap.insert(std::make_pair("urinary bladder", "0xf8ff32")); + s_ColorMap.insert(std::make_pair("uterus", "0xe38686")); + s_ColorMap.insert(std::make_pair("vagina", "0xe38686")); + s_ColorMap.insert(std::make_pair("vertebra", "0xe38686")); + s_ColorMap.insert(std::make_pair("wrist", "0xe38686")); + initialized = true; + } + + std::string lowercaseOrgan(organ); + for (unsigned int i = 0; i < organ.length(); i++) + { + lowercaseOrgan[i] = tolower(lowercaseOrgan[i]); + } + + std::map::iterator iter = s_ColorMap.find(lowercaseOrgan); + if (iter != s_ColorMap.end()) + { + std::string hexColor = iter->second; + std::string hexRed = std::string("0x") + hexColor.substr(2, 2); + std::string hexGreen = std::string("0x") + hexColor.substr(4, 2); + std::string hexBlue = std::string("0x") + hexColor.substr(6, 2); + + long int red = strtol(hexRed.c_str(), nullptr, 16); + long int green = strtol(hexGreen.c_str(), nullptr, 16); + long int blue = strtol(hexBlue.c_str(), nullptr, 16); + + return ColorProperty::New((float)red / 255.0, (float)green / 255.0, (float)blue / 255.0); + } + else + { + // a default color (green) + return ColorProperty::New(0.0, 1.0, 0.0); + } +} + +void mitk::DataNodeFactory::SetDefaultCommonProperties(mitk::DataNode::Pointer &node) +{ + // path + mitk::StringProperty::Pointer pathProp = mitk::StringProperty::New(itksys::SystemTools::GetFilenamePath(m_FileName)); + node->SetProperty(StringProperty::PATH, pathProp); + + // name already defined? + mitk::StringProperty::Pointer nameProp = dynamic_cast(node->GetProperty("name")); + if (nameProp.IsNull() || (strcmp(nameProp->GetValue(), "No Name!") == 0)) + { + // name already defined in BaseData + mitk::StringProperty::Pointer baseDataNameProp = + dynamic_cast(node->GetData()->GetProperty("name").GetPointer()); + if (baseDataNameProp.IsNull() || (strcmp(baseDataNameProp->GetValue(), "No Name!") == 0)) + { + // name neither defined in node, nor in BaseData -> name = filename + if (FileNameEndsWith(".gz")) + m_FileName = m_FileName.substr(0, m_FileName.length() - 3); + + nameProp = mitk::StringProperty::New(itksys::SystemTools::GetFilenameWithoutLastExtension(m_FileName)); + + node->SetProperty("name", nameProp); + } + else + { + // name defined in BaseData! + nameProp = mitk::StringProperty::New(baseDataNameProp->GetValue()); + node->SetProperty("name", nameProp); + } + } + + // visibility + if (!node->GetProperty("visible")) + node->SetVisibility(true); +} diff --git a/Modules/LegacyIO/mitkDataNodeFactory.h b/Modules/LegacyIO/mitkDataNodeFactory.h new file mode 100644 index 0000000000..e926086b27 --- /dev/null +++ b/Modules/LegacyIO/mitkDataNodeFactory.h @@ -0,0 +1,175 @@ +/*=================================================================== + +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 _DATA_TREE_NODE_FACTORY_H_ +#define _DATA_TREE_NODE_FACTORY_H_ + +#include "mitkColorProperty.h" +#include "mitkDataNodeSource.h" +#include "mitkFileSeriesReader.h" + +#include +#include + +namespace mitk +{ + /** + * @brief Factory, which creates instances of mitk::DataNodes filled with + * data read from a given file + * + * This class reads files, creates an appropriate mitk::BaseData and adds the + * BaseData to a mitk::DataNode. This filter may produce one or more outputs + * (i.e. mitk::DataNodes). The number of generated nodes can be retrieved by a + * call of GetNumberOfOutputs(). + * + * If you want to add a new file type, you have to register the factory + * of the file reader in the class mitk::BaseDataIOFactory. + * @ingroup MitkLegacyIOModule + * @deprecatedSince{2014_10} Use mitk::IOUtils or mitk::FileReaderRegistry instead. + */ + class MITKLEGACYIO_EXPORT DataNodeFactory : public DataNodeSource, public FileSeriesReader + { + public: + mitkClassMacro(DataNodeFactory, DataNodeSource); + + DEPRECATED(itkFactorylessNewMacro(Self)) + itkCloneMacro(Self) + + /** + * Sets the filename of the file to read. + * @param FileName the name of the file to read. + */ + itkSetStringMacro(FileName); + + /** + * @returns the name of the file to be read from disk. + */ + itkGetStringMacro(FileName); + + /** + * \brief Set prefix for multiple load + */ + itkSetStringMacro(FilePrefix); + + /** + * \brief Get prefix for multiple load + */ + itkGetStringMacro(FilePrefix); + + /** + * \brief Set pattern for multiple load + */ + itkSetStringMacro(FilePattern); + + /** + * \brief Get pattern for multiple load + */ + itkGetStringMacro(FilePattern); + + /** + * Nice default colors for segmentations of some "normal" organs. + */ + static ColorProperty::Pointer DefaultColorForOrgan(const std::string &); + + void SetDefaultCommonProperties(mitk::DataNode::Pointer &node); + + /** + * if true -> loaded image is part of a serie + */ + void SetImageSerie(bool serie); + + void AddSeriesRestriction(const std::string &tag) { m_SeriesRestrictions.push_back(tag); } + static bool m_TextureInterpolationActive; + + protected: + /** + * Constructor. + */ + DataNodeFactory(); + + /** + * Virtual destructor. + */ + virtual ~DataNodeFactory(); + + bool m_Serie; + + /** + * Determines of which file type a given file is and calls the + * appropriate reader function. + */ + virtual void GenerateData() override; + + /** + * Resizes the number of outputs of the factory. + * The outputs are initialized by empty DataNodes + * @param num the new number of outputs + */ + virtual void ResizeOutputs(const unsigned int &num); + + /** + * Checks if the file name m_FileName ends with the given name. + * Currently, this check is done by a dumb search for name in + * the filename. + * @param name the extension of the file + * @returns true, if the filename contains name. + */ + virtual bool FileNameEndsWith(const std::string &name); + + /** + * Checks if the file pattern m_FilePattern ends with the given name. + * Currently, this check is done by a dumb search for name in + * the filename. + * @param name the extension of the file + * @returns true, if the filepattern contains name. + */ + virtual bool FilePatternEndsWith(const std::string &name); + + /** + * @returns the plain filename, that is, without any directory. + */ + virtual std::string GetBaseFileName(); + + /** + * @returns the plain file prefix, that is, without any directory. + */ + virtual std::string GetBaseFilePrefix(); + + /** + * @returns the directory of the file name m_FileName. + */ + virtual std::string GetDirectory(); + +#ifdef MBI_INTERNAL + virtual void ReadFileTypeHPSONOS(); +#ifdef HAVE_IPDICOM + virtual void ReadFileTypeIPDCM(); +#endif /* HAVE_IPDICOM */ +#ifdef USE_TUS_READER + virtual void ReadFileTypeTUS(); +#endif +#endif /* MBI_INTERNAL */ + + virtual void ReadFileSeriesTypeDCM(); + + virtual void ReadFileSeriesTypeITKImageSeriesReader(); + + std::vector m_SeriesRestrictions; + int m_OldProgress; + }; +} + +#endif //#ifndef __DATA_TREE_NODE_FACTORY_H diff --git a/Modules/LegacyIO/mitkFileSeriesReader.cpp b/Modules/LegacyIO/mitkFileSeriesReader.cpp new file mode 100644 index 0000000000..ddac355575 --- /dev/null +++ b/Modules/LegacyIO/mitkFileSeriesReader.cpp @@ -0,0 +1,258 @@ +/*=================================================================== + +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 "mitkFileSeriesReader.h" +#include +#include +#include +#include + +bool mitk::FileSeriesReader::GenerateFileList() +{ + typedef std::vector StringContainer; + typedef std::map SortedStringContainer; + + if (m_FileName == "") + { + throw itk::ImageFileReaderException(__FILE__, __LINE__, "FileName must be non-empty"); + } + // MITK_INFO << "FileName: "<< m_FileName <<", FilePrefix: "<< m_FilePrefix << ", FilePattern: "<< m_FilePattern << + // std::endl; + + // determine begin and end idexes of the last digit sequence in the + // filename from the sample file name + // Therefore, walk backwards from the end of the filename until + // a number is found. The string in front of the number is the prefix, + // the string after the number is the extension. + std::string basename, path; + path = itksys::SystemTools::GetFilenamePath(m_FileName); + basename = itksys::SystemTools::GetFilenameName(m_FileName); + + unsigned int digitBegin = 0; + unsigned int digitEnd = 0; + bool digitFound = false; + for (unsigned int i = basename.length() - 1;; --i) + { + char character = basename[i]; + if (character >= '0' && character <= '9') + { + if (!digitFound) + { + digitEnd = i; + digitBegin = i; + digitFound = true; + } + else + digitBegin = i; + } + else + { + // end of digit series found, jump out of loop! + if (digitFound) + break; + } + if (i == 0) + break; + } + + // + // if there is no digit in the filename, then we have a problem + // no matching filenames can be identified! + // + if (!digitFound) + { + itkWarningMacro("Filename contains no digit!"); + return false; + } + + // + // determine prefix and extension start and length + // + unsigned int prefixBegin = 0; + unsigned int prefixLength = digitBegin; + unsigned int extensionBegin = digitEnd + 1; + unsigned int extensionLength = (digitEnd == basename.length() - 1 ? 0 : basename.length() - 1 - digitEnd); + unsigned int numberLength = digitEnd - digitBegin + 1; + + // + // extract prefix and extension + // + std::string prefix = ""; + if (prefixLength != 0) + prefix = basename.substr(prefixBegin, prefixLength); + std::string extension = ""; + if (extensionLength != 0) + extension = basename.substr(extensionBegin, extensionLength); + + // + // print debug information + // + /* + MITK_INFO << "digitBegin : " << digitBegin << std::endl; + MITK_INFO << "digitEnd : " << digitEnd << std::endl; + MITK_INFO << "number of digits: " << numberLength << std::endl; + MITK_INFO << "prefixBegin : " << prefixBegin << std::endl; + MITK_INFO << "prefixLength : " << prefixLength << std::endl; + MITK_INFO << "prefix : " << prefix << std::endl; + MITK_INFO << "extensionBegin : " << extensionBegin << std::endl; + MITK_INFO << "extensionLength : " << extensionLength << std::endl; + MITK_INFO << "extension : " << extension << std::endl; + */ + if ((prefixLength + extensionLength + numberLength) != basename.length()) + { + throw itk::ImageFileReaderException( + __FILE__, __LINE__, "prefixLength + extensionLength + numberLength != basenameLength"); + } + + // + // Load Directory + // + std::string directory = itksys::SystemTools::GetFilenamePath(m_FileName); + itksys::Directory itkDir; + if (!itkDir.Load(directory.c_str())) + { + itkWarningMacro(<< "Directory " << directory << " cannot be read!"); + return false; + } + + // + // Get a list of all files in the directory + // + StringContainer unmatchedFiles; + // unsigned long i; + for (unsigned long i = 0; i < itkDir.GetNumberOfFiles(); i++) + { + // Only read files + std::string filename = directory + "/" + itkDir.GetFile(i); + if (itksys::SystemTools::FileIsDirectory(filename.c_str())) + continue; + + // store the filenames without path + unmatchedFiles.push_back(itkDir.GetFile(i)); + } + + // + // Match the file list against the file prefix and extension, + // the result should be only the files that should be read + // + StringContainer matchedFiles; + for (auto it = unmatchedFiles.begin(); it != unmatchedFiles.end(); ++it) + { + bool prefixMatch = false; + bool extensionMatch = false; + + // check if the file prefix matches the current file + if (prefixLength != 0) + prefixMatch = (it->find(prefix) == prefixBegin); // check if prefix is found + else + prefixMatch = (((*it)[0] >= '0') && ((*it)[0] <= '9')); // check if filename begins with digit + + // check if the file extension matches the current file + if (extensionLength != 0) + extensionMatch = (it->find(extension) == it->length() - extensionLength); // check if prefix is found + else + extensionMatch = + (((*it)[it->length() - 1] >= '0') && ((*it)[it->length() - 1] <= '9')); // check if filename ends with digit + + if (prefixMatch && extensionMatch) + { + matchedFiles.push_back(*it); + } + } + if (matchedFiles.size() == 0) + { + itkWarningMacro(<< "Sorry, none of the files matched the prefix!"); + return false; + } + + // + // parse the file names from back to front for digits + // and convert them to a number. Store the filename and number + // in a SortedStringContainer + // + SortedStringContainer sortedFiles; + for (auto it = matchedFiles.begin(); it != matchedFiles.end(); ++it) + { + // parse the filename starting from pos digitBegin until we reach a non-digit + // or the end of filename + std::string number = ""; + std::string currentFilename(*it); + for (unsigned int i = digitBegin; i < currentFilename.length(); ++i) + { + char character = currentFilename[i]; + // do we have a digit? + if (character >= '0' && character <= '9') + number += character; + else + break; // end of digit series found, jump out of loop! + } + if (number.length() == 0) + { + // The file is not numbered, this is an error! + // Nevertheless, we try the next files. + itkWarningMacro(<< "The filename " << *it + << "does not contain a valid digit sequence but matches prefix and extension. Skipping file!"); + } + else + { + if ((number.length() + prefix.length() + extension.length()) != it->length()) + { + itkWarningMacro( + "The file " + << *it + << " matches prefix and extension, but the string in beteen is not a single digit-sequence. Skipping file!"); + } + else + { + // convert the number string into an integer and + // insert the filname (including directory) into the SortedStringContainer + unsigned int num = atoi(number.c_str()); + sortedFiles.insert(std::make_pair(num, directory + "/" + *it)); + } + } + } + if (sortedFiles.size() == 0) + { + itkWarningMacro(<< "Sorry, no numbered files found, I can't load anything..."); + return false; + } + + // + // Convert the sorted string container in a plain sorted vector of strings; + // + m_MatchedFileNames.clear(); + m_MatchedFileNames.resize(sortedFiles.size()); + unsigned long index = 0; + for (auto it = sortedFiles.begin(); it != sortedFiles.end(); ++it, ++index) + { + m_MatchedFileNames[index] = it->second; + MITK_INFO << "Added " << it->second << " to the set of matched files!" << std::endl; + } + return true; +} + +mitk::FileSeriesReader::MatchedFileNames mitk::FileSeriesReader::GetMatchedFileNames() +{ + return m_MatchedFileNames; +} + +mitk::FileSeriesReader::FileSeriesReader() : m_FileName(""), m_FilePrefix(""), m_FilePattern("") +{ +} + +mitk::FileSeriesReader::~FileSeriesReader() +{ +} diff --git a/Modules/LegacyIO/mitkFileSeriesReader.h b/Modules/LegacyIO/mitkFileSeriesReader.h new file mode 100644 index 0000000000..e0b357957a --- /dev/null +++ b/Modules/LegacyIO/mitkFileSeriesReader.h @@ -0,0 +1,61 @@ +/*=================================================================== + +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_FILE_SERIES_READER__H_ +#define __MITK_FILE_SERIES_READER__H_ + +#include +#include +#include +#include +#include + +namespace mitk +{ + /** + * Provides a function which generates a list of files from + * a given prefix and pattern. + * Subclasses may use this function to load a series of files. + * + * @deprecatedSince{2014_10} + */ + class MITKLEGACYIO_EXPORT FileSeriesReader : public FileReader + { + public: + mitkClassMacro(FileSeriesReader, FileReader) + + typedef std::vector MatchedFileNames; + + virtual MatchedFileNames GetMatchedFileNames(); + + protected: + FileSeriesReader(); + + virtual ~FileSeriesReader(); + + virtual bool GenerateFileList(); + + std::string m_FileName; + + std::string m_FilePrefix; + + std::string m_FilePattern; + + MatchedFileNames m_MatchedFileNames; + }; +} + +#endif diff --git a/Modules/LegacyIO/mitkImageWriter.cpp b/Modules/LegacyIO/mitkImageWriter.cpp new file mode 100644 index 0000000000..dd95129e19 --- /dev/null +++ b/Modules/LegacyIO/mitkImageWriter.cpp @@ -0,0 +1,480 @@ +/*=================================================================== + +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 "mitkImageWriter.h" + +#include "mitkImage.h" +#include "mitkImageAccessByItk.h" +#include "mitkImageReadAccessor.h" +#include "mitkImageTimeSelector.h" +#include "mitkItkPictureWrite.h" +#include + +#include +#include + +mitk::ImageWriter::ImageWriter() : m_UseCompression(true) +{ + this->SetNumberOfRequiredInputs(1); + m_MimeType = ""; + SetDefaultExtension(); +} + +mitk::ImageWriter::~ImageWriter() +{ +} + +void mitk::ImageWriter::SetFileName(const char *fileName) +{ + if (fileName && (fileName == this->m_FileName)) + { + return; + } + if (fileName) + { + this->m_FileName = fileName; + this->m_FileNameWithoutExtension = this->m_FileName; + this->m_Extension.clear(); + std::size_t pos = this->m_FileName.find_last_of("/\\"); + if (pos != std::string::npos) + { + std::size_t ppos = this->m_FileName.find_first_of('.', pos); + if (ppos != std::string::npos) + { + this->m_FileNameWithoutExtension = this->m_FileName.substr(0, ppos); + this->m_Extension = this->m_FileName.substr(ppos); + } + } + } + else + { + this->m_FileName.clear(); + this->m_FileNameWithoutExtension.clear(); + this->m_Extension.clear(); + } + this->Modified(); +} + +void mitk::ImageWriter::SetFileName(const std::string &fileName) +{ + this->SetFileName(fileName.c_str()); +} + +void mitk::ImageWriter::SetExtension(const char *extension) +{ + if (extension && (extension == this->m_Extension)) + { + return; + } + if (extension) + { + this->m_Extension = extension; + this->m_FileName = this->m_FileNameWithoutExtension + this->m_Extension; + } + else + { + this->m_Extension.clear(); + this->m_FileName = this->m_FileNameWithoutExtension; + } + this->Modified(); +} + +void mitk::ImageWriter::SetExtension(const std::string &extension) +{ + this->SetFileName(extension.c_str()); +} + +void mitk::ImageWriter::SetDefaultExtension() +{ + this->m_Extension = ".mhd"; + this->m_FileName = this->m_FileNameWithoutExtension + this->m_Extension; + this->Modified(); +} + +#include +#include +#include +static void writeVti(const char *filename, mitk::Image *image, int t = 0) +{ + vtkXMLImageDataWriter *vtkwriter = vtkXMLImageDataWriter::New(); + vtkwriter->SetFileName(filename); + vtkwriter->SetInputData(image->GetVtkImageData(t)); + vtkwriter->Write(); + vtkwriter->Delete(); +} + +#include + +void mitk::ImageWriter::WriteByITK(mitk::Image *image, const std::string &fileName) +{ + MITK_INFO << "Writing image: " << fileName << std::endl; + // Pictures and picture series like .png are written via a different mechanism then volume images. + // So, they are still multiplexed and thus not support vector images. + if (fileName.find(".png") != std::string::npos || fileName.find(".tif") != std::string::npos || + fileName.find(".jpg") != std::string::npos || fileName.find(".bmp") != std::string::npos) + { + try + { + // switch processing of single/multi-component images + if (image->GetPixelType(0).GetNumberOfComponents() == 1) + { + AccessByItk_1(image, _mitkItkPictureWrite, fileName); + } + else + { + AccessFixedPixelTypeByItk_1(image, + _mitkItkPictureWriteComposite, + MITK_ACCESSBYITK_PIXEL_TYPES_SEQ MITK_ACCESSBYITK_COMPOSITE_PIXEL_TYPES_SEQ, + fileName); + } + } + catch (itk::ExceptionObject &e) + { + std::cerr << "Caught " << e.what() << std::endl; + } + catch (std::exception &e) + { + std::cerr << "Caught std::exception " << e.what() << std::endl; + } + + return; + } + + // Implementation of writer using itkImageIO directly. This skips the use + // of templated itkImageFileWriter, which saves the multiplexing on MITK side. + + unsigned int dimension = image->GetDimension(); + unsigned int *dimensions = image->GetDimensions(); + mitk::PixelType pixelType = image->GetPixelType(); + mitk::Vector3D mitkSpacing = image->GetGeometry()->GetSpacing(); + mitk::Point3D mitkOrigin = image->GetGeometry()->GetOrigin(); + + // Due to templating in itk, we are forced to save a 4D spacing and 4D Origin, though they are not supported in MITK + itk::Vector spacing4D; + spacing4D[0] = mitkSpacing[0]; + spacing4D[1] = mitkSpacing[1]; + spacing4D[2] = mitkSpacing[2]; + spacing4D[3] = 1; // There is no support for a 4D spacing. However, we should have an valid value here + + itk::Vector origin4D; + origin4D[0] = mitkOrigin[0]; + origin4D[1] = mitkOrigin[1]; + origin4D[2] = mitkOrigin[2]; + origin4D[3] = 0; // There is no support for a 4D origin. However, we should have an valid value here + + itk::ImageIOBase::Pointer imageIO = + itk::ImageIOFactory::CreateImageIO(fileName.c_str(), itk::ImageIOFactory::WriteMode); + + if (imageIO.IsNull()) + { + itkExceptionMacro(<< "Error: Could not create itkImageIO via factory for file " << fileName); + } + + // Set the necessary information for imageIO + imageIO->SetNumberOfDimensions(dimension); + imageIO->SetPixelType(pixelType.GetPixelType()); + imageIO->SetComponentType(pixelType.GetComponentType() < PixelComponentUserType ? + static_cast(pixelType.GetComponentType()) : + itk::ImageIOBase::UNKNOWNCOMPONENTTYPE); + imageIO->SetNumberOfComponents(pixelType.GetNumberOfComponents()); + + itk::ImageIORegion ioRegion(dimension); + + for (unsigned int i = 0; i < dimension; i++) + { + imageIO->SetDimensions(i, dimensions[i]); + imageIO->SetSpacing(i, spacing4D[i]); + imageIO->SetOrigin(i, origin4D[i]); + + mitk::Vector3D mitkDirection; + mitkDirection.SetVnlVector( + image->GetGeometry()->GetIndexToWorldTransform()->GetMatrix().GetVnlMatrix().get_column(i)); + itk::Vector direction4D; + direction4D[0] = mitkDirection[0]; + direction4D[1] = mitkDirection[1]; + direction4D[2] = mitkDirection[2]; + + // MITK only supports a 3x3 direction matrix. Due to templating in itk, however, we must + // save a 4x4 matrix for 4D images. in this case, add an homogneous component to the matrix. + if (i == 3) + direction4D[3] = 1; // homogenous component + else + direction4D[3] = 0; + + vnl_vector axisDirection(dimension); + for (unsigned int j = 0; j < dimension; j++) + { + axisDirection[j] = direction4D[j] / spacing4D[i]; + } + imageIO->SetDirection(i, axisDirection); + + ioRegion.SetSize(i, image->GetLargestPossibleRegion().GetSize(i)); + ioRegion.SetIndex(i, image->GetLargestPossibleRegion().GetIndex(i)); + } + + // use compression if available + imageIO->SetUseCompression(m_UseCompression); + + imageIO->SetIORegion(ioRegion); + imageIO->SetFileName(fileName); + + ImageReadAccessor imageAccess(image); + imageIO->Write(imageAccess.GetData()); +} + +void mitk::ImageWriter::GenerateData() +{ + mitk::LocaleSwitch localeSwitch("C"); + + if (m_FileName == "") + { + itkWarningMacro(<< "Sorry, filename has not been set!"); + return; + } + + FILE *tempFile = fopen(m_FileName.c_str(), "w"); + if (tempFile == nullptr) + { + itkExceptionMacro(<< "File location not writeable"); + return; + } + fclose(tempFile); + remove(m_FileName.c_str()); + + // Creating clone of input image, since i might change the geometry + mitk::Image::Pointer input = const_cast(this->GetInput())->Clone(); + + // Check if geometry information will be lost + if (input->GetDimension() == 2) + { + if (!input->GetGeometry()->Is2DConvertable()) + { + MITK_WARN << "Saving a 2D image with 3D geometry information. Geometry information will be lost! You might " + "consider using Convert2Dto3DImageFilter before saving."; + + // set matrix to identity + mitk::AffineTransform3D::Pointer affTrans = mitk::AffineTransform3D::New(); + affTrans->SetIdentity(); + mitk::Vector3D spacing = input->GetGeometry()->GetSpacing(); + mitk::Point3D origin = input->GetGeometry()->GetOrigin(); + input->GetGeometry()->SetIndexToWorldTransform(affTrans); + input->GetGeometry()->SetSpacing(spacing); + input->GetGeometry()->SetOrigin(origin); + } + } + + bool vti = (m_Extension.find(".vti") != std::string::npos); + + // If the extension is NOT .pic and NOT .nrrd and NOT .nii and NOT .nii.gz the following block is entered + if (m_Extension.find(".pic") == std::string::npos && m_Extension.find(".nrrd") == std::string::npos && + m_Extension.find(".nii") == std::string::npos && m_Extension.find(".nii.gz") == std::string::npos) + { + if (input->GetDimension() > 3) + { + int t, timesteps; + + timesteps = input->GetDimension(3); + ImageTimeSelector::Pointer timeSelector = ImageTimeSelector::New(); + timeSelector->SetInput(input); + mitk::Image::Pointer image = timeSelector->GetOutput(); + for (t = 0; t < timesteps; ++t) + { + std::ostringstream filename; + timeSelector->SetTimeNr(t); + timeSelector->Update(); + if (input->GetTimeGeometry()->IsValidTimeStep(t)) + { + const mitk::TimeBounds &timebounds = input->GetTimeGeometry()->GetTimeBounds(t); + filename << m_FileNameWithoutExtension << "_S" << std::setprecision(0) << timebounds[0] << "_E" + << std::setprecision(0) << timebounds[1] << "_T" << t << m_Extension; + } + else + { + itkWarningMacro(<< "Error on write: TimeGeometry invalid of image " << filename.str() << "."); + filename << m_FileNameWithoutExtension << "_T" << t << m_Extension; + } + if (vti) + { + writeVti(filename.str().c_str(), input, t); + } + else + { + WriteByITK(image, filename.str()); + } + } + } + else if (vti) + { + writeVti(m_FileName.c_str(), input); + } + else + { + WriteByITK(input, m_FileName); + } + } + else + { + // use the PicFileWriter for the .pic data type + if (m_Extension.find(".pic") != std::string::npos) + { + /* PicFileWriter::Pointer picWriter = PicFileWriter::New(); + size_t found; + found = m_FileName.find( m_Extension ); // !!! HAS to be at the very end of the filename (not somewhere in the middle) + if( m_FileName.length() > 3 && found != m_FileName.length() - 4 ) + { + //if Extension not in Filename + std::ostringstream filename; + filename << m_FileName.c_str() << m_Extension; + picWriter->SetFileName( filename.str().c_str() ); + } + else + { + picWriter->SetFileName( m_FileName.c_str() ); + } + picWriter->SetInputImage( input ); + picWriter->Write(); + */ } + + // use the ITK .nrrd Image writer + if (m_Extension.find(".nrrd") != std::string::npos || m_Extension.find(".nii") != std::string::npos || + m_Extension.find(".nii.gz") != std::string::npos) + { + WriteByITK(input, this->m_FileName); + } + } + m_MimeType = "application/MITK.Pic"; +} + +bool mitk::ImageWriter::CanWriteDataType(DataNode *input) +{ + if (input) + { + return this->CanWriteBaseDataType(input->GetData()); + } + return false; +} + +void mitk::ImageWriter::SetInput(DataNode *input) +{ + if (input && CanWriteDataType(input)) + this->ProcessObject::SetNthInput(0, dynamic_cast(input->GetData())); +} + +std::string mitk::ImageWriter::GetWritenMIMEType() +{ + return m_MimeType; +} + +std::vector mitk::ImageWriter::GetPossibleFileExtensions() +{ + std::vector possibleFileExtensions; + possibleFileExtensions.push_back(".pic"); + possibleFileExtensions.push_back(".pic.gz"); + possibleFileExtensions.push_back(".bmp"); + possibleFileExtensions.push_back(".dcm"); + possibleFileExtensions.push_back(".DCM"); + possibleFileExtensions.push_back(".dicom"); + possibleFileExtensions.push_back(".DICOM"); + possibleFileExtensions.push_back(".gipl"); + possibleFileExtensions.push_back(".gipl.gz"); + possibleFileExtensions.push_back(".mha"); + possibleFileExtensions.push_back(".nii"); + possibleFileExtensions.push_back(".nii.gz"); + possibleFileExtensions.push_back(".nrrd"); + possibleFileExtensions.push_back(".nhdr"); + possibleFileExtensions.push_back(".png"); + possibleFileExtensions.push_back(".PNG"); + possibleFileExtensions.push_back(".spr"); + possibleFileExtensions.push_back(".mhd"); + possibleFileExtensions.push_back(".vtk"); + possibleFileExtensions.push_back(".vti"); + possibleFileExtensions.push_back(".hdr"); + possibleFileExtensions.push_back(".img"); + possibleFileExtensions.push_back(".img.gz"); + possibleFileExtensions.push_back(".png"); + possibleFileExtensions.push_back(".tif"); + possibleFileExtensions.push_back(".jpg"); + return possibleFileExtensions; +} + +std::string mitk::ImageWriter::GetSupportedBaseData() const +{ + return Image::GetStaticNameOfClass(); +} + +std::string mitk::ImageWriter::GetFileExtension() +{ + return m_Extension; +} + +void mitk::ImageWriter::SetInput(mitk::Image *image) +{ + this->ProcessObject::SetNthInput(0, image); +} + +const mitk::Image *mitk::ImageWriter::GetInput() +{ + if (this->GetNumberOfInputs() < 1) + { + return nullptr; + } + else + { + return static_cast(this->ProcessObject::GetInput(0)); + } +} + +const char *mitk::ImageWriter::GetDefaultFilename() +{ + return "Image.nrrd"; +} + +const char *mitk::ImageWriter::GetFileDialogPattern() +{ + return "Nearly Raw Raster Data (*.nrrd);;" + "NIfTI format (*.nii *.nii.gz);;" + "VTK Image Data Files (*.vti);;" + "NRRD with detached header (*.nhdr);;" + "Analyze Format (*.hdr);;" + "MetaImage (*.mhd);;" + "Sets of 2D slices (*.png *.tiff *.jpg *.jpeg *.bmp);;" + "DICOM (*.dcm *.DCM *.dicom *.DICOM);;" + "UMDS GIPL Format Files (*.gipl *.gipl.gz)"; +} + +const char *mitk::ImageWriter::GetDefaultExtension() +{ + return ".nrrd"; +} + +bool mitk::ImageWriter::CanWriteBaseDataType(BaseData::Pointer data) +{ + return dynamic_cast(data.GetPointer()); +} + +void mitk::ImageWriter::DoWrite(BaseData::Pointer data) +{ + if (this->CanWriteBaseDataType(data)) + { + this->SetInput(dynamic_cast(data.GetPointer())); + this->Update(); + } +} + +void mitk::ImageWriter::SetUseCompression(bool useCompression) +{ + m_UseCompression = useCompression; +} diff --git a/Modules/LegacyIO/mitkImageWriter.h b/Modules/LegacyIO/mitkImageWriter.h new file mode 100644 index 0000000000..b171e63fb6 --- /dev/null +++ b/Modules/LegacyIO/mitkImageWriter.h @@ -0,0 +1,173 @@ +/*=================================================================== + +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_IMAGE_WRITER__H_ +#define _MITK_IMAGE_WRITER__H_ + +#include +#include + +namespace mitk +{ + class Image; + /** + * @brief Writer for mitk::Image + * + * Uses the given extension (SetExtension) to decide the format to write + * (.mhd is default, .pic, .tif, .png, .jpg supported yet). + * @ingroup MitkLegacyIOModule + * @deprecatedSince{2014_10} Use mitk::IOUtils or mitk::FileWriterRegistry instead. + */ + class MITKLEGACYIO_EXPORT ImageWriter : public mitk::FileWriterWithInformation + { + public: + mitkClassMacro(ImageWriter, mitk::FileWriter); + + itkFactorylessNewMacro(Self) itkCloneMacro(Self) + + mitkWriterMacro; + + /** + * Sets the filename of the file to write. + * @param _arg the name of the file to write. + */ + virtual void SetFileName(const char *fileName) override; + virtual void SetFileName(const std::string &fileName); + + /** + * @returns the name of the file to be written to disk. + */ + itkGetStringMacro(FileName); + + /** + * \brief Explicitly set the extension to be added to the filename. + * @param _arg to be added to the filename, including a "." + * (e.g., ".mhd"). + */ + virtual void SetExtension(const char *extension); + virtual void SetExtension(const std::string &extension); + + /** + * \brief Get the extension to be added to the filename. + * @returns the extension to be added to the filename (e.g., + * ".mhd"). + */ + itkGetStringMacro(Extension); + + /** + * \brief Set the extension to be added to the filename to the default + */ + void SetDefaultExtension(); + + /** + * @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 0'th input object for the filter. + * @param input the first input for the filter. + */ + void SetInput(mitk::Image *input); + + //##Documentation + //## @brief Return the possible file extensions for the data type associated with the writer + virtual std::vector GetPossibleFileExtensions() override; + + virtual std::string GetSupportedBaseData() const override; + + /** + * @brief Return the extension to be added to the filename. + */ + virtual std::string GetFileExtension() override; + + /** + * @brief Check if the Writer can write the Content of the + */ + virtual bool CanWriteDataType(DataNode *) override; + + /** + * @brief Return the MimeType of the saved File. + */ + virtual std::string GetWritenMIMEType() override; + + using Superclass::SetInput; + /** + * @brief Set the DataTreenode as Input. Important: The Writer always have a SetInput-Function. + */ + virtual void SetInput(DataNode *); + + /** + * @returns the 0'th input object of the filter. + */ + const mitk::Image *GetInput(); + + // FileWriterWithInformation methods + virtual const char *GetDefaultFilename() override; + virtual const char *GetFileDialogPattern() override; + virtual const char *GetDefaultExtension() override; + virtual bool CanWriteBaseDataType(BaseData::Pointer data) override; + virtual void DoWrite(BaseData::Pointer data) override; + + void SetUseCompression(bool useCompression); + + protected: + /** + * Constructor. + */ + ImageWriter(); + + /** + * Virtual destructor. + */ + virtual ~ImageWriter(); + + virtual void GenerateData() override; + + virtual void WriteByITK(mitk::Image *image, const std::string &fileName); + + std::string m_FileName; + + std::string m_FileNameWithoutExtension; + + std::string m_FilePrefix; + + std::string m_FilePattern; + + std::string m_Extension; + + std::string m_MimeType; + + bool m_UseCompression; + }; +} + +#endif //_MITK_IMAGE_WRITER__H_ diff --git a/Modules/LegacyIO/mitkImageWriterFactory.cpp b/Modules/LegacyIO/mitkImageWriterFactory.cpp new file mode 100644 index 0000000000..6097cb6fc1 --- /dev/null +++ b/Modules/LegacyIO/mitkImageWriterFactory.cpp @@ -0,0 +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. + +===================================================================*/ + +#include "mitkImageWriterFactory.h" + +#include "itkCreateObjectFunction.h" +#include "itkVersion.h" + +#include "mitkImageWriter.h" + +namespace mitk +{ + template + class CreateImageWriter : public itk::CreateObjectFunctionBase + { + public: + /** Standard class typedefs. */ + typedef CreateImageWriter Self; + typedef itk::SmartPointer Pointer; + + /** Methods from itk:LightObject. */ + itkFactorylessNewMacro(Self); + LightObject::Pointer CreateObject() override + { + typename T::Pointer p = T::New(); + p->Register(); + return p.GetPointer(); + } + + protected: + CreateImageWriter() {} + ~CreateImageWriter() override {} + private: + CreateImageWriter(const Self &); // purposely not implemented + void operator=(const Self &); // purposely not implemented + }; + + ImageWriterFactory::ImageWriterFactory() + { + this->RegisterOverride( + "IOWriter", "ImageWriter", "Image Writer", 1, mitk::CreateImageWriter::New()); + } + + ImageWriterFactory::~ImageWriterFactory() {} + const char *ImageWriterFactory::GetITKSourceVersion() const { return ITK_SOURCE_VERSION; } + const char *ImageWriterFactory::GetDescription() const { return "ImageWriterFactory"; } +} // end namespace mitk diff --git a/Modules/LegacyIO/mitkImageWriterFactory.h b/Modules/LegacyIO/mitkImageWriterFactory.h new file mode 100644 index 0000000000..ae05ac68c5 --- /dev/null +++ b/Modules/LegacyIO/mitkImageWriterFactory.h @@ -0,0 +1,68 @@ +/*=================================================================== + +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 IMAGEWRITERFACTORY_H_HEADER_INCLUDED +#define IMAGEWRITERFACTORY_H_HEADER_INCLUDED + +#include + +#include "itkObjectFactoryBase.h" +#include "mitkBaseData.h" + +namespace mitk +{ + /** + * @deprecatedSince{2014_10} Use mitk::IOUtils or mitk::FileReaderRegistry instead. + */ + class DEPRECATED() MITKLEGACYIO_EXPORT ImageWriterFactory : public itk::ObjectFactoryBase + { + public: + mitkClassMacroItkParent(mitk::ImageWriterFactory, itk::ObjectFactoryBase) + + /** Class methods used to interface with the registered factories. */ + virtual const char *GetITKSourceVersion(void) const override; + virtual const char *GetDescription(void) const override; + + /** Method for class instantiation. */ + itkFactorylessNewMacro(Self); + + /** + * Register one factory of this type + * \deprecatedSince{2013_09} + */ + DEPRECATED(static void RegisterOneFactory(void)) + { + static bool IsRegistered = false; + if (!IsRegistered) + { + ImageWriterFactory::Pointer imageWriterFactory = ImageWriterFactory::New(); + ObjectFactoryBase::RegisterFactory(imageWriterFactory); + IsRegistered = true; + } + } + + protected: + ImageWriterFactory(); + ~ImageWriterFactory(); + + private: + ImageWriterFactory(const Self &); // purposely not implemented + void operator=(const Self &); // purposely not implemented + }; + +} // end namespace mitk + +#endif diff --git a/Modules/LegacyIO/mitkItkImageFileIOFactory.cpp b/Modules/LegacyIO/mitkItkImageFileIOFactory.cpp new file mode 100644 index 0000000000..53e3e22565 --- /dev/null +++ b/Modules/LegacyIO/mitkItkImageFileIOFactory.cpp @@ -0,0 +1,41 @@ +/*=================================================================== + +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 "mitkItkImageFileIOFactory.h" +#include "mitkIOAdapter.h" +#include "mitkItkImageFileReader.h" + +#include "itkVersion.h" + +namespace mitk +{ + ItkImageFileIOFactory::ItkImageFileIOFactory() + { + this->RegisterOverride("mitkIOAdapter", + "mitkItkImageFileReader", + "itk Image IO", + 1, + itk::CreateObjectFunction>::New()); + } + + ItkImageFileIOFactory::~ItkImageFileIOFactory() {} + const char *ItkImageFileIOFactory::GetITKSourceVersion() const { return ITK_SOURCE_VERSION; } + const char *ItkImageFileIOFactory::GetDescription() const + { + return "ItkImageFile IO Factory, allows the loading of images supported by ITK"; + } + +} // end namespace mitk diff --git a/Modules/LegacyIO/mitkItkImageFileIOFactory.h b/Modules/LegacyIO/mitkItkImageFileIOFactory.h new file mode 100644 index 0000000000..85441c1939 --- /dev/null +++ b/Modules/LegacyIO/mitkItkImageFileIOFactory.h @@ -0,0 +1,75 @@ +/*=================================================================== + +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 __mitkItkImageFileIOFactory_h +#define __mitkItkImageFileIOFactory_h + +#ifdef _MSC_VER +#pragma warning(disable : 4786) +#endif + +#include + +#include "itkObjectFactoryBase.h" +#include "mitkBaseData.h" + +namespace mitk +{ + //##Documentation + //## @brief Create instances of ItkImageFileReader objects using an object factory. + //## + //## @ingroup MitkLegacyIOModule + //## @deprecatedSince{2014_10} Use mitk::IOUtils or mitk::FileReaderRegistry instead. + class DEPRECATED() MITKLEGACYIO_EXPORT ItkImageFileIOFactory : public itk::ObjectFactoryBase + { + public: + /** Standard class typedefs. */ + typedef ItkImageFileIOFactory 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 override; + virtual const char *GetDescription(void) const override; + + /** Method for class instantiation. */ + itkFactorylessNewMacro(Self); + static ItkImageFileIOFactory *FactoryNew() { return new ItkImageFileIOFactory; } + /** Run-time type information (and related methods). */ + itkTypeMacro(ItkImageFileIOFactory, ObjectFactoryBase); + + /** + * Register one factory of this type + * \deprecatedSince{2013_09} + */ + DEPRECATED(static void RegisterOneFactory(void)) + { + ItkImageFileIOFactory::Pointer ItkImageFileIOFactory = ItkImageFileIOFactory::New(); + ObjectFactoryBase::RegisterFactory(ItkImageFileIOFactory); + } + + protected: + ItkImageFileIOFactory(); + ~ItkImageFileIOFactory(); + + private: + ItkImageFileIOFactory(const Self &); // purposely not implemented + void operator=(const Self &); // purposely not implemented + }; + +} // end namespace mitk + +#endif diff --git a/Modules/LegacyIO/mitkItkImageFileReader.cpp b/Modules/LegacyIO/mitkItkImageFileReader.cpp new file mode 100644 index 0000000000..bad828651b --- /dev/null +++ b/Modules/LegacyIO/mitkItkImageFileReader.cpp @@ -0,0 +1,218 @@ +/*=================================================================== + +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 "mitkItkImageFileReader.h" +#include "mitkConfig.h" +#include "mitkException.h" +#include +#include + +#include +#include +#include +#include +//#include +#include +#include +#include +#include +//#include +//#include +//#include +//#include +//#include +//#include + +void mitk::ItkImageFileReader::GenerateData() +{ + mitk::LocaleSwitch localeSwitch("C"); + mitk::Image::Pointer image = this->GetOutput(); + + const unsigned int MINDIM = 2; + const unsigned int MAXDIM = 4; + + MITK_INFO("mitkItkImageFileReader") << "loading " << m_FileName << " via itk::ImageIOFactory... " << std::endl; + + // Check to see if we can read the file given the name or prefix + if (m_FileName == "") + { + mitkThrow() << "Empty filename in mitk::ItkImageFileReader "; + return; + } + + itk::ImageIOBase::Pointer imageIO = + itk::ImageIOFactory::CreateImageIO(m_FileName.c_str(), itk::ImageIOFactory::ReadMode); + if (imageIO.IsNull()) + { + // itkWarningMacro( << "File Type not supported!" ); + mitkThrow() << "Could not create itk::ImageIOBase object for filename " << m_FileName; + return; + } + + // Got to allocate space for the image. Determine the characteristics of + // the image. + imageIO->SetFileName(m_FileName.c_str()); + imageIO->ReadImageInformation(); + + unsigned int ndim = imageIO->GetNumberOfDimensions(); + if (ndim < MINDIM || ndim > MAXDIM) + { + itkWarningMacro(<< "Sorry, only dimensions 2, 3 and 4 are supported. The given file has " << ndim + << " dimensions! Reading as 4D."); + ndim = MAXDIM; + } + + itk::ImageIORegion ioRegion(ndim); + itk::ImageIORegion::SizeType ioSize = ioRegion.GetSize(); + itk::ImageIORegion::IndexType ioStart = ioRegion.GetIndex(); + + unsigned int dimensions[MAXDIM]; + dimensions[0] = 0; + dimensions[1] = 0; + dimensions[2] = 0; + dimensions[3] = 0; + + ScalarType spacing[MAXDIM]; + spacing[0] = 1.0f; + spacing[1] = 1.0f; + spacing[2] = 1.0f; + spacing[3] = 1.0f; + + Point3D origin; + origin.Fill(0); + + unsigned int i; + for (i = 0; i < ndim; ++i) + { + ioStart[i] = 0; + ioSize[i] = imageIO->GetDimensions(i); + if (i < MAXDIM) + { + dimensions[i] = imageIO->GetDimensions(i); + spacing[i] = imageIO->GetSpacing(i); + if (spacing[i] <= 0) + spacing[i] = 1.0f; + } + if (i < 3) + { + origin[i] = imageIO->GetOrigin(i); + } + } + + ioRegion.SetSize(ioSize); + ioRegion.SetIndex(ioStart); + + MITK_INFO("mitkItkImageFileReader") << "ioRegion: " << ioRegion << std::endl; + imageIO->SetIORegion(ioRegion); + void *buffer = new unsigned char[imageIO->GetImageSizeInBytes()]; + imageIO->Read(buffer); + + image->Initialize(MakePixelType(imageIO), ndim, dimensions); + image->SetImportChannel(buffer, 0, Image::ManageMemory); + + // access direction of itk::Image and include spacing + mitk::Matrix3D matrix; + matrix.SetIdentity(); + unsigned int j, itkDimMax3 = (ndim >= 3 ? 3 : ndim); + for (i = 0; i < itkDimMax3; ++i) + for (j = 0; j < itkDimMax3; ++j) + matrix[i][j] = imageIO->GetDirection(j)[i]; + + // re-initialize PlaneGeometry with origin and direction + PlaneGeometry *planeGeometry = static_cast(image->GetSlicedGeometry(0)->GetPlaneGeometry(0)); + planeGeometry->SetOrigin(origin); + planeGeometry->GetIndexToWorldTransform()->SetMatrix(matrix); + + // re-initialize SlicedGeometry3D + SlicedGeometry3D *slicedGeometry = image->GetSlicedGeometry(0); + slicedGeometry->InitializeEvenlySpaced(planeGeometry, image->GetDimension(2)); + slicedGeometry->SetSpacing(spacing); + + MITK_INFO("mitkItkImageFileReader") << slicedGeometry->GetCornerPoint(false, false, false); + MITK_INFO("mitkItkImageFileReader") << slicedGeometry->GetCornerPoint(true, true, true); + + // re-initialize TimeGeometry + ProportionalTimeGeometry::Pointer timeGeometry = ProportionalTimeGeometry::New(); + timeGeometry->Initialize(slicedGeometry, image->GetDimension(3)); + image->SetTimeGeometry(timeGeometry); + + buffer = nullptr; + MITK_INFO("mitkItkImageFileReader") << "number of image components: " << image->GetPixelType().GetNumberOfComponents() + << std::endl; + // mitk::DataNode::Pointer node = this->GetOutput(); + // node->SetData( image ); + + // add level-window property + // if ( image->GetPixelType().GetNumberOfComponents() == 1 ) + //{ + // SetDefaultImageProperties( node ); + //} + MITK_INFO("mitkItkImageFileReader") << "...finished!" << std::endl; +} + +bool mitk::ItkImageFileReader::CanReadFile(const std::string filename, + const std::string filePrefix, + const std::string filePattern) +{ + // First check the extension + if (filename == "") + return false; + + // check if image is serie + if (filePattern != "" && filePrefix != "") + return false; + + itk::ImageIOBase::Pointer imageIO = + itk::ImageIOFactory::CreateImageIO(filename.c_str(), itk::ImageIOFactory::ReadMode); + if (imageIO.IsNull()) + return false; + + try + { + imageIO->SetFileName(filename.c_str()); + imageIO->ReadImageInformation(); + itk::MetaDataDictionary imgMetaDictionary = imageIO->GetMetaDataDictionary(); + std::vector imgMetaKeys = imgMetaDictionary.GetKeys(); + std::vector::const_iterator itKey = imgMetaKeys.begin(); + std::string metaString; + + for (; itKey != imgMetaKeys.end(); itKey++) + { + itk::ExposeMetaData(imgMetaDictionary, *itKey, metaString); + if (itKey->find("modality") != std::string::npos) + { + if (metaString.find("DWMRI") != std::string::npos) + { + return false; // DiffusionImageReader should handle this + } + } + } + } + catch (...) + { + MITK_INFO("mitkItkImageFileReader") << "Could not read ImageInformation "; + } + + return true; +} + +mitk::ItkImageFileReader::ItkImageFileReader() : m_FileName(""), m_FilePrefix(""), m_FilePattern("") +{ +} + +mitk::ItkImageFileReader::~ItkImageFileReader() +{ +} diff --git a/Modules/LegacyIO/mitkItkImageFileReader.h b/Modules/LegacyIO/mitkItkImageFileReader.h new file mode 100644 index 0000000000..e0b57ee365 --- /dev/null +++ b/Modules/LegacyIO/mitkItkImageFileReader.h @@ -0,0 +1,65 @@ +/*=================================================================== + +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 ItkImageFileReader_H_HEADER_INCLUDED +#define ItkImageFileReader_H_HEADER_INCLUDED + +#include "mitkFileReader.h" +#include "mitkImageSource.h" +#include + +namespace mitk +{ + //##Documentation + //## @brief Reader to read file formats supported by itk + //## @ingroup MitkLegacyIOModule + //## @deprecatedSince{2014_10} Use mitk::IOUtils or mitk::FileReaderRegistry instead. + class MITKLEGACYIO_EXPORT ItkImageFileReader : public ImageSource, public FileReader + { + public: + mitkClassMacro(ItkImageFileReader, FileReader); + + /** Method for creation through the object factory. */ + itkFactorylessNewMacro(Self) itkCloneMacro(Self) + + itkSetStringMacro(FileName); + itkGetStringMacro(FileName); + + itkSetStringMacro(FilePrefix); + itkGetStringMacro(FilePrefix); + + itkSetStringMacro(FilePattern); + itkGetStringMacro(FilePattern); + + static bool CanReadFile(const std::string filename, const std::string filePrefix, const std::string filePattern); + + protected: + virtual void GenerateData() override; + + ItkImageFileReader(); + + ~ItkImageFileReader(); + + std::string m_FileName; + + std::string m_FilePrefix; + + std::string m_FilePattern; + }; + +} // namespace mitk + +#endif /* ItkImageFileReader_H_HEADER_INCLUDED */ diff --git a/Modules/LegacyIO/mitkItkPictureWrite.cpp b/Modules/LegacyIO/mitkItkPictureWrite.cpp new file mode 100644 index 0000000000..a856f3ead6 --- /dev/null +++ b/Modules/LegacyIO/mitkItkPictureWrite.cpp @@ -0,0 +1,181 @@ +/*=================================================================== + +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 "mitkItkPictureWrite.h" +#include + +#include +#include +#include + +#include + +/** Set the filenames to the specified writer in dependace on the number of images passed in */ +template +void SetOutputNames(typename WriterType::Pointer writer, const std::string &baseFileName, unsigned int numberOfImages) +{ + if (numberOfImages > 1) + { + itk::NumericSeriesFileNames::Pointer numericFileNameWriter = itk::NumericSeriesFileNames::New(); + + std::string finalFileName = baseFileName; + std::string::size_type pos = baseFileName.find_last_of(".", baseFileName.length() - 1); + if (pos == std::string::npos) + finalFileName.append(".%d.png"); + else + finalFileName.insert(pos, ".%d"); + + MITK_DEBUG << "Filename: " << finalFileName; + + numericFileNameWriter->SetEndIndex(numberOfImages); + numericFileNameWriter->SetSeriesFormat(finalFileName.c_str()); + numericFileNameWriter->Modified(); + writer->SetFileNames(numericFileNameWriter->GetFileNames()); + } + // if the given image is an 2D-png image, do not use the numericFileNameWriter + // to generate the name, since it alters the fileName given as parameter + else + { + writer->SetFileName(baseFileName.c_str()); + } +} + +template +void _mitkItkPictureWrite(itk::Image *itkImage, const std::string &fileName) +{ + typedef itk::Image TImageType; + + typedef itk::Image UCharOutputImage3DType; + typedef itk::Image ShortOutputImage3DType; + typedef itk::Image OutputImage2D_8bitType; + typedef itk::Image OutputImage2D_16bitType; + + typedef itk::ImageSeriesWriter UCharWriterType; + typedef itk::ImageSeriesWriter ShortWriterType; + + typedef itk::RescaleIntensityImageFilter UCharRescalerFilterType; + typedef itk::RescaleIntensityImageFilter ShortRescalerFilterType; + + // get the size info + size_t inputTypeSize = sizeof(TPixel); + size_t supportedOutputMaxSize = 1; // default value 8bit + + // the PNG and TIFF formats can handle up-to 16-bit images + if (fileName.find(".png") != std::string::npos || fileName.find(".tif") != std::string::npos) + { + supportedOutputMaxSize = 2; + } + + // get the dimension info + unsigned int numberOfImages = 1; + if (itkImage->GetImageDimension() > 2) + numberOfImages = itkImage->GetLargestPossibleRegion().GetSize()[2]; + + typename ShortRescalerFilterType::Pointer sh_rescaler = ShortRescalerFilterType::New(); + sh_rescaler->SetInput(itkImage); + sh_rescaler->SetOutputMinimum(0); + sh_rescaler->SetOutputMaximum(65535); + + typename UCharRescalerFilterType::Pointer rescaler = UCharRescalerFilterType::New(); + rescaler->SetInput(itkImage); + rescaler->SetOutputMinimum(0); + rescaler->SetOutputMaximum(255); + + try + { + // input is 8 bit + if (inputTypeSize == 1) + { + UCharWriterType::Pointer writer = UCharWriterType::New(); + SetOutputNames(writer, fileName, numberOfImages); + writer->SetInput(rescaler->GetOutput()); + writer->Update(); + } + // input pixel type is 16bit -> writer can handle 16bit images + else if (inputTypeSize == supportedOutputMaxSize && supportedOutputMaxSize == 2) + { + ShortWriterType::Pointer writer = ShortWriterType::New(); + SetOutputNames(writer, fileName, numberOfImages); + writer->SetInput(sh_rescaler->GetOutput()); + writer->Update(); + } + // rescaling input to maximum of supported format + else + { + if (supportedOutputMaxSize == 2) + { + typename ShortWriterType::Pointer writer = ShortWriterType::New(); + SetOutputNames(writer, fileName, numberOfImages); + writer->SetInput(sh_rescaler->GetOutput()); + writer->Update(); + } + else + { + typename UCharWriterType::Pointer writer = UCharWriterType::New(); + SetOutputNames(writer, fileName, numberOfImages); + writer->SetInput(rescaler->GetOutput()); + writer->Update(); + } + } + } + catch (const itk::ExceptionObject &e) + { + MITK_ERROR << "ITK Exception occured: " << e.what(); + mitkThrow() << "Caught ITK exception while writing image with scalar type \n" << e.what(); + } +} + +template +void _mitkItkPictureWriteComposite(itk::Image *itkImage, const std::string &fileName) +{ + typedef itk::Image TImageType; + typedef itk::Image TImageType2D; + + typedef itk::ImageSeriesWriter WriterType; + typename WriterType::Pointer writer = WriterType::New(); + + // get the dimension info + unsigned int numberOfImages = 1; + if (itkImage->GetImageDimension() > 2) + numberOfImages = itkImage->GetLargestPossibleRegion().GetSize()[2]; + + // create output name(s) + SetOutputNames(writer, fileName, numberOfImages); + + writer->SetInput(itkImage); + try + { + writer->Update(); + } + catch (const itk::ExceptionObject &e) + { + MITK_ERROR << "ITK Exception occured: " << e.what(); + mitkThrow() << "Caught ITK exception while writing image with composite type \n" << e.what(); + } +} + +#define InstantiateAccessFunction__mitkItkPictureWrite(pixelType, dim) \ + template MITKLEGACYIO_EXPORT void _mitkItkPictureWrite(itk::Image *, const std::string &); + +#define InstantiateAccessFunction__mitkItkPictureWriteComposite(pixelType, dim) \ + template MITKLEGACYIO_EXPORT void _mitkItkPictureWriteComposite(itk::Image *, const std::string &); + +InstantiateAccessFunction(_mitkItkPictureWrite) + + InstantiateAccessFunctionForFixedPixelType( + _mitkItkPictureWriteComposite, MITK_ACCESSBYITK_PIXEL_TYPES_SEQ MITK_ACCESSBYITK_COMPOSITE_PIXEL_TYPES_SEQ) diff --git a/Modules/LegacyIO/mitkItkPictureWrite.h b/Modules/LegacyIO/mitkItkPictureWrite.h new file mode 100644 index 0000000000..0b8de30d64 --- /dev/null +++ b/Modules/LegacyIO/mitkItkPictureWrite.h @@ -0,0 +1,46 @@ +/*=================================================================== + +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. + +===================================================================*/ + +/** @file mitkItkPictureWrite.h */ + +#ifndef MITKITKPICTUREWRITE_H +#define MITKITKPICTUREWRITE_H + +#include +#include + +/** + * @brief ITK-Like method to be called for writing an single-component image using the AccessByItk Macros + * + * @param itkImage an image with single-component pixel type + * + * @deprecatedSince{2014_10} Use mitk::IOUtils or mitk::FileReaderRegistry instead. + */ +template +DEPRECATED(void _mitkItkPictureWrite(itk::Image *itkImage, const std::string &fileName)); + +/** + * @brief ITK-Like method to be called for writing an image + * + * @param itkImage an Image with single-component or composite pixel type + * + * @deprecatedSince{2014_10} Use mitk::IOUtils or mitk::FileReaderRegistry instead. + */ +template +DEPRECATED(void _mitkItkPictureWriteComposite(itk::Image *itkImage, + const std::string &fileName)); + +#endif /* MITKITKPICTUREWRITE_H */ diff --git a/Modules/LegacyIO/mitkPointSetIOFactory.cpp b/Modules/LegacyIO/mitkPointSetIOFactory.cpp new file mode 100644 index 0000000000..46d1619073 --- /dev/null +++ b/Modules/LegacyIO/mitkPointSetIOFactory.cpp @@ -0,0 +1,41 @@ +/*=================================================================== + +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 "mitkPointSetIOFactory.h" +#include "mitkIOAdapter.h" +#include "mitkPointSetReader.h" + +#include "itkVersion.h" + +namespace mitk +{ + PointSetIOFactory::PointSetIOFactory() + { + this->RegisterOverride("mitkIOAdapter", + "mitkPointSetReader", + "mitk PointSet IO", + 1, + itk::CreateObjectFunction>::New()); + } + + PointSetIOFactory::~PointSetIOFactory() {} + const char *PointSetIOFactory::GetITKSourceVersion() const { return ITK_SOURCE_VERSION; } + const char *PointSetIOFactory::GetDescription() const + { + return "PointSet IO Factory, allows the loading of MITK pointsets"; + } + +} // end namespace mitk diff --git a/Modules/LegacyIO/mitkPointSetIOFactory.h b/Modules/LegacyIO/mitkPointSetIOFactory.h new file mode 100644 index 0000000000..c77aa0d524 --- /dev/null +++ b/Modules/LegacyIO/mitkPointSetIOFactory.h @@ -0,0 +1,75 @@ +/*=================================================================== + +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 __mitkPointSetIOFactory_h +#define __mitkPointSetIOFactory_h + +#ifdef _MSC_VER +#pragma warning(disable : 4786) +#endif + +#include + +#include "itkObjectFactoryBase.h" +#include "mitkBaseData.h" + +namespace mitk +{ + //##Documentation + //## @brief Create instances of PointSetReader objects using an object factory. + //## + //## @ingroup MitkLegacyIOModule + //## @deprecatedSince{2014_10} Use mitk::IOUtils or mitk::FileReaderRegistry instead. + class DEPRECATED() MITKLEGACYIO_EXPORT PointSetIOFactory : public itk::ObjectFactoryBase + { + public: + /** Standard class typedefs. */ + typedef PointSetIOFactory 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 override; + virtual const char *GetDescription(void) const override; + + /** Method for class instantiation. */ + itkFactorylessNewMacro(Self); + static PointSetIOFactory *FactoryNew() { return new PointSetIOFactory; } + /** Run-time type information (and related methods). */ + itkTypeMacro(PointSetIOFactory, ObjectFactoryBase); + + /** + * Register one factory of this type + * \deprecatedSince{2013_09} + */ + DEPRECATED(static void RegisterOneFactory(void)) + { + PointSetIOFactory::Pointer PointSetIOFactory = PointSetIOFactory::New(); + ObjectFactoryBase::RegisterFactory(PointSetIOFactory); + } + + protected: + PointSetIOFactory(); + ~PointSetIOFactory(); + + private: + PointSetIOFactory(const Self &); // purposely not implemented + void operator=(const Self &); // purposely not implemented + }; + +} // end namespace mitk + +#endif diff --git a/Modules/LegacyIO/mitkPointSetReader.cpp b/Modules/LegacyIO/mitkPointSetReader.cpp new file mode 100644 index 0000000000..8d1e0045ea --- /dev/null +++ b/Modules/LegacyIO/mitkPointSetReader.cpp @@ -0,0 +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 "mitkPointSetReader.h" +#include +#include +#include + +mitk::PointSetReader::PointSetReader() +{ + m_Success = false; +} + +mitk::PointSetReader::~PointSetReader() +{ +} + +void mitk::PointSetReader::GenerateData() +{ + // Switch the current locale to "C" + LocaleSwitch localeSwitch("C"); + + m_Success = false; + if (m_FileName == "") + { + itkWarningMacro(<< "Sorry, filename has not been set!"); + return; + } + if (!this->CanReadFile(m_FileName.c_str())) + { + itkWarningMacro(<< "Sorry, can't read file " << m_FileName << "!"); + return; + } + + try + { + TiXmlDocument doc(m_FileName.c_str()); + bool loadOkay = doc.LoadFile(); + if (loadOkay) + { + TiXmlHandle docHandle(&doc); + unsigned int pointSetCounter(0); + for (TiXmlElement *currentPointSetElement = + docHandle.FirstChildElement("point_set_file").FirstChildElement("point_set").ToElement(); + currentPointSetElement != nullptr; + currentPointSetElement = currentPointSetElement->NextSiblingElement()) + { + mitk::PointSet::Pointer newPointSet = mitk::PointSet::New(); + if (currentPointSetElement->FirstChildElement("time_series") != nullptr) + { + for (TiXmlElement *currentTimeSeries = currentPointSetElement->FirstChildElement("time_series")->ToElement(); + currentTimeSeries != nullptr; + currentTimeSeries = currentTimeSeries->NextSiblingElement()) + { + unsigned int currentTimeStep(0); + TiXmlElement *currentTimeSeriesID = currentTimeSeries->FirstChildElement("time_series_id"); + + currentTimeStep = atoi(currentTimeSeriesID->GetText()); + + newPointSet = this->ReadPoint(newPointSet, currentTimeSeries, currentTimeStep); + } + } + else + { + newPointSet = this->ReadPoint(newPointSet, currentPointSetElement, 0); + } + this->SetNthOutput(pointSetCounter, newPointSet); + pointSetCounter++; + } + } + else + { + MITK_WARN << "XML parser error!"; + } + } + catch (...) + { + MITK_ERROR << "Cannot read point set."; + m_Success = false; + } + m_Success = true; +} + +mitk::PointSet::Pointer mitk::PointSetReader::ReadPoint(mitk::PointSet::Pointer newPointSet, + TiXmlElement *currentTimeSeries, + unsigned int currentTimeStep) +{ + if (currentTimeSeries->FirstChildElement("point") != nullptr) + { + for (TiXmlElement *currentPoint = currentTimeSeries->FirstChildElement("point")->ToElement(); + currentPoint != nullptr; + currentPoint = currentPoint->NextSiblingElement()) + { + unsigned int id(0); + mitk::PointSpecificationType spec((mitk::PointSpecificationType)0); + double x(0.0); + double y(0.0); + double z(0.0); + + id = atoi(currentPoint->FirstChildElement("id")->GetText()); + if (currentPoint->FirstChildElement("specification") != nullptr) + { + spec = (mitk::PointSpecificationType)atoi(currentPoint->FirstChildElement("specification")->GetText()); + } + x = atof(currentPoint->FirstChildElement("x")->GetText()); + y = atof(currentPoint->FirstChildElement("y")->GetText()); + z = atof(currentPoint->FirstChildElement("z")->GetText()); + + mitk::Point3D point; + mitk::FillVector3D(point, x, y, z); + newPointSet->SetPoint(id, point, spec, currentTimeStep); + } + } + else + { + if (currentTimeStep != newPointSet->GetTimeSteps() + 1) + { + newPointSet->Expand(currentTimeStep + 1); // expand time step series with empty time step + } + } + return newPointSet; +} + +void mitk::PointSetReader::GenerateOutputInformation() +{ +} + +int mitk::PointSetReader::CanReadFile(const char *name) +{ + std::ifstream in(name); + bool isGood = in.good(); + in.close(); + return isGood; +} + +bool mitk::PointSetReader::CanReadFile(const std::string filename, + const std::string filePrefix, + const std::string filePattern) +{ + // First check the extension + if (filename == "") + { + // MITK_INFO<<"No filename specified."<GetNumberOfOutputs(); + this->SetNumberOfIndexedOutputs(num); + for (unsigned int i = prevNum; i < num; ++i) + { + this->SetNthOutput(i, this->MakeOutput(i).GetPointer()); + } +} + +bool mitk::PointSetReader::GetSuccess() const +{ + return m_Success; +} diff --git a/Modules/LegacyIO/mitkPointSetReader.h b/Modules/LegacyIO/mitkPointSetReader.h new file mode 100644 index 0000000000..624b245144 --- /dev/null +++ b/Modules/LegacyIO/mitkPointSetReader.h @@ -0,0 +1,143 @@ +/*=================================================================== + +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_POINT_SET_READER__H_ +#define _MITK_POINT_SET_READER__H_ + +#include + +#include +#include +#include +#include +#include +#include + +namespace mitk +{ + /** + * @brief reads xml representations of mitk::PointSets from a file + * + * Reader for xml files containing one or multiple xml represenations of + * mitk::PointSets. If multiple mitk::PointSets are stored in one file, + * these are assigned to multiple outputs of the filter. The number of point + * sets which have be read can be retrieven by a call to GetNumberOfOutputs() + * after the pipeline update(). + * The reader is able to read the old 3D Pointsets without the "specification" and "timeseries" tags and the new 4D + * Pointsets. + * @note loading point sets from multiple files according to a given file pattern + * is not yet supported! + * + * @ingroup MitkLegacyIOModule + * + * @deprecatedSince{2014_10} Use mitk::IOUtils or mitk::FileReaderRegistry instead. + */ + class MITKLEGACYIO_EXPORT PointSetReader : public PointSetSource, public FileReader + { + public: + mitkClassMacro(PointSetReader, FileReader); + + itkFactorylessNewMacro(Self) itkCloneMacro(Self) + + /** + * @brief Sets the filename of the file to be read + * @param _arg the filename of the point set xml-file + */ + itkSetStringMacro(FileName); + + /** + * @brief Returns the filename of the point set xml-file. + * @returns the filename of the point set xml-file. + */ + itkGetStringMacro(FileName); + + /** + * @warning multiple load not (yet) supported + */ + itkSetStringMacro(FilePrefix); + + /** + * @warning multiple load not (yet) supported + */ + itkGetStringMacro(FilePrefix); + + /** + * @warning multiple load not (yet) supported + */ + itkSetStringMacro(FilePattern); + + /** + * @warning multiple load not (yet) supported + */ + itkGetStringMacro(FilePattern); + + static bool CanReadFile(const std::string filename, const std::string filePrefix, const std::string filePattern); + + /** + * @returns whether the last read attempt was successful or not. + */ + bool GetSuccess() const; + + protected: + /** + * Constructor + */ + PointSetReader(); + + /** + * Virtual destructor + */ + virtual ~PointSetReader(); + + /** + * Actually reads the point sets from the given file + */ + virtual void GenerateData() override; + + virtual mitk::PointSet::Pointer ReadPoint(mitk::PointSet::Pointer newPointSet, + TiXmlElement *currentTimeSeries, + unsigned int currentTimeStep); + + /** + * Does nothing in the current implementation + */ + virtual void GenerateOutputInformation() override; + + /** + * Resizes the output-objects according to the given number. + * @param num the new number of output objects. + */ + virtual void ResizeOutputs(const unsigned int &num); + + /** + * Checks if the given file has appropriate + * read access. + * @returns true if the file exists and may be read + * or false otherwise. + */ + virtual int CanReadFile(const char *name); + + std::string m_FileName; + + std::string m_FilePrefix; + + std::string m_FilePattern; + + bool m_Success; + }; +} + +#endif diff --git a/Modules/LegacyIO/mitkPointSetWriter.cpp b/Modules/LegacyIO/mitkPointSetWriter.cpp new file mode 100644 index 0000000000..f3adbcfc2e --- /dev/null +++ b/Modules/LegacyIO/mitkPointSetWriter.cpp @@ -0,0 +1,327 @@ +/*=================================================================== + +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 "mitkPointSetWriter.h" +#include +#include +#include + +// +// Initialization of the xml tags. +// + +const char *mitk::PointSetWriter::XML_POINT_SET_FILE = "point_set_file"; + +const char *mitk::PointSetWriter::XML_FILE_VERSION = "file_version"; + +const char *mitk::PointSetWriter::XML_POINT_SET = "point_set"; + +const char *mitk::PointSetWriter::XML_TIME_SERIES = "time_series"; + +const char *mitk::PointSetWriter::XML_TIME_SERIES_ID = "time_series_id"; + +const char *mitk::PointSetWriter::XML_POINT = "point"; + +const char *mitk::PointSetWriter::XML_ID = "id"; + +const char *mitk::PointSetWriter::XML_SPEC = "specification"; + +const char *mitk::PointSetWriter::XML_X = "x"; + +const char *mitk::PointSetWriter::XML_Y = "y"; + +const char *mitk::PointSetWriter::XML_Z = "z"; + +const char *mitk::PointSetWriter::VERSION_STRING = "0.1"; + +mitk::PointSetWriter::PointSetWriter() : m_FileName(""), m_FilePrefix(""), m_FilePattern("") +{ + this->SetNumberOfRequiredInputs(1); + this->SetNumberOfIndexedOutputs(1); + this->SetNthOutput(0, mitk::PointSet::New().GetPointer()); + m_Indent = 2; + m_IndentDepth = 0; + m_Success = false; +} + +mitk::PointSetWriter::~PointSetWriter() +{ +} + +void mitk::PointSetWriter::GenerateData() +{ + m_Success = false; + m_IndentDepth = 0; + + // + // Opening the file to write to + // + if (m_FileName == "") + { + itkWarningMacro(<< "Sorry, filename has not been set!"); + return; + } + std::ofstream out(m_FileName.c_str()); + if (!out.good()) + { + itkExceptionMacro(<< "File " << m_FileName << " could not be opened!"); + itkWarningMacro(<< "Sorry, file " << m_FileName << " could not be opened!"); + out.close(); + return; + } + + std::locale previousLocale(out.getloc()); + std::locale I("C"); + out.imbue(I); + + // + // Here the actual xml writing begins + // + WriteXMLHeader(out); + WriteStartElement(XML_POINT_SET_FILE, out); + WriteStartElement(XML_FILE_VERSION, out); + WriteCharacterData(VERSION_STRING, out); + WriteEndElement(XML_FILE_VERSION, out, false); + + // + // for each input object write its xml representation to + // the stream + // + for (unsigned int i = 0; i < this->GetNumberOfInputs(); ++i) + { + InputType::Pointer pointSet = this->GetInput(i); + assert(pointSet.IsNotNull()); + WriteXML(pointSet.GetPointer(), out); + } + + WriteEndElement(XML_POINT_SET_FILE, out); + out.imbue(previousLocale); + if (!out.good()) // some error during output + { + out.close(); + throw std::ios_base::failure("Some error during point set writing."); + } + + out.close(); + m_Success = true; + m_MimeType = "application/MITK.PointSet"; +} + +void mitk::PointSetWriter::WriteXML(mitk::PointSet *pointSet, std::ofstream &out) +{ + WriteStartElement(XML_POINT_SET, out); + unsigned int timecount = pointSet->GetTimeSteps(); + + for (unsigned int i = 0; i < timecount; i++) + { + WriteStartElement(XML_TIME_SERIES, out); + + WriteStartElement(XML_TIME_SERIES_ID, out); + WriteCharacterData(ConvertToString(i).c_str(), out); + WriteEndElement(XML_TIME_SERIES_ID, out, false); + + mitk::PointSet::PointsContainer *pointsContainer = pointSet->GetPointSet(i)->GetPoints(); + mitk::PointSet::PointsContainer::Iterator it; + + for (it = pointsContainer->Begin(); it != pointsContainer->End(); ++it) + { + WriteStartElement(XML_POINT, out); + + WriteStartElement(XML_ID, out); + WriteCharacterData(ConvertToString(it->Index()).c_str(), out); + WriteEndElement(XML_ID, out, false); + + mitk::PointSet::PointType point = it->Value(); + + WriteStartElement(XML_SPEC, out); + WriteCharacterData(ConvertToString(pointSet->GetSpecificationTypeInfo(it->Index(), i)).c_str(), out); + WriteEndElement(XML_SPEC, out, false); + + WriteStartElement(XML_X, out); + WriteCharacterData(ConvertToString(point[0]).c_str(), out); + WriteEndElement(XML_X, out, false); + + WriteStartElement(XML_Y, out); + WriteCharacterData(ConvertToString(point[1]).c_str(), out); + WriteEndElement(XML_Y, out, false); + + WriteStartElement(XML_Z, out); + WriteCharacterData(ConvertToString(point[2]).c_str(), out); + WriteEndElement(XML_Z, out, false); + + WriteEndElement(XML_POINT, out); + } + WriteEndElement(XML_TIME_SERIES, out); + } + + WriteEndElement(XML_POINT_SET, out); +} + +void mitk::PointSetWriter::ResizeInputs(const unsigned int &num) +{ + unsigned int prevNum = this->GetNumberOfInputs(); + this->SetNumberOfIndexedInputs(num); + for (unsigned int i = prevNum; i < num; ++i) + { + this->SetNthInput(i, mitk::PointSet::New().GetPointer()); + } +} + +void mitk::PointSetWriter::SetInput(InputType *pointSet) +{ + this->ProcessObject::SetNthInput(0, pointSet); +} + +void mitk::PointSetWriter::SetInput(const unsigned int &id, InputType *pointSet) +{ + if (id >= this->GetNumberOfInputs()) + this->ResizeInputs(id + 1); + this->ProcessObject::SetNthInput(id, pointSet); +} + +mitk::PointSet *mitk::PointSetWriter::GetInput() +{ + if (this->GetNumberOfInputs() < 1) + { + return nullptr; + } + else + { + return dynamic_cast(this->GetInput(0)); + } +} + +mitk::PointSet *mitk::PointSetWriter::GetInput(const unsigned int &num) +{ + return dynamic_cast(this->ProcessObject::GetInput(num)); +} + +template +std::string mitk::PointSetWriter::ConvertToString(T value) +{ + std::ostringstream o; + std::locale I("C"); + o.imbue(I); + + if (o << value) + { + return o.str(); + } + else + return "conversion error"; +} + +void mitk::PointSetWriter::WriteXMLHeader(std::ofstream &file) +{ + file << ""; +} + +void mitk::PointSetWriter::WriteStartElement(const char *const tag, std::ofstream &file) +{ + file << std::endl; + WriteIndent(file); + file << '<' << tag << '>'; + m_IndentDepth++; +} + +void mitk::PointSetWriter::WriteEndElement(const char *const tag, std::ofstream &file, const bool &indent) +{ + m_IndentDepth--; + if (indent) + { + file << std::endl; + WriteIndent(file); + } + file << '<' << '/' << tag << '>'; +} + +void mitk::PointSetWriter::WriteCharacterData(const char *const data, std::ofstream &file) +{ + file << data; +} + +void mitk::PointSetWriter::WriteStartElement(std::string &tag, std::ofstream &file) +{ + WriteStartElement(tag.c_str(), file); +} + +void mitk::PointSetWriter::WriteEndElement(std::string &tag, std::ofstream &file, const bool &indent) +{ + WriteEndElement(tag.c_str(), file, indent); +} + +void mitk::PointSetWriter::WriteCharacterData(std::string &data, std::ofstream &file) +{ + WriteCharacterData(data.c_str(), file); +} + +void mitk::PointSetWriter::WriteIndent(std::ofstream &file) +{ + std::string spaces(m_IndentDepth * m_Indent, ' '); + file << spaces.c_str(); +} + +bool mitk::PointSetWriter::GetSuccess() const +{ + return m_Success; +} + +bool mitk::PointSetWriter::CanWriteDataType(DataNode *input) +{ + if (input) + { + mitk::BaseData *data = input->GetData(); + if (data) + { + mitk::PointSet::Pointer pointSet = dynamic_cast(data); + if (pointSet.IsNotNull()) + { + // this writer has no "SetDefaultExtension()" - function + m_Extension = ".mps"; + return true; + } + } + } + return false; +} + +void mitk::PointSetWriter::SetInput(DataNode *input) +{ + if (input && CanWriteDataType(input)) + this->ProcessObject::SetNthInput(0, dynamic_cast(input->GetData())); +} + +std::string mitk::PointSetWriter::GetWritenMIMEType() +{ + return m_MimeType; +} + +std::vector mitk::PointSetWriter::GetPossibleFileExtensions() +{ + std::vector possibleFileExtensions; + possibleFileExtensions.push_back(".mps"); + return possibleFileExtensions; +} + +std::string mitk::PointSetWriter::GetSupportedBaseData() const +{ + return PointSet::GetStaticNameOfClass(); +} + +std::string mitk::PointSetWriter::GetFileExtension() +{ + return m_Extension; +} diff --git a/Modules/LegacyIO/mitkPointSetWriter.h b/Modules/LegacyIO/mitkPointSetWriter.h new file mode 100644 index 0000000000..6fb3a8314a --- /dev/null +++ b/Modules/LegacyIO/mitkPointSetWriter.h @@ -0,0 +1,256 @@ +/*=================================================================== + +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_POINT_SET_WRITER__H_ +#define _MITK_POINT_SET_WRITER__H_ + +#include + +#include +#include +#include + +namespace mitk +{ + /** + * @brief XML-based writer for mitk::PointSets + * + * XML-based writer for mitk::PointSets. Multiple PointSets can be written in + * a single XML file by simply setting multiple inputs to the filter. + * Writing of multiple XML files according to a given filename pattern is not + * yet supported. + * + * @ingroup MitkLegacyIOModule + * + * @deprecatedSince{2014_10} Use mitk::IOUtils or mitk::FileReaderRegistry instead. + */ + class MITKLEGACYIO_EXPORT PointSetWriter : public mitk::FileWriter + { + public: + mitkClassMacro(PointSetWriter, mitk::FileWriter); + + mitkWriterMacro; + + itkFactorylessNewMacro(Self) itkCloneMacro(Self) + + typedef mitk::PointSet InputType; + + typedef InputType::Pointer InputTypePointer; + + /** + * 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 0'th input object for the filter. + * @param input the first input for the filter. + */ + void SetInput(InputType *input); + + /** + * Sets the n'th input object for the filter. If num is + * larger than GetNumberOfInputs() the number of inputs is + * resized appropriately. + * @param input the n'th input for the filter. + */ + void SetInput(const unsigned int &num, InputType *input); + + /** + * @returns the 0'th input object of the filter. + */ + PointSet *GetInput(); + + /** + * @param num the index of the desired output object. + * @returns the n'th input object of the filter. + */ + PointSet *GetInput(const unsigned int &num); + + /** + * @brief Return the possible file extensions for the data type associated with the writer + */ + virtual std::vector GetPossibleFileExtensions() override; + + virtual std::string GetSupportedBaseData() const override; + + /** + * @brief Return the extension to be added to the filename. + */ + virtual std::string GetFileExtension() override; + + /** + * @brief Check if the Writer can write the Content of the + */ + virtual bool CanWriteDataType(DataNode *) override; + + /** + * @brief Return the MimeType of the saved File. + */ + virtual std::string GetWritenMIMEType() override; + + using mitk::FileWriter::SetInput; + /** + * @brief Set the DataTreenode as Input. Important: The Writer always have a SetInput-Function. + */ + virtual void SetInput(DataNode *); + + /** + * @returns whether the last write attempt was successful or not. + */ + bool GetSuccess() const; + + protected: + /** + * Constructor. + */ + PointSetWriter(); + + /** + * Virtual destructor. + */ + virtual ~PointSetWriter(); + + /** + * Writes the XML file + */ + virtual void GenerateData() override; + + /** + * Resizes the number of inputs of the writer. + * The inputs are initialized by empty PointSets + * @param num the new number of inputs + */ + virtual void ResizeInputs(const unsigned int &num); + + /** + * Converts an arbitrary type to a string. The type has to + * support the << operator. This works fine at least for integral + * data types as float, int, long etc. + * @param value the value to convert + * @returns the string representation of value + */ + template + std::string ConvertToString(T value); + + /** + * Writes an XML representation of the given point set to + * an outstream. The XML-Header an root node is not included! + * @param pointSet the point set to be converted to xml + * @param out the stream to write to. + */ + void WriteXML(mitk::PointSet *pointSet, std::ofstream &out); + + /** + * Writes an standard xml header to the given stream. + * @param file the stream in which the header is written. + */ + void WriteXMLHeader(std::ofstream &file); + + /** Write a start element tag */ + void WriteStartElement(const char *const tag, std::ofstream &file); + + /** + * Write an end element tag + * End-Elements following character data should pass indent = false. + */ + void WriteEndElement(const char *const tag, std::ofstream &file, const bool &indent = true); + + /** Write character data inside a tag. */ + void WriteCharacterData(const char *const data, std::ofstream &file); + + /** Write a start element tag */ + void WriteStartElement(std::string &tag, std::ofstream &file); + + /** Write an end element tag */ + void WriteEndElement(std::string &tag, std::ofstream &file, const bool &indent = true); + + /** Write character data inside a tag. */ + void WriteCharacterData(std::string &data, std::ofstream &file); + + /** Writes empty spaces to the stream according to m_IndentDepth and m_Indent */ + void WriteIndent(std::ofstream &file); + + std::string m_FileName; + + std::string m_FilePrefix; + + std::string m_FilePattern; + + std::string m_Extension; + + std::string m_MimeType; + + unsigned int m_IndentDepth; + + unsigned int m_Indent; + + bool m_Success; + + public: + static const char *XML_POINT_SET; + + static const char *XML_TIME_SERIES; + + static const char *XML_TIME_SERIES_ID; + + static const char *XML_POINT_SET_FILE; + + static const char *XML_FILE_VERSION; + + static const char *XML_POINT; + + static const char *XML_SPEC; + + static const char *XML_ID; + + static const char *XML_X; + + static const char *XML_Y; + + static const char *XML_Z; + + static const char *VERSION_STRING; + }; +} + +#endif diff --git a/Modules/LegacyIO/mitkPointSetWriterFactory.cpp b/Modules/LegacyIO/mitkPointSetWriterFactory.cpp new file mode 100644 index 0000000000..7f98f72d95 --- /dev/null +++ b/Modules/LegacyIO/mitkPointSetWriterFactory.cpp @@ -0,0 +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. + +===================================================================*/ + +#include "mitkPointSetWriterFactory.h" + +#include "itkCreateObjectFunction.h" +#include "itkVersion.h" + +#include "mitkPointSetWriter.h" + +namespace mitk +{ + template + class CreatePointSetWriter : public itk::CreateObjectFunctionBase + { + public: + /** Standard class typedefs. */ + typedef CreatePointSetWriter Self; + typedef itk::SmartPointer Pointer; + + /** Methods from itk:LightObject. */ + itkFactorylessNewMacro(Self); + LightObject::Pointer CreateObject() override + { + typename T::Pointer p = T::New(); + p->Register(); + return p.GetPointer(); + } + + protected: + CreatePointSetWriter() {} + ~CreatePointSetWriter() override {} + private: + CreatePointSetWriter(const Self &); // purposely not implemented + void operator=(const Self &); // purposely not implemented + }; + + PointSetWriterFactory::PointSetWriterFactory() + { + this->RegisterOverride( + "IOWriter", "PointSetWriter", "Point-Set Writer", 1, mitk::CreatePointSetWriter::New()); + } + + PointSetWriterFactory::~PointSetWriterFactory() {} + const char *PointSetWriterFactory::GetITKSourceVersion() const { return ITK_SOURCE_VERSION; } + const char *PointSetWriterFactory::GetDescription() const { return "PointSetWriterFactory"; } +} // end namespace mitk diff --git a/Modules/LegacyIO/mitkPointSetWriterFactory.h b/Modules/LegacyIO/mitkPointSetWriterFactory.h new file mode 100644 index 0000000000..180be34007 --- /dev/null +++ b/Modules/LegacyIO/mitkPointSetWriterFactory.h @@ -0,0 +1,68 @@ +/*=================================================================== + +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 POINTSETWRITERFACTORY_H_HEADER_INCLUDED +#define POINTSETWRITERFACTORY_H_HEADER_INCLUDED + +#include + +#include "itkObjectFactoryBase.h" +#include "mitkBaseData.h" + +namespace mitk +{ + /** + * @deprecatedSince{2014_10} Use mitk::IOUtils or mitk::FileReaderRegistry instead. + */ + class DEPRECATED() MITKLEGACYIO_EXPORT PointSetWriterFactory : public itk::ObjectFactoryBase + { + public: + mitkClassMacroItkParent(mitk::PointSetWriterFactory, itk::ObjectFactoryBase) + + /** Class methods used to interface with the registered factories. */ + virtual const char *GetITKSourceVersion(void) const override; + virtual const char *GetDescription(void) const override; + + /** Method for class instantiation. */ + itkFactorylessNewMacro(Self); + + /** + * Register one factory of this type + * \deprecatedSince{2013_09} + */ + DEPRECATED(static void RegisterOneFactory(void)) + { + static bool IsRegistered = false; + if (!IsRegistered) + { + PointSetWriterFactory::Pointer pointSetWriterFactory = PointSetWriterFactory::New(); + ObjectFactoryBase::RegisterFactory(pointSetWriterFactory); + IsRegistered = true; + } + } + + protected: + PointSetWriterFactory(); + ~PointSetWriterFactory(); + + private: + PointSetWriterFactory(const Self &); // purposely not implemented + void operator=(const Self &); // purposely not implemented + }; + +} // end namespace mitk + +#endif diff --git a/Modules/LegacyIO/mitkRawImageFileReader.cpp b/Modules/LegacyIO/mitkRawImageFileReader.cpp new file mode 100644 index 0000000000..8063d15e3f --- /dev/null +++ b/Modules/LegacyIO/mitkRawImageFileReader.cpp @@ -0,0 +1,203 @@ +/*=================================================================== + +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 "mitkRawImageFileReader.h" +#include "mitkImageCast.h" + +#include +#include +#include + +mitk::RawImageFileReader::RawImageFileReader() : m_FileName(""), m_FilePrefix(""), m_FilePattern("") +{ +} + +mitk::RawImageFileReader::~RawImageFileReader() +{ +} + +void mitk::RawImageFileReader::SetDimensions(unsigned int i, unsigned int dim) +{ + if (i > 2) + return; + + this->Modified(); // TODO: this order (first modified, then set the variable) is intended?? + m_Dimensions[i] = dim; +} + +unsigned int mitk::RawImageFileReader::GetDimensions(unsigned int i) const +{ + if (i > 2) + return 0; + + return m_Dimensions[i]; +} + +bool mitk::RawImageFileReader::CanReadFile(const std::string filename, + const std::string filePrefix, + const std::string filePattern) +{ + // First check the extension + if (filename == "") + return false; + + // check if image is serie + if (filePattern != "" && filePrefix != "") + return false; + + return true; +} + +void mitk::RawImageFileReader::GenerateData() +{ + mitk::Image::Pointer output = this->GetOutput(); + + if (this->GetOutput() == nullptr) + { + MITK_INFO << "Error" << std::endl; + } + + // Check to see if we can read the file given the name or prefix + if (m_FileName == "") + { + itkWarningMacro(<< "File Type not supported!"); + return; + } + + // check file dimensionality and pixel type and perform reading according to it + if (m_Dimensionality == 2) + { + if (m_PixelType == SCHAR) + TypedGenerateData(); + else if (m_PixelType == UCHAR) + TypedGenerateData(); + else if (m_PixelType == SSHORT) + TypedGenerateData(); + else if (m_PixelType == USHORT) + TypedGenerateData(); + else if (m_PixelType == UINT) + TypedGenerateData(); + else if (m_PixelType == SINT) + TypedGenerateData(); + else if (m_PixelType == FLOAT) + TypedGenerateData(); + else if (m_PixelType == DOUBLE) + TypedGenerateData(); + else + { + MITK_INFO << "Error while reading raw file: Dimensionality or pixel type not supported or not properly set" + << std::endl; + return; + } + } + else if (m_Dimensionality == 3) + { + if (m_PixelType == SCHAR) + TypedGenerateData(); + else if (m_PixelType == UCHAR) + TypedGenerateData(); + else if (m_PixelType == SSHORT) + TypedGenerateData(); + else if (m_PixelType == USHORT) + TypedGenerateData(); + else if (m_PixelType == UINT) + TypedGenerateData(); + else if (m_PixelType == SINT) + TypedGenerateData(); + else if (m_PixelType == FLOAT) + TypedGenerateData(); + else if (m_PixelType == DOUBLE) + TypedGenerateData(); + else + { + MITK_INFO << "Error while reading raw file: Dimensionality or pixel type not supported or not properly set" + << std::endl; + return; + } + } + else + { + MITK_INFO << "Error while reading raw file: Dimensionality not supported" << std::endl; + return; + } + + MITK_INFO << "...reading raw finished!" << std::endl; +} + +template +void mitk::RawImageFileReader::TypedGenerateData() +{ + mitk::Image::Pointer output = this->GetOutput(); + + if (this->GetOutput() == nullptr) + { + MITK_INFO << "Error" << std::endl; + } + + MITK_INFO << "loading " << m_FileName << " via itk::ImageIOFactory... " << std::endl; + + // Check to see if we can read the file given the name or prefix + if (m_FileName == "") + { + itkWarningMacro(<< "File Type not supported!"); + return; + } + + typedef itk::Image ImageType; + typedef itk::ImageFileReader ReaderType; + typedef itk::RawImageIO IOType; + + typename ReaderType::Pointer reader = ReaderType::New(); + typename IOType::Pointer io = IOType::New(); + + io->SetFileDimensionality(VImageDimensions); + + for (unsigned short int dim = 0; dim < VImageDimensions; ++dim) + { + io->SetDimensions(dim, m_Dimensions[dim]); + } + + if (m_Endianity == LITTLE) + { + io->SetByteOrderToLittleEndian(); + } + else if (m_Endianity == BIG) + { + io->SetByteOrderToBigEndian(); + } + else + { + MITK_INFO << "Warning: endianity not properly set. Resulting image might be incorrect"; + } + + reader->SetImageIO(io); + reader->SetFileName(m_FileName.c_str()); + + try + { + reader->Update(); + } + catch (itk::ExceptionObject &err) + { + MITK_ERROR << "An error occurred during the raw image reading process: "; + MITK_INFO << err << std::endl; + } + + mitk::Image::Pointer image = mitk::Image::New(); + mitk::CastToMitkImage(reader->GetOutput(), image); + output->Initialize(image); + output->SetVolume(reader->GetOutput()->GetBufferPointer()); +} diff --git a/Modules/LegacyIO/mitkRawImageFileReader.h b/Modules/LegacyIO/mitkRawImageFileReader.h new file mode 100644 index 0000000000..96eb588690 --- /dev/null +++ b/Modules/LegacyIO/mitkRawImageFileReader.h @@ -0,0 +1,107 @@ +/*=================================================================== + +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 RawImageFileReader_H_HEADER_INCLUDED +#define RawImageFileReader_H_HEADER_INCLUDED +#include "itkVector.h" +#include "mitkFileReader.h" +#include "mitkImageSource.h" +#include + +namespace mitk +{ + //##Documentation + //## @brief Reader to read raw image files + /** The user must set the dimensionality, the dimensions and the pixel type. If they are incorrect, the image will + * not be opened or the visualization will be incorrect. */ + //## @ingroup MitkLegacyIOModule + //## @deprecatedSince{2014_10} Use mitk::IOUtils or mitk::FileReaderRegistry instead. + class DEPRECATED() MITKLEGACYIO_EXPORT RawImageFileReader : public ImageSource, public FileReader + { + public: + mitkClassMacro(RawImageFileReader, FileReader); + + /** Method for creation through the object factory. */ + itkFactorylessNewMacro(Self) itkCloneMacro(Self) + + itkSetMacro(FileName, std::string); + itkSetStringMacro(FileName); + itkGetMacro(FileName, std::string); + itkGetStringMacro(FileName); + + itkSetMacro(FilePrefix, std::string); + itkSetStringMacro(FilePrefix); + itkGetMacro(FilePrefix, std::string); + itkGetStringMacro(FilePrefix); + + itkSetMacro(FilePattern, std::string); + itkSetStringMacro(FilePattern); + itkGetMacro(FilePattern, std::string); + itkGetStringMacro(FilePattern); + + /** Supported pixel types. */ + typedef enum { UCHAR, SCHAR, USHORT, SSHORT, UINT, SINT, FLOAT, DOUBLE } IOPixelType; + itkSetMacro(PixelType, IOPixelType); + + /** Endianity of bits. */ + typedef enum { LITTLE, BIG } EndianityType; + itkSetMacro(Endianity, EndianityType); + + itkSetMacro(Dimensionality, int); + itkGetMacro(Dimensionality, int); + + /** Image dimensions must be set one by one, starting from dimension 0. */ + void SetDimensions(unsigned int i, unsigned int dim); + + unsigned int GetDimensions(unsigned int i) const; + + static bool CanReadFile(const std::string filename, const std::string filePrefix, const std::string filePattern); + + protected: + RawImageFileReader(); + + ~RawImageFileReader(); + + virtual void GenerateData() override; + + template + void TypedGenerateData(); + + /** Name of file to be read.*/ + std::string m_FileName; + + /** File prefix. */ + std::string m_FilePrefix; + + /** File pattern. */ + std::string m_FilePattern; + + /** Pixel type of image to be read. Must be of type IOPixelType. */ + IOPixelType m_PixelType; + + /** Dimensionality of file to be read. Can be 2 or 3. */ + int m_Dimensionality; + + /** Endianity. Must be set to LITTLE or BIG. Default is BIG. */ + EndianityType m_Endianity; + + /** Vector containing dimensions of image to be read. */ + itk::Vector m_Dimensions; + }; + +} // namespace mitk + +#endif /* RawImageFileReader_H_HEADER_INCLUDED */ diff --git a/Modules/LegacyIO/mitkSTLFileIOFactory.cpp b/Modules/LegacyIO/mitkSTLFileIOFactory.cpp new file mode 100644 index 0000000000..9a8bf69d13 --- /dev/null +++ b/Modules/LegacyIO/mitkSTLFileIOFactory.cpp @@ -0,0 +1,37 @@ +/*=================================================================== + +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 "mitkSTLFileIOFactory.h" +#include "mitkIOAdapter.h" +#include "mitkSTLFileReader.h" + +#include "itkVersion.h" + +namespace mitk +{ + STLFileIOFactory::STLFileIOFactory() + { + this->RegisterOverride("mitkIOAdapter", + "mitkSTLFileReader", + "mitk STL Surface IO", + 1, + itk::CreateObjectFunction>::New()); + } + + STLFileIOFactory::~STLFileIOFactory() {} + const char *STLFileIOFactory::GetITKSourceVersion() const { return ITK_SOURCE_VERSION; } + const char *STLFileIOFactory::GetDescription() const { return "STLFile IO Factory, allows the loading of STL files"; } +} // end namespace mitk diff --git a/Modules/LegacyIO/mitkSTLFileIOFactory.h b/Modules/LegacyIO/mitkSTLFileIOFactory.h new file mode 100644 index 0000000000..89822ed05b --- /dev/null +++ b/Modules/LegacyIO/mitkSTLFileIOFactory.h @@ -0,0 +1,75 @@ +/*=================================================================== + +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 __mitkSTLFileIOFactory_h +#define __mitkSTLFileIOFactory_h + +#ifdef _MSC_VER +#pragma warning(disable : 4786) +#endif + +#include + +#include "itkObjectFactoryBase.h" +#include "mitkBaseData.h" + +namespace mitk +{ + //##Documentation + //## @brief Create instances of STLFileReader objects using an object factory. + //## + //## @ingroup MitkLegacyIOModule + //## @deprecatedSince{2014_10} Use mitk::IOUtils or mitk::FileReaderRegistry instead. + class DEPRECATED() MITKLEGACYIO_EXPORT STLFileIOFactory : public itk::ObjectFactoryBase + { + public: + /** Standard class typedefs. */ + typedef STLFileIOFactory 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 override; + virtual const char *GetDescription(void) const override; + + /** Method for class instantiation. */ + itkFactorylessNewMacro(Self); + static STLFileIOFactory *FactoryNew() { return new STLFileIOFactory; } + /** Run-time type information (and related methods). */ + itkTypeMacro(STLFileIOFactory, ObjectFactoryBase); + + /** + * Register one factory of this type + * \deprecatedSince{2013_09} + */ + DEPRECATED(static void RegisterOneFactory(void)) + { + STLFileIOFactory::Pointer STLFileIOFactory = STLFileIOFactory::New(); + ObjectFactoryBase::RegisterFactory(STLFileIOFactory); + } + + protected: + STLFileIOFactory(); + ~STLFileIOFactory(); + + private: + STLFileIOFactory(const Self &); // purposely not implemented + void operator=(const Self &); // purposely not implemented + }; + +} // end namespace mitk + +#endif diff --git a/Modules/LegacyIO/mitkSTLFileReader.cpp b/Modules/LegacyIO/mitkSTLFileReader.cpp new file mode 100644 index 0000000000..9824a40260 --- /dev/null +++ b/Modules/LegacyIO/mitkSTLFileReader.cpp @@ -0,0 +1,93 @@ +/*=================================================================== + +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 "mitkSTLFileReader.h" +#include +#include +#include +#include +#include +#include + +mitk::STLFileReader::STLFileReader() : mitk::SurfaceSource(), m_FileName("") +{ +} + +mitk::STLFileReader::~STLFileReader() +{ +} + +void mitk::STLFileReader::GenerateData() +{ + mitk::Surface::Pointer output = this->GetOutput(); + + if (m_FileName != "") + { + MITK_INFO("mitkSTLFileReader") << "Loading " << m_FileName << " as stl..." << std::endl; + vtkSmartPointer stlReader = vtkSmartPointer::New(); + stlReader->SetFileName(m_FileName.c_str()); + + vtkSmartPointer normalsGenerator = vtkSmartPointer::New(); + normalsGenerator->SetInputConnection(stlReader->GetOutputPort()); + + vtkSmartPointer cleanPolyDataFilter = vtkSmartPointer::New(); + cleanPolyDataFilter->SetInputConnection(normalsGenerator->GetOutputPort()); + cleanPolyDataFilter->PieceInvariantOff(); + cleanPolyDataFilter->ConvertLinesToPointsOff(); + cleanPolyDataFilter->ConvertPolysToLinesOff(); + cleanPolyDataFilter->ConvertStripsToPolysOff(); + cleanPolyDataFilter->PointMergingOn(); + cleanPolyDataFilter->Update(); + + if ((stlReader->GetOutput() != nullptr) && (cleanPolyDataFilter->GetOutput() != nullptr)) + { + vtkSmartPointer surfaceWithNormals = cleanPolyDataFilter->GetOutput(); + output->SetVtkPolyData(surfaceWithNormals); + } + } +} + +bool mitk::STLFileReader::CanReadFile(const std::string filename, + const std::string /*filePrefix*/, + const std::string /*filePattern*/) +{ + // First check the extension + if (filename == "") + { + // MITK_INFO<<"No filename specified."< + +namespace mitk +{ + //##Documentation + //## @brief Reader to read files in stl-format + //## @ingroup MitkLegacyIOModule + //## @deprecatedSince{2014_10} Use mitk::IOUtils or mitk::FileReaderRegistry instead. + class MITKLEGACYIO_EXPORT STLFileReader : public SurfaceSource + { + public: + mitkClassMacro(STLFileReader, SurfaceSource); + + /** Method for creation through the object factory. */ + itkFactorylessNewMacro(Self) itkCloneMacro(Self) + + itkSetStringMacro(FileName); + itkGetStringMacro(FileName); + + itkSetStringMacro(FilePrefix); + itkGetStringMacro(FilePrefix); + + itkSetStringMacro(FilePattern); + itkGetStringMacro(FilePattern); + + static bool CanReadFile(const std::string filename, const std::string filePrefix, const std::string filePattern); + + protected: + virtual void GenerateData() override; + + STLFileReader(); + + ~STLFileReader(); + + std::string m_FileName, m_FilePrefix, m_FilePattern; + }; + +} // namespace mitk + +#endif /* STLFileReader_H_HEADER_INCLUDED */ diff --git a/Modules/LegacyIO/mitkSurfaceVtkWriter.cpp b/Modules/LegacyIO/mitkSurfaceVtkWriter.cpp new file mode 100644 index 0000000000..f0d59c91b2 --- /dev/null +++ b/Modules/LegacyIO/mitkSurfaceVtkWriter.cpp @@ -0,0 +1,187 @@ +/*=================================================================== + +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 "mitkSurfaceVtkWriter.h" +#include "mitkSurfaceVtkWriter.txx" + +namespace mitk +{ + template <> + void SurfaceVtkWriter::SetDefaultExtension() + { + m_Extension = ".stl"; + m_WriterWriteHasReturnValue = false; + } + + template <> + void SurfaceVtkWriter::SetDefaultExtension() + { + m_Extension = ".vtk"; + m_WriterWriteHasReturnValue = false; + } + + template <> + void SurfaceVtkWriter::SetDefaultExtension() + { + m_Extension = ".vtp"; + m_WriterWriteHasReturnValue = true; + } + + template <> + const char *SurfaceVtkWriter::GetDefaultFilename() + { + return "surface"; + } + + template <> + const char *SurfaceVtkWriter::GetFileDialogPattern() + { + return "STL Surface (*.stl)"; + } + + template <> + const char *SurfaceVtkWriter::GetDefaultExtension() + { + return ".stl"; + } + + template <> + bool SurfaceVtkWriter::CanWriteBaseDataType(BaseData::Pointer data) + { + return dynamic_cast(data.GetPointer()) != nullptr; + } + + template <> + void SurfaceVtkWriter::DoWrite(BaseData::Pointer data) + { + if (this->CanWriteBaseDataType(data)) + { + this->SetInput(data.GetPointer()); + this->Update(); + } + } + + template <> + const char *SurfaceVtkWriter::GetDefaultFilename() + { + return "surface"; + } + + template <> + const char *SurfaceVtkWriter::GetFileDialogPattern() + { + return "VTK Polydata (*.vtk)"; + } + + template <> + const char *SurfaceVtkWriter::GetDefaultExtension() + { + return ".vtk"; + } + + template <> + bool SurfaceVtkWriter::CanWriteBaseDataType(BaseData::Pointer data) + { + return dynamic_cast(data.GetPointer()) != nullptr; + } + + template <> + void SurfaceVtkWriter::DoWrite(BaseData::Pointer data) + { + if (this->CanWriteBaseDataType(data)) + { + this->SetInput(data.GetPointer()); + this->Update(); + } + } + + template <> + const char *SurfaceVtkWriter::GetDefaultFilename() + { + return "surface"; + } + + template <> + const char *SurfaceVtkWriter::GetFileDialogPattern() + { + return "VTK XML Polydata (*.vtp)"; + } + + template <> + const char *SurfaceVtkWriter::GetDefaultExtension() + { + return ".vtp"; + } + + template <> + bool SurfaceVtkWriter::CanWriteBaseDataType(BaseData::Pointer data) + { + return dynamic_cast(data.GetPointer()) != nullptr; + } + + template <> + void SurfaceVtkWriter::DoWrite(BaseData::Pointer data) + { + if (this->CanWriteBaseDataType(data)) + { + this->SetInput(data.GetPointer()); + this->Update(); + } + } + + template <> + void SurfaceVtkWriter::ExecuteWrite(VtkWriterType *vtkWriter) + { + if (vtkWriter->Write() == 0 || vtkWriter->GetErrorCode() != 0) + { + itkExceptionMacro(<< "Error during surface writing: " + << vtkErrorCode::GetStringFromErrorCode(vtkWriter->GetErrorCode())); + } + } + + template <> + std::vector SurfaceVtkWriter::GetPossibleFileExtensions() + { + std::vector possibleFileExtensions; + possibleFileExtensions.push_back(".stl"); + possibleFileExtensions.push_back(".obj"); + return possibleFileExtensions; + } + + template <> + std::vector SurfaceVtkWriter::GetPossibleFileExtensions() + { + std::vector possibleFileExtensions; + possibleFileExtensions.push_back(".vtk"); + possibleFileExtensions.push_back(".obj"); + return possibleFileExtensions; + } + + template <> + std::vector SurfaceVtkWriter::GetPossibleFileExtensions() + { + std::vector possibleFileExtensions; + possibleFileExtensions.push_back(".vtp"); + possibleFileExtensions.push_back(".obj"); + return possibleFileExtensions; + } + + template class SurfaceVtkWriter; + template class SurfaceVtkWriter; + template class SurfaceVtkWriter; +} diff --git a/Modules/LegacyIO/mitkSurfaceVtkWriter.h b/Modules/LegacyIO/mitkSurfaceVtkWriter.h new file mode 100644 index 0000000000..8cc1399230 --- /dev/null +++ b/Modules/LegacyIO/mitkSurfaceVtkWriter.h @@ -0,0 +1,204 @@ +/*=================================================================== + +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_SURFACE_VTK_WRITER__H_ +#define _MITK_SURFACE_VTK_WRITER__H_ + +#include + +#include +#include +#include + +#include +#include +#include +#include +#include + +#include + +class vtkTransformPolyDataFilter; + +namespace mitk +{ + /** + * @brief VTK-based writer for mitk::Surface + * + * The mitk::Surface is written using the VTK-writer-type provided as the + * template argument. If the mitk::Surface contains multiple points of + * time, multiple files are written. The life-span (time-bounds) of each + * each point of time is included in the filename according to the + * following scheme: + * <filename>_S<timebounds[0]>E<timebounds[1]>_T<framenumber> + * (S=start, E=end, T=time). + * Writing of multiple files according to a given filename pattern is not + * yet supported. + * @ingroup MitkLegacyIOModule + * + * @deprecatedSince{2014_10} Use mitk::IOUtils or mitk::FileReaderRegistry instead. + */ + template + class MITKLEGACYIO_EXPORT SurfaceVtkWriter : public mitk::FileWriterWithInformation + { + public: + mitkClassMacro(SurfaceVtkWriter, mitk::FileWriter); + + itkFactorylessNewMacro(Self) itkCloneMacro(Self) + + mitkWriterMacro; + + typedef VTKWRITER VtkWriterType; + + /** + * 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); + + /** + * \brief Explicitly set the extension to be added to the filename. + * @param _arg to be added to the filename, including a "." + * (e.g., ".vtk"). + * + * Partial template specialization is used for some vtk-writer types + * to set a default extension. + */ + itkSetStringMacro(Extension); + + /** + * \brief Get the extension to be added to the filename. + * @returns the extension to be added to the filename (e.g., + * ".vtk"). + */ + itkGetStringMacro(Extension); + + /** + * \brief Set the extension to be added to the filename to the default + * + * Partial template specialization is used for some vtk-writer types + * to define the default extension. + */ + void SetDefaultExtension(); + + /** + * @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 0'th input object for the filter. + * @param input the first input for the filter. + */ + void SetInput(mitk::Surface *input); + + /** + * @returns the 0'th input object of the filter. + */ + const mitk::Surface *GetInput(); + + /** + * @brief Return the extension to be added to the filename. + */ + virtual std::string GetFileExtension() override; + + /** + * @brief Check if the Writer can write the Content of the DataTreenode. + */ + virtual bool CanWriteDataType(DataNode *) override; + + /** + * @brief Return the MimeType of the saved File. + */ + virtual std::string GetWritenMIMEType() override; + + using Superclass::SetInput; + /** + * @brief Set the DataTreenode as Input. Important: The Writer always have a SetInput-Function. + */ + virtual void SetInput(DataNode *); + + VtkWriterType *GetVtkWriter() { return m_VtkWriter; } + /** + * @brief Return the possible file extensions for the data type associated with the writer + */ + virtual std::vector GetPossibleFileExtensions() override; + + virtual std::string GetSupportedBaseData() const override { return Surface::GetStaticNameOfClass(); } + virtual const char *GetDefaultFilename() override; + virtual const char *GetFileDialogPattern() override; + virtual const char *GetDefaultExtension() override; + virtual bool CanWriteBaseDataType(BaseData::Pointer data) override; + virtual void DoWrite(BaseData::Pointer data) override; + + protected: + /** + * Constructor. + */ + SurfaceVtkWriter(); + + /** + * Virtual destructor. + */ + virtual ~SurfaceVtkWriter(); + + virtual void GenerateData() override; + + void ExecuteWrite(VtkWriterType *vtkWriter); + + std::string m_FileName; + + std::string m_FilePrefix; + + std::string m_FilePattern; + + std::string m_Extension; + + std::string m_MimeType; + + vtkSmartPointer m_VtkWriter; + + bool m_WriterWriteHasReturnValue; + }; + +#ifndef MitkLegacyIO_EXPORTS + extern template class SurfaceVtkWriter; + extern template class SurfaceVtkWriter; + extern template class SurfaceVtkWriter; +#endif +} + +#endif //_MITK_SURFACE_VTK_WRITER__H_ diff --git a/Modules/LegacyIO/mitkSurfaceVtkWriter.txx b/Modules/LegacyIO/mitkSurfaceVtkWriter.txx new file mode 100644 index 0000000000..c3915a7a86 --- /dev/null +++ b/Modules/LegacyIO/mitkSurfaceVtkWriter.txx @@ -0,0 +1,175 @@ +/*=================================================================== + +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 "mitkSurfaceVtkWriter.h" +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +template +mitk::SurfaceVtkWriter::SurfaceVtkWriter() : m_WriterWriteHasReturnValue(false) +{ + this->SetNumberOfRequiredInputs(1); + + m_VtkWriter = vtkSmartPointer::New(); + + // enable to write ascii-formatted-file + // m_VtkWriter->SetFileTypeToASCII(); + + SetDefaultExtension(); // and information about the Writer's Write() method +} + +template +mitk::SurfaceVtkWriter::~SurfaceVtkWriter() +{ +} + +template +void mitk::SurfaceVtkWriter::SetDefaultExtension() +{ + m_Extension = ".vtk"; +} + +template +void mitk::SurfaceVtkWriter::ExecuteWrite(VtkWriterType *vtkWriter) +{ + if (vtkWriter->Write() == 0 || vtkWriter->GetErrorCode() != 0) + { + itkExceptionMacro(<< "Error during surface writing: " + << vtkErrorCode::GetStringFromErrorCode(vtkWriter->GetErrorCode())); + } +} + +template +void mitk::SurfaceVtkWriter::GenerateData() +{ + if (m_FileName == "") + { + itkWarningMacro(<< "Sorry, filename has not been set!"); + return; + } + + mitk::Surface::Pointer input = const_cast(this->GetInput()); + + vtkSmartPointer transformPolyData = vtkSmartPointer::New(); + vtkPolyData *polyData; + BaseGeometry *geometry; + + unsigned int t, timesteps = input->GetTimeGeometry()->CountTimeSteps(); + + for (t = 0; t < timesteps; ++t) + { + // surfaces do not have to exist in all timeteps; therefor, only write valid surfaces + if (input->GetVtkPolyData(t) == nullptr) + continue; + + std::ostringstream filename; + filename.imbue(::std::locale::classic()); + geometry = input->GetGeometry(t); + if (timesteps > 1) + { + if (input->GetTimeGeometry()->IsValidTimeStep(t)) + { + const TimeBounds &timebounds = input->GetTimeGeometry()->GetTimeBounds(t); + filename << m_FileName.c_str() << "_S" << std::setprecision(0) << timebounds[0] << "_E" << std::setprecision(0) + << timebounds[1] << "_T" << t << m_Extension; + } + else + { + itkWarningMacro(<< "Error on write: TimeGeometry invalid of surface " << filename.str() << "."); + filename << m_FileName.c_str() << "_T" << t << m_Extension; + } + m_VtkWriter->SetFileName(filename.str().c_str()); + } + else + m_VtkWriter->SetFileName(m_FileName.c_str()); + + transformPolyData->SetInputData(input->GetVtkPolyData(t)); + transformPolyData->SetTransform(geometry->GetVtkTransform()); + transformPolyData->UpdateWholeExtent(); + polyData = transformPolyData->GetOutput(); + + m_VtkWriter->SetInputData(polyData); + + ExecuteWrite(m_VtkWriter); + } + + m_MimeType = "application/MITK.Surface"; +} + +template +void mitk::SurfaceVtkWriter::SetInput(mitk::Surface *surface) +{ + this->ProcessObject::SetNthInput(0, surface); +} + +template +const mitk::Surface *mitk::SurfaceVtkWriter::GetInput() +{ + if (this->GetNumberOfInputs() < 1) + { + return nullptr; + } + else + { + return static_cast(this->ProcessObject::GetInput(0)); + } +} + +template +bool mitk::SurfaceVtkWriter::CanWriteDataType(DataNode *input) +{ + if (input) + { + BaseData *data = input->GetData(); + if (data) + { + Surface::Pointer surface = dynamic_cast(data); + if (surface.IsNotNull()) + { + SetDefaultExtension(); + return true; + } + } + } + return false; +} + +template +void mitk::SurfaceVtkWriter::SetInput(DataNode *input) +{ + if (input && CanWriteDataType(input)) + SetInput(dynamic_cast(input->GetData())); +} + +template +std::string mitk::SurfaceVtkWriter::GetWritenMIMEType() +{ + return m_MimeType; +} + +template +std::string mitk::SurfaceVtkWriter::GetFileExtension() +{ + return m_Extension; +} diff --git a/Modules/LegacyIO/mitkSurfaceVtkWriterFactory.cpp b/Modules/LegacyIO/mitkSurfaceVtkWriterFactory.cpp new file mode 100644 index 0000000000..b16f7ed086 --- /dev/null +++ b/Modules/LegacyIO/mitkSurfaceVtkWriterFactory.cpp @@ -0,0 +1,64 @@ +/*=================================================================== + +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 "mitkSurfaceVtkWriterFactory.h" + +#include "itkCreateObjectFunction.h" +#include "itkVersion.h" + +#include +#include + +namespace mitk +{ + template + class CreateSurfaceWriter : public itk::CreateObjectFunctionBase + { + public: + /** Standard class typedefs. */ + typedef CreateSurfaceWriter Self; + typedef itk::SmartPointer Pointer; + + /** Methods from itk:LightObject. */ + itkFactorylessNewMacro(Self); + LightObject::Pointer CreateObject() override + { + typename T::Pointer p = T::New(); + p->Register(); + return p.GetPointer(); + } + + protected: + CreateSurfaceWriter() {} + ~CreateSurfaceWriter() override {} + private: + CreateSurfaceWriter(const Self &); // purposely not implemented + void operator=(const Self &); // purposely not implemented + }; + + SurfaceVtkWriterFactory::SurfaceVtkWriterFactory() + { + this->RegisterOverride("IOWriter", + "SurfaceVtkWriter", + "Surface Vtk Writer", + 1, + mitk::CreateSurfaceWriter>::New()); + } + + SurfaceVtkWriterFactory::~SurfaceVtkWriterFactory() {} + const char *SurfaceVtkWriterFactory::GetITKSourceVersion() const { return ITK_SOURCE_VERSION; } + const char *SurfaceVtkWriterFactory::GetDescription() const { return "SurfaceVtkWriterFactory"; } +} // end namespace mitk diff --git a/Modules/LegacyIO/mitkSurfaceVtkWriterFactory.h b/Modules/LegacyIO/mitkSurfaceVtkWriterFactory.h new file mode 100644 index 0000000000..2ef03f1426 --- /dev/null +++ b/Modules/LegacyIO/mitkSurfaceVtkWriterFactory.h @@ -0,0 +1,68 @@ +/*=================================================================== + +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 SURFACEWRITERFACTORY_H_HEADER_INCLUDED +#define SURFACEWRITERFACTORY_H_HEADER_INCLUDED + +#include + +#include "itkObjectFactoryBase.h" +#include "mitkBaseData.h" + +namespace mitk +{ + /** + * @deprecatedSince{2014_10} Use mitk::IOUtils or mitk::FileReaderRegistry instead. + */ + class DEPRECATED() MITKLEGACYIO_EXPORT SurfaceVtkWriterFactory : public itk::ObjectFactoryBase + { + public: + mitkClassMacroItkParent(mitk::SurfaceVtkWriterFactory, itk::ObjectFactoryBase) + + /** Class methods used to interface with the registered factories. */ + virtual const char *GetITKSourceVersion(void) const override; + virtual const char *GetDescription(void) const override; + + /** Method for class instantiation. */ + itkFactorylessNewMacro(Self); + + /** + * Register one factory of this type + * \deprecatedSince{2013_09} + */ + DEPRECATED(static void RegisterOneFactory(void)) + { + static bool IsRegistered = false; + if (!IsRegistered) + { + SurfaceVtkWriterFactory::Pointer surfaceVtkWriterFactory = SurfaceVtkWriterFactory::New(); + ObjectFactoryBase::RegisterFactory(surfaceVtkWriterFactory); + IsRegistered = true; + } + } + + protected: + SurfaceVtkWriterFactory(); + ~SurfaceVtkWriterFactory(); + + private: + SurfaceVtkWriterFactory(const Self &); // purposely not implemented + void operator=(const Self &); // purposely not implemented + }; + +} // end namespace mitk + +#endif diff --git a/Modules/LegacyIO/mitkVtiFileIOFactory.cpp b/Modules/LegacyIO/mitkVtiFileIOFactory.cpp new file mode 100644 index 0000000000..1f81b07505 --- /dev/null +++ b/Modules/LegacyIO/mitkVtiFileIOFactory.cpp @@ -0,0 +1,37 @@ +/*=================================================================== + +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 "mitkVtiFileIOFactory.h" +#include "mitkIOAdapter.h" +#include "mitkVtiFileReader.h" + +#include "itkVersion.h" + +namespace mitk +{ + VtiFileIOFactory::VtiFileIOFactory() + { + this->RegisterOverride("mitkIOAdapter", + "mitkVtiFileReader", + "mitk Vti Image IO", + 1, + itk::CreateObjectFunction>::New()); + } + + VtiFileIOFactory::~VtiFileIOFactory() {} + const char *VtiFileIOFactory::GetITKSourceVersion() const { return ITK_SOURCE_VERSION; } + const char *VtiFileIOFactory::GetDescription() const { return "VtiFile IO Factory, allows the loading of vti files"; } +} // end namespace mitk diff --git a/Modules/LegacyIO/mitkVtiFileIOFactory.h b/Modules/LegacyIO/mitkVtiFileIOFactory.h new file mode 100644 index 0000000000..4e819e89a7 --- /dev/null +++ b/Modules/LegacyIO/mitkVtiFileIOFactory.h @@ -0,0 +1,75 @@ +/*=================================================================== + +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 __mitkVtiFileIOFactory_h +#define __mitkVtiFileIOFactory_h + +#ifdef _MSC_VER +#pragma warning(disable : 4786) +#endif + +#include + +#include "itkObjectFactoryBase.h" +#include "mitkBaseData.h" + +namespace mitk +{ + //##Documentation + //## @brief Create instances of VtiFileReader objects using an object factory. + //## + //## @ingroup MitkLegacyIOModule + //## @deprecatedSince{2014_10} Use mitk::IOUtils or mitk::FileReaderRegistry instead. + class DEPRECATED() MITKLEGACYIO_EXPORT VtiFileIOFactory : public itk::ObjectFactoryBase + { + public: + /** Standard class typedefs. */ + typedef VtiFileIOFactory 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 override; + virtual const char *GetDescription(void) const override; + + /** Method for class instantiation. */ + itkFactorylessNewMacro(Self); + static VtiFileIOFactory *FactoryNew() { return new VtiFileIOFactory; } + /** Run-time type information (and related methods). */ + itkTypeMacro(VtiFileIOFactory, ObjectFactoryBase); + + /** + * Register one factory of this type + * \deprecatedSince{2013_09} + */ + DEPRECATED(static void RegisterOneFactory(void)) + { + VtiFileIOFactory::Pointer VtiFileIOFactory = VtiFileIOFactory::New(); + ObjectFactoryBase::RegisterFactory(VtiFileIOFactory); + } + + protected: + VtiFileIOFactory(); + ~VtiFileIOFactory(); + + private: + VtiFileIOFactory(const Self &); // purposely not implemented + void operator=(const Self &); // purposely not implemented + }; + +} // end namespace mitk + +#endif diff --git a/Modules/LegacyIO/mitkVtiFileReader.cpp b/Modules/LegacyIO/mitkVtiFileReader.cpp new file mode 100644 index 0000000000..62de994504 --- /dev/null +++ b/Modules/LegacyIO/mitkVtiFileReader.cpp @@ -0,0 +1,69 @@ +/*=================================================================== + +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 "mitkVtiFileReader.h" + +#include +#include + +mitk::VtiFileReader::VtiFileReader() : m_FileName(""), m_FilePrefix(""), m_FilePattern("") +{ +} + +mitk::VtiFileReader::~VtiFileReader() +{ +} + +void mitk::VtiFileReader::GenerateData() +{ + if (m_FileName != "") + { + vtkXMLImageDataReader *vtkReader = vtkXMLImageDataReader::New(); + vtkReader->SetFileName(m_FileName.c_str()); + vtkReader->Update(); + + if (vtkReader->GetOutput() != nullptr) + { + mitk::Image::Pointer output = this->GetOutput(); + output->Initialize(vtkReader->GetOutput()); + output->SetVolume(vtkReader->GetOutput()->GetScalarPointer()); + } + vtkReader->Delete(); + } +} + +bool mitk::VtiFileReader::CanReadFile(const std::string filename, + const std::string /*filePrefix*/, + const std::string /*filePattern*/) +{ + // First check the extension + if (filename == "") + return false; + + bool extensionFound = false; + std::string::size_type VTIPos = filename.rfind(".vti"); + if ((VTIPos != std::string::npos) && (VTIPos == filename.length() - 4)) + extensionFound = true; + + VTIPos = filename.rfind(".VTI"); + if ((VTIPos != std::string::npos) && (VTIPos == filename.length() - 4)) + extensionFound = true; + + if (!extensionFound) + return false; + + return true; +} diff --git a/Modules/LegacyIO/mitkVtiFileReader.h b/Modules/LegacyIO/mitkVtiFileReader.h new file mode 100644 index 0000000000..1f47f7abf3 --- /dev/null +++ b/Modules/LegacyIO/mitkVtiFileReader.h @@ -0,0 +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 VtiFileReader_H_HEADER_INCLUDED +#define VtiFileReader_H_HEADER_INCLUDED + +#include "mitkFileReader.h" +#include "mitkImageSource.h" +#include + +namespace mitk +{ + //##Documentation + //## @brief Reader to read image files in vtk file format + //## @ingroup MitkLegacyIOModule + //## @deprecatedSince{2014_10} Use mitk::IOUtils or mitk::FileReaderRegistry instead. + class DEPRECATED() MITKLEGACYIO_EXPORT VtiFileReader : public ImageSource, public FileReader + { + public: + mitkClassMacro(VtiFileReader, FileReader); + + /** Method for creation through the object factory. */ + itkFactorylessNewMacro(Self) itkCloneMacro(Self) + + itkSetStringMacro(FileName); + itkGetStringMacro(FileName); + + itkSetStringMacro(FilePrefix); + itkGetStringMacro(FilePrefix); + + itkSetStringMacro(FilePattern); + itkGetStringMacro(FilePattern); + + static bool CanReadFile(const std::string filename, const std::string filePrefix, const std::string filePattern); + + protected: + VtiFileReader(); + + ~VtiFileReader(); + + virtual void GenerateData() override; + + //##Description + //## @brief Time when Header was last read + // itk::TimeStamp m_ReadHeaderTime; + + protected: + std::string m_FileName; + + std::string m_FilePrefix; + + std::string m_FilePattern; + }; + +} // namespace mitk + +#endif /* VtiFileReader_H_HEADER_INCLUDED */ diff --git a/Modules/LegacyIO/mitkVtkImageIOFactory.cpp b/Modules/LegacyIO/mitkVtkImageIOFactory.cpp new file mode 100644 index 0000000000..7b7745f969 --- /dev/null +++ b/Modules/LegacyIO/mitkVtkImageIOFactory.cpp @@ -0,0 +1,41 @@ +/*=================================================================== + +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 "mitkVtkImageIOFactory.h" +#include "mitkIOAdapter.h" +#include "mitkVtkImageReader.h" + +#include "itkVersion.h" + +namespace mitk +{ + VtkImageIOFactory::VtkImageIOFactory() + { + this->RegisterOverride("mitkIOAdapter", + "mitkVtkImageReader", + "mitk Vtk Image IO", + 1, + itk::CreateObjectFunction>::New()); + } + + VtkImageIOFactory::~VtkImageIOFactory() {} + const char *VtkImageIOFactory::GetITKSourceVersion() const { return ITK_SOURCE_VERSION; } + const char *VtkImageIOFactory::GetDescription() const + { + return "VtkImage IO Factory, allows the loading of pvtk files"; + } + +} // end namespace mitk diff --git a/Modules/LegacyIO/mitkVtkImageIOFactory.h b/Modules/LegacyIO/mitkVtkImageIOFactory.h new file mode 100644 index 0000000000..3430f389ae --- /dev/null +++ b/Modules/LegacyIO/mitkVtkImageIOFactory.h @@ -0,0 +1,75 @@ +/*=================================================================== + +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 __mitkVtkImageIOFactory_h +#define __mitkVtkImageIOFactory_h + +#ifdef _MSC_VER +#pragma warning(disable : 4786) +#endif + +#include + +#include "itkObjectFactoryBase.h" +#include "mitkBaseData.h" + +namespace mitk +{ + //##Documentation + //## @brief Create instances of VtkImageReader objects using an object factory. + //## + //## @ingroup MitkLegacyIOModule + //## @deprecatedSince{2014_10} Use mitk::IOUtils or mitk::FileReaderRegistry instead. + class DEPRECATED() MITKLEGACYIO_EXPORT VtkImageIOFactory : public itk::ObjectFactoryBase + { + public: + /** Standard class typedefs. */ + typedef VtkImageIOFactory 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 override; + virtual const char *GetDescription(void) const override; + + /** Method for class instantiation. */ + itkFactorylessNewMacro(Self); + static VtkImageIOFactory *FactoryNew() { return new VtkImageIOFactory; } + /** Run-time type information (and related methods). */ + itkTypeMacro(VtkImageIOFactory, ObjectFactoryBase); + + /** + * Register one factory of this type + * \deprecatedSince{2013_09} + */ + DEPRECATED(static void RegisterOneFactory(void)) + { + VtkImageIOFactory::Pointer VtkImageIOFactory = VtkImageIOFactory::New(); + ObjectFactoryBase::RegisterFactory(VtkImageIOFactory); + } + + protected: + VtkImageIOFactory(); + ~VtkImageIOFactory(); + + private: + VtkImageIOFactory(const Self &); // purposely not implemented + void operator=(const Self &); // purposely not implemented + }; + +} // end namespace mitk + +#endif diff --git a/Modules/LegacyIO/mitkVtkImageReader.cpp b/Modules/LegacyIO/mitkVtkImageReader.cpp new file mode 100644 index 0000000000..3a2fd3c028 --- /dev/null +++ b/Modules/LegacyIO/mitkVtkImageReader.cpp @@ -0,0 +1,97 @@ +/*=================================================================== + +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 "mitkVtkImageReader.h" + +#include +#include +#include + +mitk::VtkImageReader::VtkImageReader() : m_FileName(""), m_FilePrefix(""), m_FilePattern("") +{ +} + +mitk::VtkImageReader::~VtkImageReader() +{ +} + +void mitk::VtkImageReader::GenerateData() +{ + if (m_FileName != "") + { + MITK_INFO << "Loading " << m_FileName << " as vtk" << std::endl; + + /// We create a Generic Reader to test de .vtk/ + vtkDataReader *chooser = vtkDataReader::New(); + chooser->SetFileName(m_FileName.c_str()); + + if (chooser->IsFileStructuredPoints()) + { + /// StructuredPoints/ + MITK_INFO << "StructuredPoints" << std::endl; + vtkStructuredPointsReader *reader = vtkStructuredPointsReader::New(); + reader->SetFileName(m_FileName.c_str()); + reader->Update(); + + if (reader->GetOutput() != nullptr) + { + mitk::Image::Pointer output = this->GetOutput(); + output->Initialize(reader->GetOutput()); + output->SetVolume(reader->GetOutput()->GetScalarPointer()); + } + reader->Delete(); + } + else + { + MITK_ERROR << " ... sorry, this .vtk format is not supported yet." << std::endl; + } + chooser->Delete(); + } +} + +bool mitk::VtkImageReader::CanReadFile(const std::string filename, + const std::string /*filePrefix*/, + const std::string /*filePattern*/) +{ + // First check the extension + if (filename == "") + return false; + + bool extensionFound = false; + std::string::size_type PVTKPos = filename.rfind(".pvtk"); + if ((PVTKPos != std::string::npos) && (PVTKPos == filename.length() - 5)) + { + extensionFound = true; + } + + PVTKPos = filename.rfind(".PVTK"); + if ((PVTKPos != std::string::npos) && (PVTKPos == filename.length() - 5)) + { + extensionFound = true; + } + + if (extensionFound) + { + vtkDataReader *chooser = vtkDataReader::New(); + chooser->SetFileName(filename.c_str()); + if (!chooser->IsFileStructuredPoints()) + return false; + } + else + return false; + + return true; +} diff --git a/Modules/LegacyIO/mitkVtkImageReader.h b/Modules/LegacyIO/mitkVtkImageReader.h new file mode 100644 index 0000000000..54970eafb2 --- /dev/null +++ b/Modules/LegacyIO/mitkVtkImageReader.h @@ -0,0 +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 VtkImageReader_H_HEADER_INCLUDED +#define VtkImageReader_H_HEADER_INCLUDED + +#include "mitkFileReader.h" +#include "mitkImageSource.h" +#include + +namespace mitk +{ + //##Documentation + //## @brief Reader to read image files in vtk file format + //## @ingroup MitkLegacyIOModule + //## @deprecatedSince{2014_10} Use mitk::IOUtils or mitk::FileReaderRegistry instead. + class DEPRECATED() MITKLEGACYIO_EXPORT VtkImageReader : public ImageSource, public FileReader + { + public: + mitkClassMacro(VtkImageReader, FileReader); + + /** Method for creation through the object factory. */ + itkFactorylessNewMacro(Self) itkCloneMacro(Self) + + itkSetStringMacro(FileName); + itkGetStringMacro(FileName); + + itkSetStringMacro(FilePrefix); + itkGetStringMacro(FilePrefix); + + itkSetStringMacro(FilePattern); + itkGetStringMacro(FilePattern); + + static bool CanReadFile(const std::string filename, const std::string filePrefix, const std::string filePattern); + + protected: + VtkImageReader(); + + ~VtkImageReader(); + + virtual void GenerateData() override; + + //##Description + //## @brief Time when Header was last read + // itk::TimeStamp m_ReadHeaderTime; + + protected: + std::string m_FileName; + + std::string m_FilePrefix; + + std::string m_FilePattern; + }; + +} // namespace mitk + +#endif /* VtkImageReader_H_HEADER_INCLUDED */ diff --git a/Modules/LegacyIO/mitkVtkSurfaceIOFactory.cpp b/Modules/LegacyIO/mitkVtkSurfaceIOFactory.cpp new file mode 100644 index 0000000000..7d9cab57cc --- /dev/null +++ b/Modules/LegacyIO/mitkVtkSurfaceIOFactory.cpp @@ -0,0 +1,41 @@ +/*=================================================================== + +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 "mitkVtkSurfaceIOFactory.h" +#include "mitkIOAdapter.h" +#include "mitkVtkSurfaceReader.h" + +#include "itkVersion.h" + +namespace mitk +{ + VtkSurfaceIOFactory::VtkSurfaceIOFactory() + { + this->RegisterOverride("mitkIOAdapter", + "mitkVtkSurfaceReader", + "mitk Vtk Surface IO", + 1, + itk::CreateObjectFunction>::New()); + } + + VtkSurfaceIOFactory::~VtkSurfaceIOFactory() {} + const char *VtkSurfaceIOFactory::GetITKSourceVersion() const { return ITK_SOURCE_VERSION; } + const char *VtkSurfaceIOFactory::GetDescription() const + { + return "VtkSurface IO Factory, allows the loading of Vtk files"; + } + +} // end namespace mitk diff --git a/Modules/LegacyIO/mitkVtkSurfaceIOFactory.h b/Modules/LegacyIO/mitkVtkSurfaceIOFactory.h new file mode 100644 index 0000000000..d1ea0022cd --- /dev/null +++ b/Modules/LegacyIO/mitkVtkSurfaceIOFactory.h @@ -0,0 +1,75 @@ +/*=================================================================== + +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 __mitkVtkSurfaceIOFactory_h +#define __mitkVtkSurfaceIOFactory_h + +#ifdef _MSC_VER +#pragma warning(disable : 4786) +#endif + +#include + +#include "itkObjectFactoryBase.h" +#include "mitkBaseData.h" + +namespace mitk +{ + //##Documentation + //## @brief Create instances of VtkSurfaceReader objects using an object factory. + //## + //## @ingroup MitkLegacyIOModule + //## @deprecatedSince{2014_10} Use mitk::IOUtils or mitk::FileReaderRegistry instead. + class DEPRECATED() MITKLEGACYIO_EXPORT VtkSurfaceIOFactory : public itk::ObjectFactoryBase + { + public: + /** Standard class typedefs. */ + typedef VtkSurfaceIOFactory 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 override; + virtual const char *GetDescription(void) const override; + + /** Method for class instantiation. */ + itkFactorylessNewMacro(Self); + static VtkSurfaceIOFactory *FactoryNew() { return new VtkSurfaceIOFactory; } + /** Run-time type information (and related methods). */ + itkTypeMacro(VtkSurfaceIOFactory, ObjectFactoryBase); + + /** + * Register one factory of this type + * \deprecatedSince{2013_09} + */ + DEPRECATED(static void RegisterOneFactory(void)) + { + VtkSurfaceIOFactory::Pointer VtkSurfaceIOFactory = VtkSurfaceIOFactory::New(); + ObjectFactoryBase::RegisterFactory(VtkSurfaceIOFactory); + } + + protected: + VtkSurfaceIOFactory(); + ~VtkSurfaceIOFactory(); + + private: + VtkSurfaceIOFactory(const Self &); // purposely not implemented + void operator=(const Self &); // purposely not implemented + }; + +} // end namespace mitk + +#endif diff --git a/Modules/LegacyIO/mitkVtkSurfaceReader.cpp b/Modules/LegacyIO/mitkVtkSurfaceReader.cpp new file mode 100644 index 0000000000..60ca830eba --- /dev/null +++ b/Modules/LegacyIO/mitkVtkSurfaceReader.cpp @@ -0,0 +1,124 @@ +/*=================================================================== + +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 "mitkVtkSurfaceReader.h" +#include +#include +#include +#include +#include + +mitk::VtkSurfaceReader::VtkSurfaceReader() : m_FileName("") +{ +} + +mitk::VtkSurfaceReader::~VtkSurfaceReader() +{ +} + +void mitk::VtkSurfaceReader::GenerateData() +{ + if (m_FileName != "") + { + bool success = false; + MITK_INFO << "Loading " << m_FileName << " as vtk" << std::endl; + + std::string ext = itksys::SystemTools::GetFilenameLastExtension(m_FileName); + ext = itksys::SystemTools::LowerCase(ext); + if (ext == ".vtk") + { + /// We create a Generic Reader to test de .vtk/ + vtkDataReader *chooser = vtkDataReader::New(); + chooser->SetFileName(m_FileName.c_str()); + if (chooser->IsFilePolyData()) + { + /// PolyData/ + itkDebugMacro(<< "PolyData"); + vtkPolyDataReader *reader = vtkPolyDataReader::New(); + reader->SetFileName(m_FileName.c_str()); + reader->Update(); + + if (reader->GetOutput() != nullptr) + { + mitk::Surface::Pointer output = this->GetOutput(); + output->SetVtkPolyData(reader->GetOutput()); + success = true; + } + reader->Delete(); + } + chooser->Delete(); + } + else if (ext == ".vtp") + { + vtkXMLPolyDataReader *reader = vtkXMLPolyDataReader::New(); + if (reader->CanReadFile(m_FileName.c_str())) + { + /// PolyData/ + itkDebugMacro(<< "XMLPolyData"); + reader->SetFileName(m_FileName.c_str()); + reader->Update(); + + if (reader->GetOutput() != nullptr) + { + mitk::Surface::Pointer output = this->GetOutput(); + output->SetVtkPolyData(reader->GetOutput()); + success = true; + } + reader->Delete(); + } + } + if (!success) + { + itkWarningMacro(<< " ... sorry, this .vtk format is not supported yet."); + } + } +} + +bool mitk::VtkSurfaceReader::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 == ".vtk") + { + vtkDataReader *chooser = vtkDataReader::New(); + chooser->SetFileName(filename.c_str()); + if (!chooser->IsFilePolyData()) + { + chooser->Delete(); + return false; + } + chooser->Delete(); + } + else if (ext == ".vtp") + { + vtkXMLPolyDataReader *chooser = vtkXMLPolyDataReader::New(); + if (!chooser->CanReadFile(filename.c_str())) + { + chooser->Delete(); + return false; + } + chooser->Delete(); + } + else + return false; + + return true; +} diff --git a/Modules/LegacyIO/mitkVtkSurfaceReader.h b/Modules/LegacyIO/mitkVtkSurfaceReader.h new file mode 100644 index 0000000000..1f4ede0084 --- /dev/null +++ b/Modules/LegacyIO/mitkVtkSurfaceReader.h @@ -0,0 +1,59 @@ +/*=================================================================== + +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 VtkSurfaceReader_H_HEADER_INCLUDED +#define VtkSurfaceReader_H_HEADER_INCLUDED + +#include "mitkSurfaceSource.h" +#include + +namespace mitk +{ + //##Documentation + //## @brief Reader to read surface files in vtk-format + //## @ingroup MitkLegacyIOModule + //## @deprecatedSince{2014_10} Use mitk::IOUtils or mitk::FileReaderRegistry instead. + class MITKLEGACYIO_EXPORT VtkSurfaceReader : public SurfaceSource + { + public: + mitkClassMacro(VtkSurfaceReader, SurfaceSource); + + /** Method for creation through the object factory. */ + itkFactorylessNewMacro(Self) itkCloneMacro(Self) + + itkSetStringMacro(FileName); + itkGetStringMacro(FileName); + + itkSetStringMacro(FilePrefix); + itkGetStringMacro(FilePrefix); + + itkSetStringMacro(FilePattern); + itkGetStringMacro(FilePattern); + + static bool CanReadFile(const std::string filename, const std::string filePrefix, const std::string filePattern); + + protected: + virtual void GenerateData() override; + + VtkSurfaceReader(); + + ~VtkSurfaceReader(); + + std::string m_FileName, m_FilePrefix, m_FilePattern; + }; + +} // namespace mitk + +#endif /* VtkSurfaceReader_H_HEADER_INCLUDED */ diff --git a/Modules/LegacyIO/vtkPointSetXMLParser.cpp b/Modules/LegacyIO/vtkPointSetXMLParser.cpp new file mode 100644 index 0000000000..cf1a4f130c --- /dev/null +++ b/Modules/LegacyIO/vtkPointSetXMLParser.cpp @@ -0,0 +1,185 @@ +/*=================================================================== + +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 "vtkPointSetXMLParser.h" +#include "mitkInteractionConst.h" +#include "mitkOperation.h" +#include "mitkPointOperation.h" +#include "mitkPointSetWriter.h" +#include "vtkObjectFactory.h" + +namespace mitk +{ + vtkStandardNewMacro(vtkPointSetXMLParser); +} + +mitk::vtkPointSetXMLParser::vtkPointSetXMLParser() +{ +} + +mitk::vtkPointSetXMLParser::~vtkPointSetXMLParser() +{ +} + +int mitk::vtkPointSetXMLParser::InitializeParser() +{ + vtkXMLParser::InitializeParser(); + std::istream *stream = this->GetStream(); + if (!stream) + { + vtkErrorMacro("no stream available in XML file reader"); + this->ParseError = 1; + return 0; + } + m_PreviousLocale = stream->getloc(); + std::locale I("C"); + stream->imbue(I); + return 1; +} + +int mitk::vtkPointSetXMLParser::CleanupParser() +{ + std::istream *stream = this->GetStream(); + if (!stream) + { + vtkErrorMacro("no stream available in XML file reader"); + this->ParseError = 1; + return 0; + } + stream->imbue(m_PreviousLocale); + vtkXMLParser::CleanupParser(); + return 1; +} + +void mitk::vtkPointSetXMLParser::StartElement(const char *name, const char ** /*atts */) +{ + std::string currentElement = name; + // + // when a new point set begins in the file, create a new + // mitk::point set and store it in m_PointSetList + // + if (currentElement == mitk::PointSetWriter::XML_POINT_SET) + { + m_CurrentPointSet = PointSetType::New(); + } + // + // when a new point begins, initialize it to zero. + // + else if (currentElement == mitk::PointSetWriter::XML_POINT) + { + m_CurrentPoint[0] = 0.0f; + m_CurrentPoint[1] = 0.0f; + m_CurrentPoint[2] = 0.0f; + m_CurId.clear(); + m_CurXString.clear(); + m_CurYString.clear(); + m_CurZString.clear(); + } + + // + // the current element is pushed on to the stack + // to be able to detect some errors in the xml file + // + m_ParseStack.push(currentElement); +} + +void mitk::vtkPointSetXMLParser::EndElement(const char *name) +{ + std::string currentElement = name; + + // + // make sure, that the current end element matches with the + // last start tag + // + if (m_ParseStack.top() != currentElement) + { + MITK_ERROR << "Top of parse stack ( " << m_ParseStack.top() << " ) is != currentEndElement ( " << currentElement + << " )!" << std::endl; + } + m_ParseStack.pop(); + + // + // After a complete point set has been parsed, its + // output information is updated and it is inserted into the list + // of parsed point sets. + // + if (currentElement == mitk::PointSetWriter::XML_POINT_SET) + { + m_CurrentPointSet->UpdateOutputInformation(); + m_PointSetList.push_back(m_CurrentPointSet); + } + // + // if we have finished parsing a point, insert it to the current + // point set. + // + else if (currentElement == mitk::PointSetWriter::XML_POINT) + { + m_CurrentPointId = ParsePointIdentifier(m_CurId); + m_CurrentPoint[0] = ParseScalarType(m_CurXString); + m_CurrentPoint[1] = ParseScalarType(m_CurYString); + m_CurrentPoint[2] = ParseScalarType(m_CurZString); + + mitk::PointOperation popInsert(mitk::OpINSERT, m_CurrentPoint, m_CurrentPointId); + mitk::PointOperation popDeactivate(mitk::OpDESELECTPOINT, m_CurrentPoint, m_CurrentPointId); + assert(m_CurrentPointSet.IsNotNull()); + m_CurrentPointSet->ExecuteOperation(&popInsert); + m_CurrentPointSet->ExecuteOperation(&popDeactivate); + } +} + +void mitk::vtkPointSetXMLParser::CharacterDataHandler(const char *inData, int inLength) +{ + std::string currentElement = m_ParseStack.top(); + if (currentElement == mitk::PointSetWriter::XML_ID) + { + m_CurId.append(inData, inLength); + } + else if (currentElement == mitk::PointSetWriter::XML_X) + { + m_CurXString.append(inData, inLength); + } + else if (currentElement == mitk::PointSetWriter::XML_Y) + { + m_CurYString.append(inData, inLength); + } + else if (currentElement == mitk::PointSetWriter::XML_Z) + { + m_CurZString.append(inData, inLength); + } +} + +mitk::ScalarType mitk::vtkPointSetXMLParser::ParseScalarType(const std::string &data) +{ + std::istringstream stm; + stm.str(data); + ScalarType number; + stm >> number; + return number; +} + +mitk::vtkPointSetXMLParser::PointIdentifier mitk::vtkPointSetXMLParser::ParsePointIdentifier(const std::string &data) +{ + std::istringstream stm; + stm.str(data); + PointIdentifier pointID; + stm >> pointID; + return pointID; +} + +mitk::vtkPointSetXMLParser::PointSetList mitk::vtkPointSetXMLParser::GetParsedPointSets() +{ + return m_PointSetList; +} diff --git a/Modules/LegacyIO/vtkPointSetXMLParser.h b/Modules/LegacyIO/vtkPointSetXMLParser.h new file mode 100644 index 0000000000..89ee95200a --- /dev/null +++ b/Modules/LegacyIO/vtkPointSetXMLParser.h @@ -0,0 +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. + +===================================================================*/ + +#ifndef _VTK_POINT_SET_XML_READER__H_ +#define _VTK_POINT_SET_XML_READER__H_ + +#include +#include +#include +#include +#include +#include + +namespace mitk +{ + /** + * @brief Implementation of the vtkXMLParser interface for reading mitk::PointSets. + * + * This class implements the XMLParser interface of the vtkXMLParser which is based + * on expat. It is used by the mitk::PointSetReader and is NOT INTENDED TO BE USED + * FROM THE END-USER. If you want to read point sets, use the mitk::PointSetReader. + * @ingroup MitkLegacyIOModule + * + * @deprecatedSince{2014_10} Use mitk::IOUtils or mitk::FileReaderRegistry instead. + */ + class DEPRECATED() MITKLEGACYIO_EXPORT vtkPointSetXMLParser : public vtkXMLParser + { + public: + vtkTypeMacro(vtkPointSetXMLParser, vtkXMLParser); + + static vtkPointSetXMLParser *New(); + + typedef mitk::PointSet PointSetType; + + typedef std::stack ParseStack; + + typedef std::list PointSetList; + + typedef PointSetType::DataType::PointIdentifier PointIdentifier; + + typedef PointSetType::PointType PointType; + + virtual int InitializeParser() override; + virtual int CleanupParser() override; + /** + * Handler function which is called, when a new xml start-tag + * has been parsed. + */ + virtual void StartElement(const char *name, const char **atts) override; + + /** + * Handler function which is called, when a xml end-tag + * has been parsed. + */ + virtual void EndElement(const char *name) override; + + /** + * Handler function which is called, if characted data has been + * parsed by expat. + * @param inData a char array containing the parsed string data + * @param inLength the length of the parsed data string. + */ + virtual void CharacterDataHandler(const char *inData, int inLength) override; + + /** + * Converts the given data to mitk::ScalarType. + */ + virtual mitk::ScalarType ParseScalarType(const std::string &data); + + /** + * Converts the given data to an PointIdentifier + */ + virtual PointIdentifier ParsePointIdentifier(const std::string &data); + + /** + * @returns the list of point sets which have been read from file. + * NOTE: your have to call the Parse() function, before this function. + */ + virtual PointSetList GetParsedPointSets(); + + protected: + vtkPointSetXMLParser(); + virtual ~vtkPointSetXMLParser(); + + /** + * A stack containing the parsed start-tags. + * If an end tag is encountered, it is matched with the + * top element of the stack. + */ + ParseStack m_ParseStack; + + /** + * Contains the parsed point sets. + */ + PointSetList m_PointSetList; + + /** + * The current point set which is processed + * by the parser. + */ + PointSetType::Pointer m_CurrentPointSet; + + /** + * The current point which is processed + * by the parser. + */ + PointType m_CurrentPoint; + + std::string m_CurId; + std::string m_CurXString; + std::string m_CurYString; + std::string m_CurZString; + + /** + * The current point id which is processed + * by the parser. + */ + PointIdentifier m_CurrentPointId; + + std::locale m_PreviousLocale; + }; +} +#endif // _VTK_POINT_SET_XML_READER__H_ diff --git a/Modules/ModuleList.cmake b/Modules/ModuleList.cmake index 711e2c00da..9ab99b1a0e 100644 --- a/Modules/ModuleList.cmake +++ b/Modules/ModuleList.cmake @@ -1,77 +1,79 @@ # The entries in the mitk_modules list must be # ordered according to their dependencies. set(mitk_modules Core CommandLine AppUtil DCMTesting RDF + LegacyIO DataTypesExt Annotation LegacyGL AlgorithmsExt MapperExt DICOMReader DICOMReaderServices DICOMTesting SceneSerializationBase PlanarFigure ImageDenoising ImageExtraction SceneSerialization Gizmo GraphAlgorithms Multilabel ImageStatistics ContourModel SurfaceInterpolation Segmentation PlanarFigureSegmentation QtWidgets QtWidgetsExt Chart SegmentationUI Classification GPGPU OpenIGTLink IGTBase IGT CameraCalibration OpenCL OpenCVVideoSupport QtOverlays ToFHardware ToFProcessing ToFUI PhotoacousticsHardware PhotoacousticsAlgorithms PhotoacousticsLib US USUI DicomUI Remeshing Python QtPython Persistence OpenIGTLinkUI IGTUI DicomRT RTUI + IOExt XNAT TubeGraph BiophotonicsHardware MatchPointRegistration MatchPointRegistrationUI DiffusionImaging TumorInvasionAnalysis BoundingShape RenderWindowManager RenderWindowManagerUI CEST DICOMQI ) if(MITK_ENABLE_PIC_READER) list(APPEND mitk_modules IpPicSupportIO) endif()