diff --git a/Core/Code/IO/mitkFileWriterSelector.cpp b/Core/Code/IO/mitkFileWriterSelector.cpp index dbe909c460..f00d482265 100644 --- a/Core/Code/IO/mitkFileWriterSelector.cpp +++ b/Core/Code/IO/mitkFileWriterSelector.cpp @@ -1,275 +1,277 @@ /*=================================================================== 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 "mitkFileWriterSelector.h" #include #include #include #include #include #include +#include + namespace mitk { struct FileWriterSelector::Impl : us::SharedData { Impl() : m_BestId(-1) , m_SelectedId(m_BestId) {} Impl(const Impl& other) : us::SharedData(other) , m_BestId(-1) , m_SelectedId(m_BestId) {} FileWriterRegistry m_WriterRegistry; std::map m_Items; std::set m_MimeTypes; long m_BestId; long m_SelectedId; }; FileWriterSelector::FileWriterSelector(const FileWriterSelector& other) : m_Data(other.m_Data) { } FileWriterSelector::FileWriterSelector(const BaseData* baseData, const std::string& destMimeType) : m_Data(new Impl) { mitk::CoreServicePointer mimeTypeProvider(mitk::CoreServices::GetMimeTypeProvider()); // Get all writers and their mime types for the given base data type std::vector refs = m_Data->m_WriterRegistry.GetReferences(baseData, destMimeType); us::ServiceReference bestRef; for (std::vector::const_iterator iter = refs.begin(), iterEnd = refs.end(); iter != iterEnd; ++iter) { std::string mimeTypeName = iter->GetProperty(IFileWriter::PROP_MIMETYPE()).ToString(); if (!mimeTypeName.empty()) { MimeType mimeType = mimeTypeProvider->GetMimeTypeForName(mimeTypeName); if (mimeType.IsValid()) { // There is a registered mime-type for this writer. Now get the confidence level // of this writer for writing the given base data object. IFileWriter* writer = m_Data->m_WriterRegistry.GetWriter(*iter); if (writer == NULL) continue; try { writer->SetInput(baseData); IFileWriter::ConfidenceLevel confidenceLevel = writer->GetConfidenceLevel(); std::cout << confidenceLevel << std::endl; if (confidenceLevel == IFileWriter::Unsupported) { continue; } Item item; item.m_FileWriterRef = *iter; item.m_FileWriter = writer; item.m_ConfidenceLevel = confidenceLevel; item.m_MimeType = mimeType; item.m_Id = us::any_cast(iter->GetProperty(us::ServiceConstants::SERVICE_ID())); m_Data->m_Items.insert(std::make_pair(item.m_Id, item)); m_Data->m_MimeTypes.insert(mimeType); if (!bestRef || bestRef < *iter) { bestRef = *iter; } } catch (const us::BadAnyCastException& e) { MITK_WARN << "Unexpected: " << e.what(); } catch (const std::exception& e) { // Log the error but continue MITK_WARN << "IFileWriter::GetConfidenceLevel exception: " << e.what(); } } } } if (bestRef) { try { m_Data->m_BestId = us::any_cast(bestRef.GetProperty(us::ServiceConstants::SERVICE_ID())); m_Data->m_SelectedId = m_Data->m_BestId; } catch (const us::BadAnyCastException&) {} } } FileWriterSelector::~FileWriterSelector() { } FileWriterSelector& FileWriterSelector::operator=(const FileWriterSelector& other) { m_Data = other.m_Data; return *this; } std::vector FileWriterSelector::Get(const std::string& mimeType) const { std::vector result; for (std::map::const_iterator iter = m_Data->m_Items.begin(), iterEnd = m_Data->m_Items.end(); iter != iterEnd; ++iter) { if (mimeType.empty() || iter->second.GetMimeType().GetName() == mimeType) { result.push_back(iter->second); } } std::sort(result.begin(), result.end()); return result; } std::vector FileWriterSelector::Get() const { return Get(this->GetSelected().m_MimeType.GetName()); } FileWriterSelector::Item FileWriterSelector::Get(long id) const { std::map::const_iterator iter = m_Data->m_Items.find(id); if (iter != m_Data->m_Items.end()) { return iter->second; } return Item(); } FileWriterSelector::Item FileWriterSelector::GetDefault() const { return Get(m_Data->m_BestId); } long FileWriterSelector::GetDefaultId() const { return m_Data->m_BestId; } FileWriterSelector::Item FileWriterSelector::GetSelected() const { return Get(m_Data->m_SelectedId); } long FileWriterSelector::GetSelectedId() const { return m_Data->m_SelectedId; } bool FileWriterSelector::Select(const std::string& mimeType) { std::vector items = Get(mimeType); if (items.empty()) return false; return Select(items.back()); } bool FileWriterSelector::Select(const FileWriterSelector::Item& item) { return Select(item.m_Id); } bool FileWriterSelector::Select(long id) { if (id > -1) { if (m_Data->m_Items.find(id) == m_Data->m_Items.end()) { return false; } m_Data->m_SelectedId = id; return true; } return false; } std::vector FileWriterSelector::GetMimeTypes() const { std::vector result; result.reserve(m_Data->m_MimeTypes.size()); result.assign(m_Data->m_MimeTypes.begin(), m_Data->m_MimeTypes.end()); return result; } void FileWriterSelector::Swap(FileWriterSelector& fws) { m_Data.Swap(fws.m_Data); } IFileWriter* FileWriterSelector::Item::GetWriter() const { return m_FileWriter; } std::string FileWriterSelector::Item::GetDescription() const { us::Any descr = m_FileWriterRef.GetProperty(IFileWriter::PROP_DESCRIPTION()); if (descr.Empty()) return std::string(); return descr.ToString(); } IFileWriter::ConfidenceLevel FileWriterSelector::Item::GetConfidenceLevel() const { return m_ConfidenceLevel; } MimeType FileWriterSelector::Item::GetMimeType() const { return m_MimeType; } us::ServiceReference FileWriterSelector::Item::GetReference() const { return m_FileWriterRef; } long FileWriterSelector::Item::GetServiceId() const { return m_Id; } bool FileWriterSelector::Item::operator<(const FileWriterSelector::Item& other) const { // sort by confidence level first (ascending) if (m_ConfidenceLevel == other.m_ConfidenceLevel) { // sort by file writer service ranking return m_FileWriterRef < other.m_FileWriterRef; } return m_ConfidenceLevel < other.m_ConfidenceLevel; } FileWriterSelector::Item::Item() : m_FileWriter(NULL) , m_Id(-1) {} void swap(FileWriterSelector& fws1, FileWriterSelector& fws2) { fws1.Swap(fws2); } } diff --git a/Core/Code/Testing/mitkFileReaderRegistryTest.cpp b/Core/Code/Testing/mitkFileReaderRegistryTest.cpp index 34967e3154..b335b9e12b 100644 --- a/Core/Code/Testing/mitkFileReaderRegistryTest.cpp +++ b/Core/Code/Testing/mitkFileReaderRegistryTest.cpp @@ -1,220 +1,220 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkTestingMacros.h" #include "mitkAbstractFileReader.h" #include "mitkIFileReader.h" #include "mitkFileReaderRegistry.h" #include #include #include class DummyReader : public mitk::AbstractFileReader { public: DummyReader(const DummyReader& other) : mitk::AbstractFileReader(other) { } DummyReader(const std::string& mimeTypeName, const std::string& extension, int priority) : mitk::AbstractFileReader() { mitk::CustomMimeType mimeType(mimeTypeName); mimeType.AddExtension(extension); mimeType.SetComment("This is a dummy description"); this->SetMimeType(mimeType); this->SetRanking(priority); m_ServiceReg = this->RegisterService(); } ~DummyReader() { if (m_ServiceReg) m_ServiceReg.Unregister(); } using mitk::AbstractFileReader::Read; - virtual std::vector< itk::SmartPointer > Read(std::istream& /*stream*/) + virtual std::vector< itk::SmartPointer > Read() { std::vector result; return result; } private: DummyReader* Clone() const { return new DummyReader(*this); } us::ServiceRegistration m_ServiceReg; }; // End of internal dummy reader class DummyReader2 : public mitk::AbstractFileReader { public: DummyReader2(const DummyReader2& other) : mitk::AbstractFileReader(other) { } DummyReader2(const std::string& mimeTypeName, const std::string& extension, int priority) : mitk::AbstractFileReader() { mitk::CustomMimeType mimeType(mimeTypeName); mimeType.AddExtension(extension); mimeType.SetComment("This is a second dummy description"); this->SetMimeType(mimeType); this->SetRanking(priority); m_ServiceReg = this->RegisterService(); } ~DummyReader2() { if (m_ServiceReg) m_ServiceReg.Unregister(); } using mitk::AbstractFileReader::Read; - virtual std::vector< itk::SmartPointer > Read(std::istream& /*stream*/) + virtual std::vector< itk::SmartPointer > Read() { std::vector result; return result; } private: DummyReader2* Clone() const { return new DummyReader2(*this); } us::ServiceRegistration m_ServiceReg; }; // End of internal dummy reader 2 /** * TODO */ int mitkFileReaderRegistryTest(int /*argc*/ , char* /*argv*/[]) { // always start with this! MITK_TEST_BEGIN("FileReaderRegistry"); // mitk::FileReaderRegistry::Pointer frm = mitk::FileReaderRegistry::New(); // MITK_TEST_CONDITION_REQUIRED(argc == 2,"Testing FileReaderRegistry instantiation"); //DummyReader testDR("application/dummy", "test",1); //DummyReader otherDR("application/dummy2", "other",1); //MITK_TEST_CONDITION_REQUIRED(!testDR.CanRead("/this/is/a/folder/file.tes"),"Negative test of default CanRead() implementation"); //mitk::FileReaderRegistry* readerRegistry = new mitk::FileReaderRegistry; //mitk::IFileReader* returned = readerRegistry->GetReader("bla.test"); //MITK_TEST_CONDITION_REQUIRED(returned && &static_cast(testDR) != returned,"Testing correct retrieval of FileReader 1/2"); //returned = readerRegistry->GetReader("other"); //MITK_TEST_CONDITION_REQUIRED(returned && &static_cast(otherDR) != returned,"Testing correct retrieval of FileReader 2/2"); //DummyReader mediocreTestDR("application/dummy", "test", 20); //DummyReader prettyFlyTestDR("application/dummy", "test", 50); //DummyReader2 awesomeTestDR("application/dummy", "test", 100); //returned = readerRegistry->GetReader("test"); //MITK_TEST_CONDITION_REQUIRED(dynamic_cast(returned), "Testing correct priorized retrieval of FileReader: Best reader"); // Now to give those readers some options, then we will try again // mitk::IFileReader::OptionList options; // options.push_back(std::make_pair("isANiceGuy", true)); // mediocreTestDR.SetOptions(options); // options.clear(); // options.push_back(std::make_pair("canFly", true)); // prettyFlyTestDR.SetOptions(options); // options.push_back(std::make_pair("isAwesome", true)); // awesomeTestDR.SetOptions(options); //note: awesomeReader canFly and isAwesome // // Reset Options, use to define what we want the reader to do // options.clear(); // mitk::IFileReader::OptionNames optionsFilter; // optionsFilter.push_back("canFly"); // returned = readerRegistry->GetReader("test", optionsFilter); // MITK_TEST_CONDITION_REQUIRED(returned && &static_cast(awesomeTestDR) != returned, "Testing correct retrieval of FileReader with Options: Best reader with options"); // optionsFilter.push_back("isAwesome"); // returned = readerRegistry->GetReader("test", optionsFilter); // MITK_TEST_CONDITION_REQUIRED(returned && &static_cast(awesomeTestDR) != returned, "Testing correct retrieval of FileReader with multiple Options: Best reader with options"); // optionsFilter.clear(); // optionsFilter.push_back("isANiceGuy"); // returned = readerRegistry->GetReader("test", optionsFilter); // MITK_TEST_CONDITION_REQUIRED(returned && &static_cast(mediocreTestDR) != returned, "Testing correct retrieval of specific FileReader with Options: Low priority reader with specific option"); // optionsFilter.push_back("canFly"); // returned = readerRegistry->GetReader("test", optionsFilter); // MITK_TEST_CONDITION_REQUIRED(returned == NULL, "Testing correct return of 0 value when no matching reader was found"); // // Onward to test the retrieval of multiple readers // std::vector< mitk::IFileReader* > returnedList; // returnedList = readerRegistry->GetReaders("test", optionsFilter); // MITK_TEST_CONDITION_REQUIRED(returnedList.empty(), "Testing correct return of zero readers when no matching reader was found, asking for all compatibles"); // optionsFilter.clear(); // optionsFilter.push_back("canFly"); // returnedList = readerRegistry->GetReaders("test", optionsFilter); // MITK_TEST_CONDITION_REQUIRED(returnedList.size() == 2, "Testing correct return of two readers when two matching reader was found, asking for all compatibles"); // MITK_TEST_CONDITION_REQUIRED(dynamic_cast(returnedList.front()), "Testing correct priorization of returned Readers with options 1/2"); // optionsFilter.clear(); // optionsFilter.push_back("isAwesome"); // returnedList = readerRegistry->GetReaders("test", optionsFilter); // MITK_TEST_CONDITION_REQUIRED(returnedList.size() == 1, "Testing correct return of one readers when one matching reader was found, asking for all compatibles"); // MITK_TEST_CONDITION_REQUIRED(dynamic_cast(returnedList.front()), "Testing correctness of result from former query"); // And now to verify a working read chain for a mps file: //mitk::PointSetReader::Pointer psr = mitk::PointSetReader::New(); //std::vector basedata; //basedata = mitk::FileReaderRegistry::Read("F://Build//MITK-Data//pointSet.mps"); //MITK_TEST_CONDITION_REQUIRED(basedata.size() > 0, "Testing correct read of PointSet"); // Testing templated call to ReaderRegistry //mitk::PointSet::Pointer pointset = mitk::FileReaderRegistry::Read< mitk::PointSet >("F://Build//MITK-Data//pointSet.mps"); //MITK_TEST_CONDITION_REQUIRED(pointset.IsNotNull(), "Testing templated call of Read()"); // And now for something completely different... (Debug) // mitk::LegacyFileReaderService::Pointer lfr = mitk::LegacyFileReaderService::New(".nrrd", "Nearly Raw Raster Data"); //returned = mitk::FileReaderRegistry::GetReader(".nrrd"); //MITK_TEST_CONDITION_REQUIRED(lfr == returned, "Testing correct retrieval of specific FileReader with Options: Low priority reader with specific option"); //std::vector image = mitk::FileReaderRegistry::Read("F://Build//MITK-Data//Pic2DplusT.nrrd"); //MITK_TEST_CONDITION_REQUIRED(image.size() > 0, "Testing whether image was returned or not"); //mitk::Image::Pointer image2 = dynamic_cast (image.front().GetPointer()); //MITK_TEST_CONDITION_REQUIRED(image2.IsNotNull(), "Testing if BaseData is an image"); // Delete this here because it will call the PrototypeServiceFactory::Unget() method // of the dummy readers. //delete readerRegistry; // always end with this! MITK_TEST_END(); } diff --git a/Core/Code/Testing/mitkPointSetReaderTest.cpp b/Core/Code/Testing/mitkPointSetReaderTest.cpp index 3e8341851f..6967e3f01d 100644 --- a/Core/Code/Testing/mitkPointSetReaderTest.cpp +++ b/Core/Code/Testing/mitkPointSetReaderTest.cpp @@ -1,67 +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 "mitkPointSet.h" #include "mitkTestingMacros.h" #include "mitkFileReaderRegistry.h" #include "mitkMimeType.h" /** * Test for the class "mitkPointSetReader". * * 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 data set for the tests (see CMakeLists.txt). */ int mitkPointSetReaderTest(int argc , char* argv[]) { // always start with this! MITK_TEST_BEGIN("PointSetReader") MITK_TEST_CONDITION_REQUIRED(argc == 2,"Testing invocation") mitk::FileReaderRegistry readerRegistry; // Get PointSet reader(s) std::vector readers = readerRegistry.GetReaders(mitk::FileReaderRegistry::GetMimeTypeForExtension("mps")); MITK_TEST_CONDITION_REQUIRED(!readers.empty(), "Testing for registered readers") for (std::vector::const_iterator iter = readers.begin(), end = readers.end(); iter != end; ++iter) { std::string testName = "test1"; mitk::IFileReader* reader = *iter; + reader->SetInput(testName); // testing file reading with invalid data - MITK_TEST_CONDITION_REQUIRED(reader->GetConfidenceLevel(testName) == mitk::IFileReader::Unsupported, "Testing confidence level with invalid input file name!"); - CPPUNIT_ASSERT_THROW(reader->Read(testName), mitk::Exception); + MITK_TEST_CONDITION_REQUIRED(reader->GetConfidenceLevel() == mitk::IFileReader::Unsupported, "Testing confidence level with invalid input file name!"); + CPPUNIT_ASSERT_THROW(reader->Read(), mitk::Exception); // testing file reading with valid data std::string filePath = argv[1]; - MITK_TEST_CONDITION_REQUIRED( reader->GetConfidenceLevel(filePath) == mitk::IFileReader::Supported, "Testing confidence level with valid input file name!"); - std::vector data = reader->Read(filePath); + reader->SetInput(filePath); + MITK_TEST_CONDITION_REQUIRED( reader->GetConfidenceLevel() == mitk::IFileReader::Supported, "Testing confidence level with valid input file name!"); + std::vector data = reader->Read(); MITK_TEST_CONDITION_REQUIRED( !data.empty(), "Testing non-empty data with valid input file name!"); // evaluate if the read point set is correct mitk::PointSet::Pointer resultPS = dynamic_cast(data.front().GetPointer()); MITK_TEST_CONDITION_REQUIRED( resultPS.IsNotNull(), "Testing correct BaseData type"); MITK_TEST_CONDITION_REQUIRED( resultPS->GetTimeSteps() == 14, "Testing output time step generation!"); // CAVE: Only valid with the specified test data! MITK_TEST_CONDITION_REQUIRED( resultPS->GetPointSet(resultPS->GetTimeSteps()-1)->GetNumberOfPoints() == 0, "Testing output time step generation with empty time step!"); // CAVE: Only valid with the specified test data! } // always end with this! MITK_TEST_END() } diff --git a/Core/Code/Testing/mitkPointSetWriterTest.cpp b/Core/Code/Testing/mitkPointSetWriterTest.cpp index 6cee924473..c32a05bd34 100644 --- a/Core/Code/Testing/mitkPointSetWriterTest.cpp +++ b/Core/Code/Testing/mitkPointSetWriterTest.cpp @@ -1,79 +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 "mitkPointSet.h" #include "mitkTestingMacros.h" #include "mitkFileWriterSelector.h" #include #include /** * Test for the class "mitkPointSetFileWriter". * * 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 mitkPointSetWriterTest(int /* argc */, char* /*argv*/[]) { // always start with this! MITK_TEST_BEGIN("PointSetWriter") // create pointSet srand(time(NULL)); mitk::PointSet::Pointer pointSet = mitk::PointSet::New(); int numberOfPoints = rand()%100; for (int i=0; i<=numberOfPoints+1;i++) { mitk::Point3D point; point[0] = rand()%1000; point[1] = rand()%1000; point[2] = rand()%1000; pointSet->SetPoint(i,point); } MITK_TEST_CONDITION_REQUIRED(pointSet.IsNotNull(),"PointSet creation") // Get PointSet writer(s) mitk::FileWriterSelector writerSelector(pointSet.GetPointer()); std::vector writers = writerSelector.Get(); MITK_TEST_CONDITION_REQUIRED(!writers.empty(), "Testing for registered writers") for (std::vector::const_iterator iter = writers.begin(), end = writers.end(); iter != end; ++iter) { // test for exception handling try { - iter->GetWriter()->Write(pointSet, "/usr/bin"); + mitk::IFileWriter* writer = iter->GetWriter(); + writer->SetInput(pointSet); + writer->SetOutputLocation("/usr/bin"); + iter->GetWriter()->Write(); MITK_TEST_FAILED_MSG( << "itk::ExceptionObject expected" ) } catch (const itk::ExceptionObject&) { /* this is expected */ } catch(...) { //this means that a wrong exception (i.e. no itk:Exception) has been thrown MITK_TEST_FAILED_MSG( << "Wrong exception (i.e. no itk:Exception) caught during write [FAILED]") } } // always end with this! MITK_TEST_END() } diff --git a/Examples/QtFreeRender/QtFreeRender.cpp b/Examples/QtFreeRender/QtFreeRender.cpp index fc0937f21f..f6d8e5f3e3 100644 --- a/Examples/QtFreeRender/QtFreeRender.cpp +++ b/Examples/QtFreeRender/QtFreeRender.cpp @@ -1,373 +1,370 @@ /*=================================================================== 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 "mitkRenderWindow.h" -#include #include #include #include #include #include #include #include "mitkProperties.h" #include "mitkPlaneGeometryDataMapper2D.h" #include "mitkGlobalInteraction.h" #include "mitkDisplayInteractor.h" #include "mitkPositionEvent.h" #include "mitkStateEvent.h" #include "mitkLine.h" #include "mitkInteractionConst.h" #include "mitkVtkLayerController.h" #include "mitkPositionTracker.h" #include "mitkDisplayInteractor.h" #include "mitkSlicesRotator.h" #include "mitkSlicesSwiveller.h" #include "mitkRenderWindowFrame.h" #include "mitkGradientBackground.h" #include "mitkCoordinateSupplier.h" #include "mitkDataStorage.h" +#include "mitkIOUtil.h" #include "vtkTextProperty.h" #include "vtkCornerAnnotation.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkAnnotatedCubeActor.h" #include "vtkOrientationMarkerWidget.h" #include "vtkProperty.h" // us #include "usGetModuleContext.h" #include "usModuleContext.h" #include "mitkInteractionEventObserver.h" //##Documentation //## @brief Example of a NON QT DEPENDENT MITK RENDERING APPLICATION. mitk::RenderWindow::Pointer mitkWidget1; mitk::RenderWindow::Pointer mitkWidget2; mitk::RenderWindow::Pointer mitkWidget3; mitk::RenderWindow::Pointer mitkWidget4; mitk::DisplayInteractor::Pointer m_DisplayInteractor; mitk::CoordinateSupplier::Pointer m_LastLeftClickPositionSupplier; mitk::GradientBackground::Pointer m_GradientBackground4; mitk::RenderWindowFrame::Pointer m_RectangleRendering1; mitk::RenderWindowFrame::Pointer m_RectangleRendering2; mitk::RenderWindowFrame::Pointer m_RectangleRendering3; mitk::RenderWindowFrame::Pointer m_RectangleRendering4; mitk::SliceNavigationController* m_TimeNavigationController = NULL; mitk::DataStorage::Pointer m_DataStorage; mitk::DataNode::Pointer m_PlaneNode1; mitk::DataNode::Pointer m_PlaneNode2; mitk::DataNode::Pointer m_PlaneNode3; mitk::DataNode::Pointer m_Node; void InitializeWindows() { // Set default view directions for SNCs mitkWidget1->GetSliceNavigationController()->SetDefaultViewDirection(mitk::SliceNavigationController::Axial); mitkWidget2->GetSliceNavigationController()->SetDefaultViewDirection(mitk::SliceNavigationController::Sagittal); mitkWidget3->GetSliceNavigationController()->SetDefaultViewDirection(mitk::SliceNavigationController::Frontal); mitkWidget4->GetSliceNavigationController()->SetDefaultViewDirection(mitk::SliceNavigationController::Original); //initialize m_TimeNavigationController: send time via sliceNavigationControllers m_TimeNavigationController = mitk::RenderingManager::GetInstance()->GetTimeNavigationController(); m_TimeNavigationController->ConnectGeometryTimeEvent(mitkWidget1->GetSliceNavigationController(), false); m_TimeNavigationController->ConnectGeometryTimeEvent(mitkWidget2->GetSliceNavigationController(), false); m_TimeNavigationController->ConnectGeometryTimeEvent(mitkWidget3->GetSliceNavigationController(), false); m_TimeNavigationController->ConnectGeometryTimeEvent(mitkWidget4->GetSliceNavigationController(), false); mitkWidget1->GetSliceNavigationController()->ConnectGeometrySendEvent(mitk::BaseRenderer::GetInstance(mitkWidget4->GetVtkRenderWindow())); //reverse connection between sliceNavigationControllers and m_TimeNavigationController mitkWidget1->GetSliceNavigationController()->ConnectGeometryTimeEvent(m_TimeNavigationController, false); mitkWidget2->GetSliceNavigationController()->ConnectGeometryTimeEvent(m_TimeNavigationController, false); mitkWidget3->GetSliceNavigationController()->ConnectGeometryTimeEvent(m_TimeNavigationController, false); mitkWidget4->GetSliceNavigationController()->ConnectGeometryTimeEvent(m_TimeNavigationController, false); // Let NavigationControllers listen to GlobalInteraction mitk::GlobalInteraction *gi = mitk::GlobalInteraction::GetInstance(); gi->AddListener(m_TimeNavigationController); m_LastLeftClickPositionSupplier = mitk::CoordinateSupplier::New("navigation", NULL); mitk::GlobalInteraction::GetInstance()->AddListener(m_LastLeftClickPositionSupplier); m_GradientBackground4 = mitk::GradientBackground::New(); m_GradientBackground4->SetRenderWindow(mitkWidget4->GetVtkRenderWindow()); m_GradientBackground4->SetGradientColors(0.1, 0.1, 0.1, 0.5, 0.5, 0.5); m_GradientBackground4->Enable(); m_RectangleRendering1 = mitk::RenderWindowFrame::New(); m_RectangleRendering1->SetRenderWindow(mitkWidget1->GetVtkRenderWindow()); m_RectangleRendering1->Enable(1.0, 0.0, 0.0); m_RectangleRendering2 = mitk::RenderWindowFrame::New(); m_RectangleRendering2->SetRenderWindow(mitkWidget2->GetVtkRenderWindow()); m_RectangleRendering2->Enable(0.0, 1.0, 0.0); m_RectangleRendering3 = mitk::RenderWindowFrame::New(); m_RectangleRendering3->SetRenderWindow(mitkWidget3->GetVtkRenderWindow()); m_RectangleRendering3->Enable(0.0, 0.0, 1.0); m_RectangleRendering4 = mitk::RenderWindowFrame::New(); m_RectangleRendering4->SetRenderWindow(mitkWidget4->GetVtkRenderWindow()); m_RectangleRendering4->Enable(1.0, 1.0, 0.0); } void AddDisplayPlaneSubTree() { // add the displayed planes of the multiwidget to a node to which the subtree // @a planesSubTree points ... float white[3] = { 1.0f, 1.0f, 1.0f }; mitk::PlaneGeometryDataMapper2D::Pointer mapper; mitk::IntProperty::Pointer layer = mitk::IntProperty::New(1000); // ... of widget 1 m_PlaneNode1 = (mitk::BaseRenderer::GetInstance(mitkWidget1->GetVtkRenderWindow()))->GetCurrentWorldPlaneGeometryNode(); m_PlaneNode1->SetColor(white, mitk::BaseRenderer::GetInstance(mitkWidget4->GetVtkRenderWindow())); m_PlaneNode1->SetProperty("visible", mitk::BoolProperty::New(true)); m_PlaneNode1->SetProperty("name", mitk::StringProperty::New("widget1Plane")); m_PlaneNode1->SetProperty("includeInBoundingBox", mitk::BoolProperty::New(false)); m_PlaneNode1->SetProperty("helper object", mitk::BoolProperty::New(true)); m_PlaneNode1->SetProperty("layer", layer); m_PlaneNode1->SetColor(1.0, 0.0, 0.0); mapper = mitk::PlaneGeometryDataMapper2D::New(); m_PlaneNode1->SetMapper(mitk::BaseRenderer::Standard2D, mapper); // ... of widget 2 m_PlaneNode2 = (mitk::BaseRenderer::GetInstance(mitkWidget2->GetVtkRenderWindow()))->GetCurrentWorldPlaneGeometryNode(); m_PlaneNode2->SetColor(white, mitk::BaseRenderer::GetInstance(mitkWidget4->GetVtkRenderWindow())); m_PlaneNode2->SetProperty("visible", mitk::BoolProperty::New(true)); m_PlaneNode2->SetProperty("name", mitk::StringProperty::New("widget2Plane")); m_PlaneNode2->SetProperty("includeInBoundingBox", mitk::BoolProperty::New(false)); m_PlaneNode2->SetProperty("helper object", mitk::BoolProperty::New(true)); m_PlaneNode2->SetProperty("layer", layer); m_PlaneNode2->SetColor(0.0, 1.0, 0.0); mapper = mitk::PlaneGeometryDataMapper2D::New(); m_PlaneNode2->SetMapper(mitk::BaseRenderer::Standard2D, mapper); // ... of widget 3 m_PlaneNode3 = (mitk::BaseRenderer::GetInstance(mitkWidget3->GetVtkRenderWindow()))->GetCurrentWorldPlaneGeometryNode(); m_PlaneNode3->SetColor(white, mitk::BaseRenderer::GetInstance(mitkWidget4->GetVtkRenderWindow())); m_PlaneNode3->SetProperty("visible", mitk::BoolProperty::New(true)); m_PlaneNode3->SetProperty("name", mitk::StringProperty::New("widget3Plane")); m_PlaneNode3->SetProperty("includeInBoundingBox", mitk::BoolProperty::New(false)); m_PlaneNode3->SetProperty("helper object", mitk::BoolProperty::New(true)); m_PlaneNode3->SetProperty("layer", layer); m_PlaneNode3->SetColor(0.0, 0.0, 1.0); mapper = mitk::PlaneGeometryDataMapper2D::New(); m_PlaneNode3->SetMapper(mitk::BaseRenderer::Standard2D, mapper); m_Node = mitk::DataNode::New(); m_Node->SetProperty("name", mitk::StringProperty::New("Widgets")); m_Node->SetProperty("helper object", mitk::BoolProperty::New(true)); //AddPlanesToDataStorage if (m_PlaneNode1.IsNotNull() && m_PlaneNode2.IsNotNull() && m_PlaneNode3.IsNotNull() && m_Node.IsNotNull()) { if (m_DataStorage.IsNotNull()) { m_DataStorage->Add(m_Node); m_DataStorage->Add(m_PlaneNode1, m_Node); m_DataStorage->Add(m_PlaneNode2, m_Node); m_DataStorage->Add(m_PlaneNode3, m_Node); static_cast(m_PlaneNode1->GetMapper(mitk::BaseRenderer::Standard2D))->SetDatastorageAndGeometryBaseNode( m_DataStorage, m_Node); static_cast(m_PlaneNode2->GetMapper(mitk::BaseRenderer::Standard2D))->SetDatastorageAndGeometryBaseNode( m_DataStorage, m_Node); static_cast(m_PlaneNode3->GetMapper(mitk::BaseRenderer::Standard2D))->SetDatastorageAndGeometryBaseNode( m_DataStorage, m_Node); } } } void Fit() { vtkRenderer * vtkrenderer; mitk::BaseRenderer::GetInstance(mitkWidget1->GetVtkRenderWindow())->GetDisplayGeometry()->Fit(); mitk::BaseRenderer::GetInstance(mitkWidget2->GetVtkRenderWindow())->GetDisplayGeometry()->Fit(); mitk::BaseRenderer::GetInstance(mitkWidget3->GetVtkRenderWindow())->GetDisplayGeometry()->Fit(); mitk::BaseRenderer::GetInstance(mitkWidget4->GetVtkRenderWindow())->GetDisplayGeometry()->Fit(); int w = vtkObject::GetGlobalWarningDisplay(); vtkObject::GlobalWarningDisplayOff(); vtkrenderer = mitk::BaseRenderer::GetInstance(mitkWidget1->GetVtkRenderWindow())->GetVtkRenderer(); if (vtkrenderer != NULL) vtkrenderer->ResetCamera(); vtkrenderer = mitk::BaseRenderer::GetInstance(mitkWidget2->GetVtkRenderWindow())->GetVtkRenderer(); if (vtkrenderer != NULL) vtkrenderer->ResetCamera(); vtkrenderer = mitk::BaseRenderer::GetInstance(mitkWidget3->GetVtkRenderWindow())->GetVtkRenderer(); if (vtkrenderer != NULL) vtkrenderer->ResetCamera(); vtkrenderer = mitk::BaseRenderer::GetInstance(mitkWidget4->GetVtkRenderWindow())->GetVtkRenderer(); if (vtkrenderer != NULL) vtkrenderer->ResetCamera(); vtkObject::SetGlobalWarningDisplay(w); } int main(int argc, char* argv[]) { if (argc < 2) { fprintf(stderr, "Usage: %s [filename1] [filename2] ...\n\n", ""); return 1; } // Create a DataStorage m_DataStorage = mitk::StandaloneDataStorage::New(); //************************************************************************* // Part II: Create some data by reading files //************************************************************************* int i; for (i = 1; i < argc; ++i) { // For testing if (strcmp(argv[i], "-testing") == 0) continue; - // Create a DataNodeFactory to read a data format supported - // by the DataNodeFactory (many image formats, surface formats, etc.) - mitk::DataNodeFactory::Pointer nodeReader = mitk::DataNodeFactory::New(); - const char * filename = argv[i]; + std::string filename = argv[i]; try { - nodeReader->SetFileName(filename); - nodeReader->Update(); + // Read the file and add it as a data node to the data storage + mitk::DataStorage::SetOfObjects::Pointer nodes = mitk::IOUtil::Load(filename, *m_DataStorage); - // Since the DataNodeFactory directly creates a node, - // use the datastorage to add the read node - mitk::DataNode::Pointer node = nodeReader->GetOutput(); - m_DataStorage->Add(node); - - mitk::Image::Pointer image = dynamic_cast(node->GetData()); - if (image.IsNotNull()) + for (mitk::DataStorage::SetOfObjects::Iterator nodeIter = nodes->Begin(), + nodeIterEnd = nodes->End(); nodeIter != nodeIterEnd; ++nodeIter) { - // Set the property "volumerendering" to the Boolean value "true" - node->SetProperty("volumerendering", mitk::BoolProperty::New(false)); - node->SetProperty("name", mitk::StringProperty::New("testimage")); - node->SetProperty("layer", mitk::IntProperty::New(1)); + mitk::DataNode::Pointer node = nodeIter->Value(); + mitk::Image::Pointer image = dynamic_cast(node->GetData()); + if (image.IsNotNull()) + { + // Set the property "volumerendering" to the Boolean value "true" + node->SetProperty("volumerendering", mitk::BoolProperty::New(false)); + node->SetProperty("name", mitk::StringProperty::New("testimage")); + node->SetProperty("layer", mitk::IntProperty::New(1)); + } } } catch (...) { - fprintf(stderr, "Could not open file %s \n\n", filename); + std::cerr << "Could not open file " << filename << std::endl; exit(2); } } //************************************************************************* // Part V: Create window and pass the tree to it //************************************************************************* // Global Interaction initialize // legacy because window manager relies still on existence if global interaction mitk::GlobalInteraction::GetInstance()->Initialize("global"); //mitk::GlobalInteraction::GetInstance()->AddListener(m_DisplayInteractor); // Create renderwindows mitkWidget1 = mitk::RenderWindow::New(); mitkWidget2 = mitk::RenderWindow::New(); mitkWidget3 = mitk::RenderWindow::New(); mitkWidget4 = mitk::RenderWindow::New(); // Tell the renderwindow which (part of) the datastorage to render mitkWidget1->GetRenderer()->SetDataStorage(m_DataStorage); mitkWidget2->GetRenderer()->SetDataStorage(m_DataStorage); mitkWidget3->GetRenderer()->SetDataStorage(m_DataStorage); mitkWidget4->GetRenderer()->SetDataStorage(m_DataStorage); // Let NavigationControllers listen to GlobalInteraction mitk::GlobalInteraction *gi = mitk::GlobalInteraction::GetInstance(); gi->AddListener(mitkWidget1->GetSliceNavigationController()); gi->AddListener(mitkWidget2->GetSliceNavigationController()); gi->AddListener(mitkWidget3->GetSliceNavigationController()); gi->AddListener(mitkWidget4->GetSliceNavigationController()); // instantiate display interactor if (m_DisplayInteractor.IsNull()) { m_DisplayInteractor = mitk::DisplayInteractor::New(); m_DisplayInteractor->LoadStateMachine("DisplayInteraction.xml"); m_DisplayInteractor->SetEventConfig("DisplayConfigMITK.xml"); // Register as listener via micro services us::ModuleContext* context = us::GetModuleContext(); context->RegisterService( m_DisplayInteractor.GetPointer()); } // Use it as a 2D View mitkWidget1->GetRenderer()->SetMapperID(mitk::BaseRenderer::Standard2D); mitkWidget2->GetRenderer()->SetMapperID(mitk::BaseRenderer::Standard2D); mitkWidget3->GetRenderer()->SetMapperID(mitk::BaseRenderer::Standard2D); mitkWidget4->GetRenderer()->SetMapperID(mitk::BaseRenderer::Standard3D); mitkWidget1->SetSize(400, 400); mitkWidget2->GetVtkRenderWindow()->SetPosition(mitkWidget1->GetVtkRenderWindow()->GetPosition()[0] + 420, mitkWidget1->GetVtkRenderWindow()->GetPosition()[1]); mitkWidget2->SetSize(400, 400); mitkWidget3->GetVtkRenderWindow()->SetPosition(mitkWidget1->GetVtkRenderWindow()->GetPosition()[0], mitkWidget1->GetVtkRenderWindow()->GetPosition()[1] + 450); mitkWidget3->SetSize(400, 400); mitkWidget4->GetVtkRenderWindow()->SetPosition(mitkWidget1->GetVtkRenderWindow()->GetPosition()[0] + 420, mitkWidget1->GetVtkRenderWindow()->GetPosition()[1] + 450); mitkWidget4->SetSize(400, 400); InitializeWindows(); AddDisplayPlaneSubTree(); Fit(); // Initialize the RenderWindows mitk::TimeGeometry::Pointer geo = m_DataStorage->ComputeBoundingGeometry3D(m_DataStorage->GetAll()); mitk::RenderingManager::GetInstance()->InitializeViews(geo); m_DataStorage->Print(std::cout); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); // reinit the mitkVTKEventProvider; // this is only necessary once after calling // ForceImmediateUpdateAll() for the first time mitkWidget1->ReinitEventProvider(); mitkWidget2->ReinitEventProvider(); mitkWidget3->ReinitEventProvider(); mitkWidget1->GetVtkRenderWindow()->Render(); mitkWidget2->GetVtkRenderWindow()->Render(); mitkWidget3->GetVtkRenderWindow()->Render(); mitkWidget4->GetVtkRenderWindow()->Render(); mitkWidget4->GetVtkRenderWindowInteractor()->Start(); return 0; } diff --git a/Modules/ContourModel/IO/mitkContourModelSetWriter.cpp b/Modules/ContourModel/IO/mitkContourModelSetWriter.cpp index cc9c7e1312..e9f1939dc9 100644 --- a/Modules/ContourModel/IO/mitkContourModelSetWriter.cpp +++ b/Modules/ContourModel/IO/mitkContourModelSetWriter.cpp @@ -1,172 +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 "mitkContourModelSetWriter.h" #include "mitkContourModelWriter.h" mitk::ContourModelSetWriter::ContourModelSetWriter() : m_FileName(""), m_FilePrefix(""), m_FilePattern("") { this->SetNumberOfRequiredInputs( 1 ); this->SetNumberOfIndexedOutputs( 1 ); this->SetNthOutput( 0, mitk::ContourModel::New().GetPointer() ); m_Success = false; } mitk::ContourModelSetWriter::~ContourModelSetWriter() {} void mitk::ContourModelSetWriter::GenerateData() { //Use regular ContourModel writer to write each contour of the set to a single file. //Just use a different file extension .cnt_set mitk::ContourModelWriter::Pointer writer = mitk::ContourModelWriter::New(); writer->SetFileName(this->GetFileName()); if ( m_FileName == "" ) { itkWarningMacro( << "Sorry, filename has not been set! Setting filename to default." ); m_FileName = GetDefaultFilename(); } InputType::Pointer contourModelSet = this->GetInput(); // // for each contour object set input of writer // for ( int i = 0 ; i < contourModelSet->GetSize(); ++i ) { mitk::ContourModel* contour = contourModelSet->GetContourModelAt(i); writer->SetInput( i, contour ); } writer->Update(); m_Success = true; m_MimeType = "application/MITK.ContourModel"; } void mitk::ContourModelSetWriter::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::ContourModel::New().GetPointer() ); } } void mitk::ContourModelSetWriter::SetInput( InputType* contourModel ) { this->ProcessObject::SetNthInput( 0, contourModel ); } void mitk::ContourModelSetWriter::SetInput( const unsigned int& id, InputType* contourModel ) { if ( id >= this->GetNumberOfInputs() ) this->ResizeInputs( id + 1 ); this->ProcessObject::SetNthInput( id, contourModel ); } mitk::ContourModelSet* mitk::ContourModelSetWriter::GetInput() { if ( this->GetNumberOfInputs() < 1 ) { return 0; } else { return dynamic_cast ( this->GetInput( 0 ) ); } } mitk::ContourModelSet* mitk::ContourModelSetWriter::GetInput( const unsigned int& num ) { return dynamic_cast ( this->ProcessObject::GetInput( num ) ); } bool mitk::ContourModelSetWriter::GetSuccess() const { return m_Success; } - +std::string mitk::ContourModelSetWriter::GetSupportedBaseData() const +{ + return ContourModelSet::GetStaticNameOfClass(); +} bool mitk::ContourModelSetWriter::CanWriteDataType( DataNode* input ) { if ( input ) { mitk::BaseData* data = input->GetData(); if ( data ) { mitk::ContourModel::Pointer contourModel = dynamic_cast( data ); if( contourModel.IsNotNull() ) { //this writer has no "SetDefaultExtension()" - function m_Extension = ".cnt_set"; return true; } } } return false; } void mitk::ContourModelSetWriter::SetInput( DataNode* input ) { if( input && CanWriteDataType( input ) ) this->ProcessObject::SetNthInput( 0, dynamic_cast( input->GetData() ) ); } std::vector mitk::ContourModelSetWriter::GetPossibleFileExtensions() { std::vector possibleFileExtensions; possibleFileExtensions.push_back(".cnt_set"); return possibleFileExtensions; } std::string mitk::ContourModelSetWriter::GetFileExtension() { return m_Extension; } std::string mitk::ContourModelSetWriter::GetWritenMIMEType() { return "application/MITK.ContourModelSet"; } diff --git a/Modules/ContourModel/IO/mitkContourModelSetWriter.h b/Modules/ContourModel/IO/mitkContourModelSetWriter.h index c9e46a7fea..67c76fb9b4 100644 --- a/Modules/ContourModel/IO/mitkContourModelSetWriter.h +++ b/Modules/ContourModel/IO/mitkContourModelSetWriter.h @@ -1,199 +1,201 @@ /*=================================================================== 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_CONTOURMODELSET_WRITER__H_ #define _MITK_CONTOURMODELSET_WRITER__H_ #include #include #include #include #include namespace mitk { /** * @brief XML-based writer for mitk::ContourModelSet * * Uses the regular ContourModel writer to write each contour of the ContourModelSet to a single file. * * @ingroup PSIO * @ingroup Process */ class MitkContourModel_EXPORT ContourModelSetWriter : public mitk::FileWriterWithInformation { public: mitkClassMacro( ContourModelSetWriter, mitk::FileWriter ); mitkWriterMacro; itkFactorylessNewMacro(Self) itkCloneMacro(Self) typedef mitk::ContourModelSet 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. */ ContourModelSet* GetInput(); /** * @param num the index of the desired output object. * @returns the n'th input object of the filter. */ ContourModelSet* GetInput( const unsigned int& num ); /** * @brief Return the possible file extensions for the data type associated with the writer */ virtual std::vector GetPossibleFileExtensions(); /** * @brief Return the extension to be added to the filename. */ virtual std::string GetFileExtension(); /** * @brief Check if the Writer can write the Content of the */ virtual bool CanWriteDataType( DataNode* ); /** * @brief Return the MimeType of the saved File. */ virtual std::string GetWritenMIMEType(); using Superclass::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; + std::string GetSupportedBaseData() const; + /*++++++ FileWriterWithInformation methods +++++++*/ virtual const char *GetDefaultFilename() { return "ContourModelSet.cnt_set"; } virtual const char *GetFileDialogPattern() { return "MITK ContourModelSet (*.cnt_set)"; } virtual const char *GetDefaultExtension() { return ".cnt_set"; } virtual bool CanWriteBaseDataType(BaseData::Pointer data) { return (dynamic_cast(data.GetPointer()) != NULL); }; virtual void DoWrite(BaseData::Pointer data) { if (this->CanWriteBaseDataType(data)) { this->SetInput(dynamic_cast(data.GetPointer())); this->Update(); } } protected: /** * Constructor. */ ContourModelSetWriter(); /** * Virtual destructor. */ virtual ~ContourModelSetWriter(); /** * Writes the XML file */ virtual void GenerateData(); /** * Resizes the number of inputs of the writer. * The inputs are initialized by empty ContourModels * @param num the new number of inputs */ virtual void ResizeInputs( const unsigned int& num ); std::string m_FileName; std::string m_FilePrefix; std::string m_FilePattern; std::string m_Extension; std::string m_MimeType; bool m_Success; }; } #endif diff --git a/Modules/ContourModel/IO/mitkContourModelWriter.cpp b/Modules/ContourModel/IO/mitkContourModelWriter.cpp index 8e16efa717..8782ab9bc9 100644 --- a/Modules/ContourModel/IO/mitkContourModelWriter.cpp +++ b/Modules/ContourModel/IO/mitkContourModelWriter.cpp @@ -1,483 +1,486 @@ /*=================================================================== 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 "mitkContourModelWriter.h" #include "mitkTimeGeometry.h" #include #include #include /* * The xml file will look like: * * * * * * * * * * * * * * * * * * * */ // // Initialization of the xml tags. // const char* mitk::ContourModelWriter::XML_CONTOURMODEL = "contourModel" ; const char* mitk::ContourModelWriter::XML_HEAD = "head" ; const char* mitk::ContourModelWriter::XML_GEOMETRY_INFO = "geometryInfo" ; const char* mitk::ContourModelWriter::XML_DATA = "data"; const char* mitk::ContourModelWriter::XML_TIME_STEP = "timestep"; const char* mitk::ContourModelWriter::XML_CONTROL_POINTS = "controlPoints" ; const char* mitk::ContourModelWriter::XML_POINT = "point" ; const char* mitk::ContourModelWriter::XML_X = "x" ; const char* mitk::ContourModelWriter::XML_Y = "y" ; const char* mitk::ContourModelWriter::XML_Z = "z" ; mitk::ContourModelWriter::ContourModelWriter() : m_FileName(""), m_FilePrefix(""), m_FilePattern("") { this->SetNumberOfRequiredInputs( 1 ); this->SetNumberOfIndexedOutputs( 1 ); this->SetNthOutput( 0, mitk::ContourModel::New().GetPointer() ); m_Indent = 2; m_IndentDepth = 0; m_Success = false; } mitk::ContourModelWriter::~ContourModelWriter() {} void mitk::ContourModelWriter::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 ); // // for each input object write its xml representation to // the stream // for ( unsigned int i = 0 ; i < this->GetNumberOfInputs(); ++i ) { InputType::Pointer contourModel = this->GetInput( i ); assert( contourModel.IsNotNull() ); WriteXML( contourModel.GetPointer(), out ); } out.imbue(previousLocale); if ( !out.good() ) // some error during output { out.close(); throw std::ios_base::failure("Some error during contour writing."); } out.close(); m_Success = true; m_MimeType = "application/MITK.ContourModel"; } void mitk::ContourModelWriter::WriteXML( mitk::ContourModel* contourModel, std::ofstream& out ) { /*++++ ++++*/ WriteStartElement( XML_CONTOURMODEL, out ); /*++++ ++++*/ WriteStartElement( XML_HEAD, out); /*++++ ++++*/ WriteStartElement( XML_GEOMETRY_INFO, out); WriteGeometryInformation( contourModel->GetTimeGeometry(), out);; /*++++ ++++*/ WriteEndElement( XML_GEOMETRY_INFO, out); /*++++ ++++*/ WriteEndElement( XML_HEAD, out); /*++++ ++++*/ WriteStartElement( XML_DATA, out); unsigned int timecount = contourModel->GetTimeSteps(); for(unsigned int i=0; i< timecount; i++) { /*++++ ++++*/ std::vector at; at.push_back("n"); std::vector val; val.push_back(ConvertToString(i)); at.push_back("isClosed"); val.push_back(ConvertToString(contourModel->IsClosed())); WriteStartElementWithAttribut( XML_TIME_STEP, at, val, out ); /*++++ ++++*/ WriteStartElement(XML_CONTROL_POINTS, out); mitk::ContourModel::VertexIterator it = contourModel->IteratorBegin(); mitk::ContourModel::VertexIterator end = contourModel->IteratorEnd(); while(it != end) { mitk::ContourModel::VertexType* v = *it; /*++++ ++++*/ std::vector attr; attr.push_back("IsControlPoint"); std::vector value; value.push_back(ConvertToString(v->IsControlPoint)); WriteStartElementWithAttribut( XML_POINT, attr, value, out ); /*++++ ++++*/ WriteStartElement( XML_X, out ); WriteCharacterData( ConvertToString(v->Coordinates[0] ).c_str(), out ); /*++++ ++++*/ WriteEndElement( XML_X, out, false ); /*++++ ++++*/ WriteStartElement( XML_Y, out ); WriteCharacterData( ConvertToString( v->Coordinates[1] ).c_str(), out ); /*++++ ++++*/ WriteEndElement( XML_Y, out, false ); /*++++ ++++*/ WriteStartElement( XML_Z, out ); WriteCharacterData( ConvertToString( v->Coordinates[2] ).c_str(), out ); /*++++ ++++*/ WriteEndElement( XML_Z, out, false ); /*++++ ++++*/ WriteEndElement( XML_POINT, out ); it++; } /*++++ ++++*/ WriteEndElement(XML_CONTROL_POINTS, out); /*++++ ++++*/ WriteEndElement( XML_TIME_STEP, out ); } /*++++ ++++*/ WriteEndElement( XML_DATA, out ); /*++++ ++++*/ WriteEndElement( XML_CONTOURMODEL, out ); } void mitk::ContourModelWriter::WriteGeometryInformation( mitk::TimeGeometry* /*geometry*/, std::ofstream& out ) { WriteCharacterData("", out); } void mitk::ContourModelWriter::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::ContourModel::New().GetPointer() ); } } void mitk::ContourModelWriter::SetInput( InputType* contourModel ) { this->ProcessObject::SetNthInput( 0, contourModel ); } void mitk::ContourModelWriter::SetInput( const unsigned int& id, InputType* contourModel ) { if ( id >= this->GetNumberOfInputs() ) this->ResizeInputs( id + 1 ); this->ProcessObject::SetNthInput( id, contourModel ); } mitk::ContourModel* mitk::ContourModelWriter::GetInput() { if ( this->GetNumberOfInputs() < 1 ) { return 0; } else { return dynamic_cast ( this->GetInput( 0 ) ); } } mitk::ContourModel* mitk::ContourModelWriter::GetInput( const unsigned int& num ) { return dynamic_cast ( this->ProcessObject::GetInput( num ) ); } template < typename T> std::string mitk::ContourModelWriter::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::ContourModelWriter::WriteXMLHeader( std::ofstream &file ) { file << ""; } void mitk::ContourModelWriter::WriteStartElement( const char *const tag, std::ofstream &file ) { file << std::endl; WriteIndent( file ); file << '<' << tag << '>'; m_IndentDepth++; } void mitk::ContourModelWriter::WriteStartElementWithAttribut( const char *const tag, std::vector attributes, std::vector values, std::ofstream &file ) { file << std::endl; WriteIndent( file ); file << '<' << tag; unsigned int attributesSize = attributes.size(); unsigned int valuesSize = values.size(); if( attributesSize == valuesSize){ std::vector::iterator attributesIt = attributes.begin(); std::vector::iterator end = attributes.end(); std::vector::iterator valuesIt = values.begin(); while(attributesIt != end) { file << ' '; WriteCharacterData( *attributesIt, file); file << '=' << '"'; WriteCharacterData( *valuesIt, file); file << '"'; attributesIt++; valuesIt++; } } file << '>'; m_IndentDepth++; } void mitk::ContourModelWriter::WriteEndElement( const char *const tag, std::ofstream &file, const bool& indent ) { m_IndentDepth--; if ( indent ) { file << std::endl; WriteIndent( file ); } file << '<' << '/' << tag << '>'; } void mitk::ContourModelWriter::WriteCharacterData( const char *const data, std::ofstream &file ) { file << data; } void mitk::ContourModelWriter::WriteStartElement( std::string &tag, std::ofstream &file ) { WriteStartElement( tag.c_str(), file ); } void mitk::ContourModelWriter::WriteEndElement( std::string &tag, std::ofstream &file, const bool& indent ) { WriteEndElement( tag.c_str(), file, indent ); } void mitk::ContourModelWriter::WriteCharacterData( std::string &data, std::ofstream &file ) { WriteCharacterData( data.c_str(), file ); } void mitk::ContourModelWriter::WriteIndent( std::ofstream& file ) { std::string spaces( m_IndentDepth * m_Indent, ' ' ); file << spaces.c_str(); } bool mitk::ContourModelWriter::GetSuccess() const { - return m_Success; + return m_Success; } - +std::string mitk::ContourModelWriter::GetSupportedBaseData() const +{ + return ContourModel::GetStaticNameOfClass(); +} bool mitk::ContourModelWriter::CanWriteDataType( DataNode* input ) { if ( input ) { mitk::BaseData* data = input->GetData(); if ( data ) { mitk::ContourModel::Pointer contourModel = dynamic_cast( data ); if( contourModel.IsNotNull() ) { //this writer has no "SetDefaultExtension()" - function m_Extension = ".cnt"; return true; } } } return false; } void mitk::ContourModelWriter::SetInput( DataNode* input ) { if( input && CanWriteDataType( input ) ) this->ProcessObject::SetNthInput( 0, dynamic_cast( input->GetData() ) ); } std::string mitk::ContourModelWriter::GetWritenMIMEType() { return m_MimeType; } std::vector mitk::ContourModelWriter::GetPossibleFileExtensions() { std::vector possibleFileExtensions; possibleFileExtensions.push_back(".cnt"); return possibleFileExtensions; } std::string mitk::ContourModelWriter::GetFileExtension() { return m_Extension; } diff --git a/Modules/ContourModel/IO/mitkContourModelWriter.h b/Modules/ContourModel/IO/mitkContourModelWriter.h index af79b8d760..7b7d1ac7d5 100644 --- a/Modules/ContourModel/IO/mitkContourModelWriter.h +++ b/Modules/ContourModel/IO/mitkContourModelWriter.h @@ -1,325 +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. ===================================================================*/ #ifndef _MITK_CONTOURMODEL_WRITER__H_ #define _MITK_CONTOURMODEL_WRITER__H_ #include #include #include #include //DEPRECATED #include namespace mitk { /** * @brief XML-based writer for mitk::ContourModels * * XML-based writer for mitk::ContourModels. Multiple ContourModels can be written in * a single XML file by simply setting multiple inputs to the filter. * * The xml file will look like: * * * * * * * * * * * * * * * * * * * * * @ingroup PSIO * @ingroup Process */ class TimeSlicedGeometry; class MitkContourModel_EXPORT ContourModelWriter : public mitk::FileWriterWithInformation { public: mitkClassMacro( ContourModelWriter, mitk::FileWriter ); mitkWriterMacro; itkFactorylessNewMacro(Self) itkCloneMacro(Self) typedef mitk::ContourModel 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. */ ContourModel* GetInput(); /** * @param num the index of the desired output object. * @returns the n'th input object of the filter. */ ContourModel* GetInput( const unsigned int& num ); /** * @brief Return the possible file extensions for the data type associated with the writer */ virtual std::vector GetPossibleFileExtensions(); /** * @brief Return the extension to be added to the filename. */ virtual std::string GetFileExtension(); /** * @brief Check if the Writer can write the Content of the */ virtual bool CanWriteDataType( DataNode* ); /** * @brief Return the MimeType of the saved File. */ virtual std::string GetWritenMIMEType(); using Superclass::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; + std::string GetSupportedBaseData() const; + /*++++++ FileWriterWithInformation methods +++++++*/ virtual const char *GetDefaultFilename() { return "ContourModel.cnt"; } virtual const char *GetFileDialogPattern() { return "MITK ContourModel (*.cnt)"; } virtual const char *GetDefaultExtension() { return ".cnt"; } virtual bool CanWriteBaseDataType(BaseData::Pointer data) { return (dynamic_cast(data.GetPointer()) != NULL); }; virtual void DoWrite(BaseData::Pointer data) { if (this->CanWriteBaseDataType(data)) { this->SetInput(dynamic_cast(data.GetPointer())); this->Update(); } } protected: /** * Constructor. */ ContourModelWriter(); /** * Virtual destructor. */ virtual ~ContourModelWriter(); /** * Writes the XML file */ virtual void GenerateData(); /** * Resizes the number of inputs of the writer. * The inputs are initialized by empty ContourModels * @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 < typename T> 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 contourModel the point set to be converted to xml * @param out the stream to write to. */ void WriteXML( mitk::ContourModel* contourModel, std::ofstream& out ); /** * Writes the geometry information of the TimeGeometry to an outstream. * The root tag is not included. * @param geometry the TimeGeometry of the contour. * @param the stream to write to. */ void WriteGeometryInformation( mitk::TimeGeometry* geometry, std::ofstream& out ); /** * Writes the geometry information of the TimeGeometry to an outstream. * The root tag is not included. * @param geometry the TimeGeometry of the contour. * @param the stream to write to. * * \deprecatedSince{2013_09} Please use TimeGeometry instead of TimeSlicedGeometry. For more information see http://www.mitk.org/Development/Refactoring%20of%20the%20Geometry%20Classes%20-%20Part%201 */ DEPRECATED(void WriteGeometryInformation( mitk::TimeSlicedGeometry* geometry, 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 ); void WriteStartElementWithAttribut( const char *const tag, std::vector attributes, std::vector values, 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_CONTOURMODEL; static const char* XML_HEAD; static const char* XML_GEOMETRY_INFO; static const char* XML_DATA; static const char* XML_TIME_STEP; static const char* XML_CONTROL_POINTS; static const char* XML_POINT; static const char* XML_X; static const char* XML_Y; static const char* XML_Z; }; } #endif diff --git a/Modules/DiffusionImaging/Connectomics/Testing/mitkConnectomicsNetworkCreationTest.cpp b/Modules/DiffusionImaging/Connectomics/Testing/mitkConnectomicsNetworkCreationTest.cpp index 58bc9b97f5..010261f01e 100644 --- a/Modules/DiffusionImaging/Connectomics/Testing/mitkConnectomicsNetworkCreationTest.cpp +++ b/Modules/DiffusionImaging/Connectomics/Testing/mitkConnectomicsNetworkCreationTest.cpp @@ -1,119 +1,113 @@ /*=================================================================== 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. ===================================================================*/ // Testing #include "mitkTestingMacros.h" #include "mitkTestFixture.h" // std includes #include // MITK includes -#include #include "mitkConnectomicsNetworkCreator.h" -#include +#include "mitkIOUtil.h" // VTK includes #include class mitkConnectomicsNetworkCreationTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkConnectomicsNetworkCreationTestSuite); /// \todo Fix VTK memory leaks. Bug 18097. vtkDebugLeaks::SetExitError(0); MITK_TEST(CreateNetworkFromFibersAndParcellation); CPPUNIT_TEST_SUITE_END(); private: std::string m_ParcellationPath; std::string m_FiberPath; std::string m_ReferenceNetworkPath; public: /** * @brief Setup Always call this method before each Test-case to ensure correct and new intialization of the used members for a new test case. (If the members are not used in a test, the method does not need to be called). */ void setUp() { m_ReferenceNetworkPath = GetTestDataFilePath("DiffusionImaging/Connectomics/reference.cnf"); m_ParcellationPath = GetTestDataFilePath("DiffusionImaging/Connectomics/parcellation.nrrd"); m_FiberPath = GetTestDataFilePath("DiffusionImaging/Connectomics/fiberBundle.fib"); } void tearDown() { m_ReferenceNetworkPath = ""; m_ParcellationPath = ""; m_FiberPath = ""; } void CreateNetworkFromFibersAndParcellation() { - const std::string s1="", s2=""; - // load fiber image - std::vector fiberInfile = - mitk::BaseDataIO::LoadBaseDataFromFile( m_FiberPath, s1, s2, false ); + std::vector fiberInfile = mitk::IOUtil::Load( m_FiberPath ); if( fiberInfile.empty() ) { std::string errorMessage = "Fiber Image at " + m_FiberPath + " could not be read. Aborting."; CPPUNIT_ASSERT_MESSAGE( errorMessage, false ); } mitk::BaseData* fiberBaseData = fiberInfile.at(0); mitk::FiberBundleX* fiberBundle = dynamic_cast( fiberBaseData ); // load parcellation - std::vector parcellationInFile = - mitk::BaseDataIO::LoadBaseDataFromFile( m_ParcellationPath, s1, s2, false ); + std::vector parcellationInFile = mitk::IOUtil::Load( m_ParcellationPath ); if( parcellationInFile.empty() ) { std::string errorMessage = "Parcellation at " + m_ParcellationPath + " could not be read. Aborting."; CPPUNIT_ASSERT_MESSAGE( errorMessage, false ); } mitk::BaseData* parcellationBaseData = parcellationInFile.at(0); mitk::Image* parcellationImage = dynamic_cast( parcellationBaseData ); // do creation mitk::ConnectomicsNetworkCreator::Pointer connectomicsNetworkCreator = mitk::ConnectomicsNetworkCreator::New(); connectomicsNetworkCreator->SetSegmentation( parcellationImage ); connectomicsNetworkCreator->SetFiberBundle( fiberBundle ); connectomicsNetworkCreator->CalculateCenterOfMass(); connectomicsNetworkCreator->SetEndPointSearchRadius( 15 ); connectomicsNetworkCreator->CreateNetworkFromFibersAndSegmentation(); // load network - std::vector referenceFile = - mitk::BaseDataIO::LoadBaseDataFromFile( m_ReferenceNetworkPath, s1, s2, false ); + std::vector referenceFile = mitk::IOUtil::Load( m_ReferenceNetworkPath ); if( referenceFile.empty() ) { std::string errorMessage = "Reference Network at " + m_ReferenceNetworkPath + " could not be read. Aborting."; CPPUNIT_ASSERT_MESSAGE( errorMessage, false ); } mitk::BaseData* referenceBaseData = referenceFile.at(0); mitk::ConnectomicsNetwork* referenceNetwork = dynamic_cast( referenceBaseData ); mitk::ConnectomicsNetwork::Pointer network = connectomicsNetworkCreator->GetNetwork(); CPPUNIT_ASSERT_MESSAGE( "Comparing created and reference network.", mitk::Equal( network.GetPointer(), referenceNetwork, mitk::eps, true) ); } }; MITK_TEST_SUITE_REGISTRATION(mitkConnectomicsNetworkCreation) diff --git a/Modules/DiffusionImaging/Connectomics/Testing/mitkConnectomicsStatisticsCalculatorTest.cpp b/Modules/DiffusionImaging/Connectomics/Testing/mitkConnectomicsStatisticsCalculatorTest.cpp index 102c26eeb1..e8a219c615 100644 --- a/Modules/DiffusionImaging/Connectomics/Testing/mitkConnectomicsStatisticsCalculatorTest.cpp +++ b/Modules/DiffusionImaging/Connectomics/Testing/mitkConnectomicsStatisticsCalculatorTest.cpp @@ -1,143 +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. ===================================================================*/ // Testing #include "mitkTestingMacros.h" #include "mitkTestFixture.h" // std includes #include #include // MITK includes -#include +#include #include // VTK includes #include class mitkConnectomicsStatisticsCalculatorTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkConnectomicsStatisticsCalculatorTestSuite); /// \todo Fix VTK memory leaks. Bug 18097. vtkDebugLeaks::SetExitError(0); MITK_TEST(StatisticsCalculatorUpdate); CPPUNIT_TEST_SUITE_END(); private: mitk::ConnectomicsNetwork::Pointer m_Network; std::string m_NetworkPath; public: /** * @brief Setup Always call this method before each Test-case to ensure correct and new intialization of the used members for a new test case. (If the members are not used in a test, the method does not need to be called). */ void setUp() { //load network m_NetworkPath = GetTestDataFilePath("DiffusionImaging/Connectomics/reference.cnf"); - const std::string s1="", s2=""; - std::vector networkFile = - mitk::BaseDataIO::LoadBaseDataFromFile( m_NetworkPath, s1, s2, false ); + std::vector networkFile = mitk::IOUtil::Load( m_NetworkPath ); if( networkFile.empty() ) { std::string errorMessage = "File at " + m_NetworkPath + " could not be read. Aborting."; CPPUNIT_ASSERT_MESSAGE( errorMessage, !networkFile.empty() ); return; } mitk::BaseData* networkBaseData = networkFile.at(0); mitk::ConnectomicsNetwork* network = dynamic_cast( networkBaseData ); if( !network ) { std::string errorMessage = "Read file at " + m_NetworkPath + " could not be recognized as network. Aborting."; CPPUNIT_ASSERT_MESSAGE( errorMessage, network); return; } m_Network = network; } void tearDown() { m_Network = NULL; m_NetworkPath = ""; } void StatisticsCalculatorUpdate() { mitk::ConnectomicsStatisticsCalculator::Pointer statisticsCalculator = mitk::ConnectomicsStatisticsCalculator::New(); statisticsCalculator->SetNetwork( m_Network ); statisticsCalculator->Update(); double eps( 0.0001 ); CPPUNIT_ASSERT_MESSAGE( "GetNumberOfVertices", mitk::Equal( statisticsCalculator->GetNumberOfVertices( ), 4 , eps, true ) ); CPPUNIT_ASSERT_MESSAGE( "GetNumberOfEdges" , mitk::Equal( statisticsCalculator->GetNumberOfEdges( ), 5 , eps, true ) ); CPPUNIT_ASSERT_MESSAGE( "GetAverageDegree", mitk::Equal( statisticsCalculator->GetAverageDegree( ), 2.5 , eps, true ) ); CPPUNIT_ASSERT_MESSAGE( "GetConnectionDensity", mitk::Equal( statisticsCalculator->GetConnectionDensity( ), 0.833333 , eps, true ) ); CPPUNIT_ASSERT_MESSAGE( "GetNumberOfConnectedComponents", mitk::Equal( statisticsCalculator->GetNumberOfConnectedComponents( ), 1 , eps, true ) ); CPPUNIT_ASSERT_MESSAGE( "GetAverageComponentSize", mitk::Equal( statisticsCalculator->GetAverageComponentSize( ), 4 , eps, true ) ); CPPUNIT_ASSERT_MESSAGE( "GetLargestComponentSize", mitk::Equal( statisticsCalculator->GetLargestComponentSize( ), 4 , eps, true ) ); CPPUNIT_ASSERT_MESSAGE( "GetRatioOfNodesInLargestComponent", mitk::Equal( statisticsCalculator->GetRatioOfNodesInLargestComponent( ), 1 , eps, true ) ); CPPUNIT_ASSERT_MESSAGE( "GetHopPlotExponent", mitk::Equal( statisticsCalculator->GetHopPlotExponent( ), 0.192645 , eps, true ) ); CPPUNIT_ASSERT_MESSAGE( "GetEffectiveHopDiameter", mitk::Equal( statisticsCalculator->GetEffectiveHopDiameter( ), 1 , eps, true ) ); CPPUNIT_ASSERT_MESSAGE( "GetAverageClusteringCoefficientsC", mitk::Equal( statisticsCalculator->GetAverageClusteringCoefficientsC( ), 0.833333 , eps, true ) ); CPPUNIT_ASSERT_MESSAGE( "GetAverageClusteringCoefficientsD", mitk::Equal( statisticsCalculator->GetAverageClusteringCoefficientsD( ), 0.916667 , eps, true ) ); CPPUNIT_ASSERT_MESSAGE( "GetAverageClusteringCoefficientsE", mitk::Equal( statisticsCalculator->GetAverageClusteringCoefficientsE( ), 0.833333 , eps, true ) ); CPPUNIT_ASSERT_MESSAGE( "GetAverageVertexBetweennessCentrality", mitk::Equal( statisticsCalculator->GetAverageVertexBetweennessCentrality( ), 0.25 , eps, true ) ); CPPUNIT_ASSERT_MESSAGE( "GetAverageEdgeBetweennessCentrality", mitk::Equal( statisticsCalculator->GetAverageEdgeBetweennessCentrality( ), 1.4 , eps, true ) ); CPPUNIT_ASSERT_MESSAGE( "GetNumberOfIsolatedPoints" , mitk::Equal( statisticsCalculator->GetNumberOfIsolatedPoints( ), 0 , eps, true ) ); CPPUNIT_ASSERT_MESSAGE( "GetRatioOfIsolatedPoints", mitk::Equal( statisticsCalculator->GetRatioOfIsolatedPoints( ), 0 , eps, true ) ); CPPUNIT_ASSERT_MESSAGE( "GetNumberOfEndPoints", mitk::Equal( statisticsCalculator->GetNumberOfEndPoints( ), 0 , eps, true ) ); CPPUNIT_ASSERT_MESSAGE( "GetRatioOfEndPoints", mitk::Equal( statisticsCalculator->GetRatioOfEndPoints( ), 0 , eps, true ) ); CPPUNIT_ASSERT_MESSAGE( "GetDiameter", mitk::Equal( statisticsCalculator->GetDiameter( ), 2 , eps, true ) ); CPPUNIT_ASSERT_MESSAGE( "GetDiameter90", mitk::Equal( statisticsCalculator->GetDiameter90( ), 2 , eps, true ) ); CPPUNIT_ASSERT_MESSAGE( "GetRadius" , mitk::Equal( statisticsCalculator->GetRadius( ), 1 , eps, true ) ); CPPUNIT_ASSERT_MESSAGE( "GetRadius90", mitk::Equal( statisticsCalculator->GetRadius90( ), 1 , eps, true ) ); CPPUNIT_ASSERT_MESSAGE( "GetAverageEccentricity", mitk::Equal( statisticsCalculator->GetAverageEccentricity( ), 1.5 , eps, true ) ); CPPUNIT_ASSERT_MESSAGE( "GetAverageEccentricity90", mitk::Equal( statisticsCalculator->GetAverageEccentricity90( ), 1.5 , eps, true ) ); CPPUNIT_ASSERT_MESSAGE( "GetAveragePathLength" , mitk::Equal( statisticsCalculator->GetAveragePathLength( ), 1.16667 , eps, true ) ); CPPUNIT_ASSERT_MESSAGE( "GetNumberOfCentralPoints" , mitk::Equal( statisticsCalculator->GetNumberOfCentralPoints( ), 2 , eps, true ) ); CPPUNIT_ASSERT_MESSAGE( "GetRatioOfCentralPoints", mitk::Equal( statisticsCalculator->GetRatioOfCentralPoints( ), 0.5 , eps, true ) ); // CPPUNIT_ASSERT_MESSAGE( " ", mitk::Equal( statisticsCalculator->GetSpectralRadius( ), , eps, true ) ); // CPPUNIT_ASSERT_MESSAGE( " ", mitk::Equal( statisticsCalculator->GetSecondLargestEigenValue( ), , eps, true ) ); // CPPUNIT_ASSERT_MESSAGE( " ", mitk::Equal( statisticsCalculator->GetAdjacencyTrace( ), , eps, true ) ); // CPPUNIT_ASSERT_MESSAGE( " ", mitk::Equal( statisticsCalculator->GetAdjacencyEnergy( ), , eps, true ) ); // CPPUNIT_ASSERT_MESSAGE( " ", mitk::Equal( statisticsCalculator->GetLaplacianTrace( ), , eps, true ) ); // CPPUNIT_ASSERT_MESSAGE( " ", mitk::Equal( statisticsCalculator->GetLaplacianEnergy( ), , eps, true ) ); // CPPUNIT_ASSERT_MESSAGE( " ", mitk::Equal( statisticsCalculator->GetLaplacianSpectralGap( ), , eps, true ) ); // CPPUNIT_ASSERT_MESSAGE( " ", mitk::Equal( statisticsCalculator->GetNormalizedLaplacianTrace( ), , eps, true ) ); // CPPUNIT_ASSERT_MESSAGE( " ", mitk::Equal( statisticsCalculator->GetNormalizedLaplacianEnergy( ), , eps, true ) ); // CPPUNIT_ASSERT_MESSAGE( " ", mitk::Equal( statisticsCalculator->GetNormalizedLaplacianNumberOf2s( ), , eps, true ) ); // CPPUNIT_ASSERT_MESSAGE( " ", mitk::Equal( statisticsCalculator->GetNormalizedLaplacianNumberOf1s( ), , eps, true ) ); // CPPUNIT_ASSERT_MESSAGE( " ", mitk::Equal( statisticsCalculator->GetNormalizedLaplacianNumberOf0s( ), , eps, true ) ); // CPPUNIT_ASSERT_MESSAGE( " ", mitk::Equal( statisticsCalculator->GetNormalizedLaplacianLowerSlope( ), , eps, true ) ); // CPPUNIT_ASSERT_MESSAGE( " ", mitk::Equal( statisticsCalculator->GetNormalizedLaplacianUpperSlope( ), , eps, true ) ); CPPUNIT_ASSERT_MESSAGE( "GetSmallWorldness", mitk::Equal( statisticsCalculator->GetSmallWorldness( ), 1.72908 , eps, true ) ); } }; MITK_TEST_SUITE_REGISTRATION(mitkConnectomicsStatisticsCalculator) diff --git a/Modules/DiffusionImaging/DiffusionCore/IODataStructures/DiffusionWeightedImages/mitkNrrdDiffusionImageWriter.cpp b/Modules/DiffusionImaging/DiffusionCore/IODataStructures/DiffusionWeightedImages/mitkNrrdDiffusionImageWriter.cpp index 2d6fa9cfe9..7307bf83e2 100644 --- a/Modules/DiffusionImaging/DiffusionCore/IODataStructures/DiffusionWeightedImages/mitkNrrdDiffusionImageWriter.cpp +++ b/Modules/DiffusionImaging/DiffusionCore/IODataStructures/DiffusionWeightedImages/mitkNrrdDiffusionImageWriter.cpp @@ -1,328 +1,334 @@ /*=================================================================== 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 __mitkNrrdDiffusionImageWriter__cpp #define __mitkNrrdDiffusionImageWriter__cpp #include "mitkNrrdDiffusionImageWriter.h" #include "itkMetaDataDictionary.h" #include "itkMetaDataObject.h" #include "itkNrrdImageIO.h" #include "itkNiftiImageIO.h" #include "itkImageFileWriter.h" #include "itksys/SystemTools.hxx" #include #include template mitk::NrrdDiffusionImageWriter::NrrdDiffusionImageWriter() : m_FileName(""), m_FilePrefix(""), m_FilePattern(""), m_Success(false) { this->SetNumberOfRequiredInputs( 1 ); } template mitk::NrrdDiffusionImageWriter::~NrrdDiffusionImageWriter() {} template void mitk::NrrdDiffusionImageWriter::GenerateData() { m_Success = false; InputType* input = this->GetInput(); if (input == NULL) { itkWarningMacro(<<"Sorry, input to NrrdDiffusionImageWriter is NULL!"); return; } if ( m_FileName == "" ) { itkWarningMacro( << "Sorry, filename has not been set!" ); return ; } const std::string& locale = "C"; const std::string& currLocale = setlocale( LC_ALL, NULL ); if ( locale.compare(currLocale)!=0 ) { try { setlocale(LC_ALL, locale.c_str()); } catch(...) { MITK_INFO << "Could not set locale " << locale; } } char keybuffer[512]; char valbuffer[512]; //itk::MetaDataDictionary dic = input->GetImage()->GetMetaDataDictionary(); vnl_matrix_fixed measurementFrame = input->GetMeasurementFrame(); if (measurementFrame(0,0) || measurementFrame(0,1) || measurementFrame(0,2) || measurementFrame(1,0) || measurementFrame(1,1) || measurementFrame(1,2) || measurementFrame(2,0) || measurementFrame(2,1) || measurementFrame(2,2)) { sprintf( valbuffer, " (%lf,%lf,%lf) (%lf,%lf,%lf) (%lf,%lf,%lf)", measurementFrame(0,0), measurementFrame(0,1), measurementFrame(0,2), measurementFrame(1,0), measurementFrame(1,1), measurementFrame(1,2), measurementFrame(2,0), measurementFrame(2,1), measurementFrame(2,2)); itk::EncapsulateMetaData(input->GetVectorImage()->GetMetaDataDictionary(),std::string("measurement frame"),std::string(valbuffer)); } sprintf( valbuffer, "DWMRI"); itk::EncapsulateMetaData(input->GetVectorImage()->GetMetaDataDictionary(),std::string("modality"),std::string(valbuffer)); if(input->GetDirections()->Size()) { sprintf( valbuffer, "%1f", input->GetReferenceBValue() ); itk::EncapsulateMetaData(input->GetVectorImage()->GetMetaDataDictionary(),std::string("DWMRI_b-value"),std::string(valbuffer)); } for(unsigned int i=0; iGetDirections()->Size(); i++) { sprintf( keybuffer, "DWMRI_gradient_%04d", i ); /*if(itk::ExposeMetaData(input->GetMetaDataDictionary(), std::string(keybuffer),tmp)) continue;*/ sprintf( valbuffer, "%1f %1f %1f", input->GetDirections()->ElementAt(i).get(0), input->GetDirections()->ElementAt(i).get(1), input->GetDirections()->ElementAt(i).get(2)); itk::EncapsulateMetaData(input->GetVectorImage()->GetMetaDataDictionary(),std::string(keybuffer),std::string(valbuffer)); } typedef itk::VectorImage ImageType; std::string ext = itksys::SystemTools::GetFilenameLastExtension(m_FileName); ext = itksys::SystemTools::LowerCase(ext); if (ext == ".hdwi" || ext == ".dwi") { itk::NrrdImageIO::Pointer io = itk::NrrdImageIO::New(); //io->SetNrrdVectorType( nrrdKindList ); io->SetFileType( itk::ImageIOBase::Binary ); io->UseCompressionOn(); typedef itk::ImageFileWriter WriterType; typename WriterType::Pointer nrrdWriter = WriterType::New(); nrrdWriter->UseInputMetaDataDictionaryOn(); nrrdWriter->SetInput( input->GetVectorImage() ); nrrdWriter->SetImageIO(io); nrrdWriter->SetFileName(m_FileName); nrrdWriter->UseCompressionOn(); nrrdWriter->SetImageIO(io); try { nrrdWriter->Update(); } catch (itk::ExceptionObject e) { std::cout << e << std::endl; throw; } } else if (ext == ".fsl" || ext == ".fslgz") { MITK_INFO << "Writing Nifti-Image for FSL"; typename ImageType::Pointer vecimg = input->GetVectorImage(); typedef itk::Image ImageType4D; typename ImageType4D::Pointer img4 = ImageType4D::New(); typename ImageType::SpacingType spacing = vecimg->GetSpacing(); typename ImageType4D::SpacingType spacing4; for(int i=0; i<3; i++) spacing4[i] = spacing[i]; spacing4[3] = 1; img4->SetSpacing( spacing4 ); // Set the image spacing typename ImageType::PointType origin = vecimg->GetOrigin(); typename ImageType4D::PointType origin4; for(int i=0; i<3; i++) origin4[i] = origin[i]; origin4[3] = 0; img4->SetOrigin( origin4 ); // Set the image origin typename ImageType::DirectionType direction = vecimg->GetDirection(); typename ImageType4D::DirectionType direction4; for(int i=0; i<3; i++) for(int j=0; j<3; j++) direction4[i][j] = direction[i][j]; for(int i=0; i<4; i++) direction4[i][3] = 0; for(int i=0; i<4; i++) direction4[3][i] = 0; direction4[3][3] = 1; img4->SetDirection( direction4 ); // Set the image direction typename ImageType::RegionType region = vecimg->GetLargestPossibleRegion(); typename ImageType4D::RegionType region4; typename ImageType::RegionType::SizeType size = region.GetSize(); typename ImageType4D::RegionType::SizeType size4; for(int i=0; i<3; i++) size4[i] = size[i]; size4[3] = vecimg->GetVectorLength(); typename ImageType::RegionType::IndexType index = region.GetIndex(); typename ImageType4D::RegionType::IndexType index4; for(int i=0; i<3; i++) index4[i] = index[i]; index4[3] = 0; region4.SetSize(size4); region4.SetIndex(index4); img4->SetRegions( region4 ); img4->Allocate(); itk::ImageRegionIterator it (vecimg, vecimg->GetLargestPossibleRegion() ); typedef typename ImageType::PixelType VecPixType; for (it.GoToBegin(); !it.IsAtEnd(); ++it) { VecPixType vec = it.Get(); typename ImageType::IndexType currentIndex = it.GetIndex(); for(unsigned int ind=0; indSetPixel(index4, vec[ind]); } } // create copy of file with correct ending for mitk std::string fname3 = m_FileName; std::string::iterator itend = fname3.end(); if (ext == ".fsl") fname3.replace( itend-3, itend, "nii"); else fname3.replace( itend-5, itend, "nii.gz"); itk::NiftiImageIO::Pointer io4 = itk::NiftiImageIO::New(); typedef itk::VectorImage ImageType; typedef itk::ImageFileWriter WriterType4; typename WriterType4::Pointer nrrdWriter4 = WriterType4::New(); nrrdWriter4->UseInputMetaDataDictionaryOn(); nrrdWriter4->SetInput( img4 ); nrrdWriter4->SetFileName(fname3); nrrdWriter4->UseCompressionOn(); nrrdWriter4->SetImageIO(io4); try { nrrdWriter4->Update(); } catch (itk::ExceptionObject e) { std::cout << e << std::endl; throw; } itksys::SystemTools::CopyAFile(fname3.c_str(), m_FileName.c_str()); if(input->GetDirections()->Size()) { std::ofstream myfile; std::string fname = m_FileName; fname += ".bvals"; myfile.open (fname.c_str()); for(unsigned int i=0; iGetDirections()->Size(); i++) { double twonorm = input->GetDirections()->ElementAt(i).two_norm(); myfile << input->GetReferenceBValue()*twonorm*twonorm << " "; } myfile.close(); std::ofstream myfile2; std::string fname2 = m_FileName; fname2 += ".bvecs"; myfile2.open (fname2.c_str()); for(int j=0; j<3; j++) { for(unsigned int i=0; iGetDirections()->Size(); i++) { //need to modify the length typename mitk::DiffusionImage::GradientDirectionContainerType::Pointer grads = input->GetDirections(); typename mitk::DiffusionImage::GradientDirectionType direction = grads->ElementAt(i); direction.normalize(); myfile2 << direction.get(j) << " "; //myfile2 << input->GetDirections()->ElementAt(i).get(j) << " "; } myfile2 << std::endl; } std::ofstream myfile3; std::string fname4 = m_FileName; fname4 += ".ttk"; myfile3.open (fname4.c_str()); for(unsigned int i=0; iGetDirections()->Size(); i++) { for(int j=0; j<3; j++) { myfile3 << input->GetDirections()->ElementAt(i).get(j) << " "; } myfile3 << std::endl; } } } try { setlocale(LC_ALL, currLocale.c_str()); } catch(...) { MITK_INFO << "Could not reset locale " << currLocale; } m_Success = true; } template void mitk::NrrdDiffusionImageWriter::SetInput( InputType* diffVolumes ) { this->ProcessObject::SetNthInput( 0, diffVolumes ); } template mitk::DiffusionImage* mitk::NrrdDiffusionImageWriter::GetInput() { if ( this->GetNumberOfInputs() < 1 ) { return NULL; } else { return dynamic_cast ( this->ProcessObject::GetInput( 0 ) ); } } template std::vector mitk::NrrdDiffusionImageWriter::GetPossibleFileExtensions() { std::vector possibleFileExtensions; possibleFileExtensions.push_back(".dwi"); possibleFileExtensions.push_back(".hdwi"); possibleFileExtensions.push_back(".fsl"); possibleFileExtensions.push_back(".fslgz"); return possibleFileExtensions; } +template +std::string mitk::NrrdDiffusionImageWriter::GetSupportedBaseData() const +{ + return DiffusionImage::GetStaticNameOfClass(); +} + #endif //__mitkNrrdDiffusionImageWriter__cpp diff --git a/Modules/DiffusionImaging/DiffusionCore/IODataStructures/DiffusionWeightedImages/mitkNrrdDiffusionImageWriter.h b/Modules/DiffusionImaging/DiffusionCore/IODataStructures/DiffusionWeightedImages/mitkNrrdDiffusionImageWriter.h index f000a54ccc..4d3204f3fd 100644 --- a/Modules/DiffusionImaging/DiffusionCore/IODataStructures/DiffusionWeightedImages/mitkNrrdDiffusionImageWriter.h +++ b/Modules/DiffusionImaging/DiffusionCore/IODataStructures/DiffusionWeightedImages/mitkNrrdDiffusionImageWriter.h @@ -1,138 +1,140 @@ /*=================================================================== 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_NRRDDIFFVOL_WRITER__H_ #define _MITK_NRRDDIFFVOL_WRITER__H_ #include #include #include namespace mitk { /** * Writes diffusion volumes to a file * @ingroup Process */ template < class TPixelType > class NrrdDiffusionImageWriter : public mitk::FileWriterWithInformation { public: mitkClassMacro( NrrdDiffusionImageWriter, mitk::FileWriterWithInformation ); mitkWriterMacro; itkFactorylessNewMacro(Self) itkCloneMacro(Self) typedef mitk::DiffusionImage InputType; /** * Sets the filename of the file to write. * @param FileName the name of the file to write. */ itkSetStringMacro( FileName ); /** * @returns the name of the file to be written to disk. */ itkGetStringMacro( FileName ); /** * @warning multiple write not (yet) supported */ itkSetStringMacro( FilePrefix ); /** * @warning multiple write not (yet) supported */ itkGetStringMacro( FilePrefix ); /** * @warning multiple write not (yet) supported */ itkSetStringMacro( FilePattern ); /** * @warning multiple write not (yet) supported */ itkGetStringMacro( FilePattern ); /** * Sets the input object for the filter. * @param input the diffusion volumes to write to file. */ using itk::ProcessObject::SetInput; void SetInput( InputType* input ); /** * @returns the 0'th input object of the filter. */ InputType* GetInput(); /** * Returns false if an error happened during writing */ itkGetMacro( Success, bool ); /** * @return possible file extensions for the data type associated with the writer */ virtual std::vector GetPossibleFileExtensions(); + std::string GetSupportedBaseData() const; + // FileWriterWithInformation methods virtual const char * GetDefaultFilename() { return "DiffusionWeightedImages.dwi"; } virtual const char * GetFileDialogPattern() { return "Diffusion Weighted Images (*.dwi *.hdwi *.fsl)"; } virtual const char * GetDefaultExtension() { return ".dwi"; } virtual bool CanWriteBaseDataType(BaseData::Pointer data) { return (dynamic_cast*>(data.GetPointer()) != NULL); } virtual void DoWrite(BaseData::Pointer data) { if (CanWriteBaseDataType(data)) { this->SetInput(dynamic_cast*>(data.GetPointer())); this->Update(); } } protected: NrrdDiffusionImageWriter(); virtual ~NrrdDiffusionImageWriter(); virtual void GenerateData(); std::string m_FileName; std::string m_FilePrefix; std::string m_FilePattern; bool m_Success; }; } // end of namespace mitk #include "mitkNrrdDiffusionImageWriter.cpp" #endif diff --git a/Modules/DiffusionImaging/DiffusionCore/Testing/CMakeLists.txt b/Modules/DiffusionImaging/DiffusionCore/Testing/CMakeLists.txt index e2c2f866b2..c3fa88b681 100644 --- a/Modules/DiffusionImaging/DiffusionCore/Testing/CMakeLists.txt +++ b/Modules/DiffusionImaging/DiffusionCore/Testing/CMakeLists.txt @@ -1,6 +1,16 @@ +# The DiffusionCore tests need relaxed compiler flags... +# TODO fix tests to compile without these additional no-error flags +if(MSVC_VERSION) + # disable deprecated warnings (they would lead to errors) + mitkFunctionCheckCAndCXXCompilerFlags("/wd4996" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) +else() + mitkFunctionCheckCAndCXXCompilerFlags("-Wno-error=deprecated" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) + mitkFunctionCheckCAndCXXCompilerFlags("-Wno-error=deprecated-declarations" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) +endif() + MITK_CREATE_MODULE_TESTS() if(TARGET ${TESTDRIVER}) mitk_use_modules(TARGET ${TESTDRIVER} PACKAGES ITK|ITKIOTransformBase+ITKDiffusionTensorImage) mitkAddCustomModuleTest(mitkImageReconstructionTest mitkImageReconstructionTest ${MITK_DATA_DIR}/DiffusionImaging/ImageReconstruction/test.dwi ${MITK_DATA_DIR}/DiffusionImaging/ImageReconstruction/test_dti.dti ${MITK_DATA_DIR}/DiffusionImaging/ImageReconstruction/test_QN0.qbi ${MITK_DATA_DIR}/DiffusionImaging/ImageReconstruction/test_QA0.qbi ${MITK_DATA_DIR}/DiffusionImaging/ImageReconstruction/test_QA6.qbi ${MITK_DATA_DIR}/DiffusionImaging/ImageReconstruction/test_QA4.qbi ${MITK_DATA_DIR}/DiffusionImaging/ImageReconstruction/test_QA5.qbi) endif() diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkConnectomicsNetworkWriter.cpp b/Modules/DiffusionImaging/DiffusionIO/mitkConnectomicsNetworkWriter.cpp index b23be02b53..c082c6d90c 100644 --- a/Modules/DiffusionImaging/DiffusionIO/mitkConnectomicsNetworkWriter.cpp +++ b/Modules/DiffusionImaging/DiffusionIO/mitkConnectomicsNetworkWriter.cpp @@ -1,157 +1,162 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkConnectomicsNetworkWriter.h" #include "mitkConnectomicsNetworkDefinitions.h" #include #include "itksys/SystemTools.hxx" mitk::ConnectomicsNetworkWriter::ConnectomicsNetworkWriter() : m_FileName(""), m_FilePrefix(""), m_FilePattern(""), m_Success(false) { this->SetNumberOfRequiredInputs( 1 ); } mitk::ConnectomicsNetworkWriter::~ConnectomicsNetworkWriter() {} void mitk::ConnectomicsNetworkWriter::GenerateData() { MITK_INFO << "Writing connectomics network"; m_Success = false; InputType* input = this->GetInput(); if (input == NULL) { itkWarningMacro(<<"Sorry, input to ConnectomicsNetworkWriter is NULL!"); return; } if ( m_FileName == "" ) { itkWarningMacro( << "Sorry, filename has not been set!" ); return ; } std::string ext = itksys::SystemTools::GetFilenameLastExtension(m_FileName); ext = itksys::SystemTools::LowerCase(ext); if (ext == ".cnf") { // Get geometry of the network mitk::BaseGeometry* geometry = input->GetGeometry(); // Create XML document TiXmlDocument documentXML; { // begin document TiXmlDeclaration* declXML = new TiXmlDeclaration( "1.0", "", "" ); // TODO what to write here? encoding? etc.... documentXML.LinkEndChild( declXML ); TiXmlElement* mainXML = new TiXmlElement(mitk::ConnectomicsNetworkDefinitions::XML_CONNECTOMICS_FILE); mainXML->SetAttribute(mitk::ConnectomicsNetworkDefinitions::XML_FILE_VERSION, mitk::ConnectomicsNetworkDefinitions::VERSION_STRING); documentXML.LinkEndChild(mainXML); TiXmlElement* geometryXML = new TiXmlElement(mitk::ConnectomicsNetworkDefinitions::XML_GEOMETRY); { // begin geometry geometryXML->SetDoubleAttribute(mitk::ConnectomicsNetworkDefinitions::XML_MATRIX_XX, geometry->GetMatrixColumn(0)[0]); geometryXML->SetDoubleAttribute(mitk::ConnectomicsNetworkDefinitions::XML_MATRIX_XY, geometry->GetMatrixColumn(0)[1]); geometryXML->SetDoubleAttribute(mitk::ConnectomicsNetworkDefinitions::XML_MATRIX_XZ, geometry->GetMatrixColumn(0)[2]); geometryXML->SetDoubleAttribute(mitk::ConnectomicsNetworkDefinitions::XML_MATRIX_YX, geometry->GetMatrixColumn(1)[0]); geometryXML->SetDoubleAttribute(mitk::ConnectomicsNetworkDefinitions::XML_MATRIX_YY, geometry->GetMatrixColumn(1)[1]); geometryXML->SetDoubleAttribute(mitk::ConnectomicsNetworkDefinitions::XML_MATRIX_YZ, geometry->GetMatrixColumn(1)[2]); geometryXML->SetDoubleAttribute(mitk::ConnectomicsNetworkDefinitions::XML_MATRIX_ZX, geometry->GetMatrixColumn(2)[0]); geometryXML->SetDoubleAttribute(mitk::ConnectomicsNetworkDefinitions::XML_MATRIX_ZY, geometry->GetMatrixColumn(2)[1]); geometryXML->SetDoubleAttribute(mitk::ConnectomicsNetworkDefinitions::XML_MATRIX_ZZ, geometry->GetMatrixColumn(2)[2]); geometryXML->SetDoubleAttribute(mitk::ConnectomicsNetworkDefinitions::XML_ORIGIN_X, geometry->GetOrigin()[0]); geometryXML->SetDoubleAttribute(mitk::ConnectomicsNetworkDefinitions::XML_ORIGIN_Y, geometry->GetOrigin()[1]); geometryXML->SetDoubleAttribute(mitk::ConnectomicsNetworkDefinitions::XML_ORIGIN_Z, geometry->GetOrigin()[2]); geometryXML->SetDoubleAttribute(mitk::ConnectomicsNetworkDefinitions::XML_SPACING_X, geometry->GetSpacing()[0]); geometryXML->SetDoubleAttribute(mitk::ConnectomicsNetworkDefinitions::XML_SPACING_Y, geometry->GetSpacing()[1]); geometryXML->SetDoubleAttribute(mitk::ConnectomicsNetworkDefinitions::XML_SPACING_Z, geometry->GetSpacing()[2]); } // end geometry mainXML->LinkEndChild(geometryXML); TiXmlElement* verticesXML = new TiXmlElement(mitk::ConnectomicsNetworkDefinitions::XML_VERTICES); { // begin vertices section VertexVectorType vertexVector = this->GetInput()->GetVectorOfAllNodes(); for( unsigned int index = 0; index < vertexVector.size(); index++ ) { // not localized as of yet TODO TiXmlElement* vertexXML = new TiXmlElement(mitk::ConnectomicsNetworkDefinitions::XML_VERTEX ); vertexXML->SetAttribute( mitk::ConnectomicsNetworkDefinitions::XML_VERTEX_ID , vertexVector[ index ].id ); vertexXML->SetAttribute( mitk::ConnectomicsNetworkDefinitions::XML_VERTEX_LABEL , vertexVector[ index ].label ); vertexXML->SetDoubleAttribute( mitk::ConnectomicsNetworkDefinitions::XML_VERTEX_X , vertexVector[ index ].coordinates[0] ); vertexXML->SetDoubleAttribute( mitk::ConnectomicsNetworkDefinitions::XML_VERTEX_Y , vertexVector[ index ].coordinates[1] ); vertexXML->SetDoubleAttribute( mitk::ConnectomicsNetworkDefinitions::XML_VERTEX_Z , vertexVector[ index ].coordinates[2] ); verticesXML->LinkEndChild(vertexXML); } } // end vertices section mainXML->LinkEndChild(verticesXML); TiXmlElement* edgesXML = new TiXmlElement(mitk::ConnectomicsNetworkDefinitions::XML_EDGES); { // begin edges section EdgeVectorType edgeVector = this->GetInput()->GetVectorOfAllEdges(); for(unsigned int index = 0; index < edgeVector.size(); index++ ) { TiXmlElement* edgeXML = new TiXmlElement(mitk::ConnectomicsNetworkDefinitions::XML_EDGE ); edgeXML->SetAttribute( mitk::ConnectomicsNetworkDefinitions::XML_EDGE_ID , index ); edgeXML->SetAttribute( mitk::ConnectomicsNetworkDefinitions::XML_EDGE_SOURCE_ID , edgeVector[ index ].second.sourceId ); edgeXML->SetAttribute( mitk::ConnectomicsNetworkDefinitions::XML_EDGE_TARGET_ID , edgeVector[ index ].second.targetId ); edgeXML->SetAttribute( mitk::ConnectomicsNetworkDefinitions::XML_EDGE_WEIGHT_ID , edgeVector[ index ].second.weight ); edgesXML->LinkEndChild(edgeXML); } } // end edges section mainXML->LinkEndChild(edgesXML); } // end document documentXML.SaveFile( m_FileName ); m_Success = true; MITK_INFO << "Connectomics network written"; } } void mitk::ConnectomicsNetworkWriter::SetInputConnectomicsNetwork( InputType* conNetwork ) { this->ProcessObject::SetNthInput( 0, conNetwork ); } mitk::ConnectomicsNetwork* mitk::ConnectomicsNetworkWriter::GetInput() { if ( this->GetNumberOfInputs() < 1 ) { return NULL; } else { return dynamic_cast ( this->ProcessObject::GetInput( 0 ) ); } } std::vector mitk::ConnectomicsNetworkWriter::GetPossibleFileExtensions() { std::vector possibleFileExtensions; possibleFileExtensions.push_back(".cnf"); return possibleFileExtensions; } + +std::string mitk::ConnectomicsNetworkWriter::GetSupportedBaseData() const +{ + return InputType::GetStaticNameOfClass(); +} diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkConnectomicsNetworkWriter.h b/Modules/DiffusionImaging/DiffusionIO/mitkConnectomicsNetworkWriter.h index 344f0890b8..2116f19aff 100644 --- a/Modules/DiffusionImaging/DiffusionIO/mitkConnectomicsNetworkWriter.h +++ b/Modules/DiffusionImaging/DiffusionIO/mitkConnectomicsNetworkWriter.h @@ -1,157 +1,159 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef __mitkConnectomicsNetworkWriter_h #define __mitkConnectomicsNetworkWriter_h #include #include #include "mitkConnectomicsNetwork.h" #include namespace mitk { /** * Writes connectomics networks to a file * @ingroup Process */ class ConnectomicsNetworkWriter : public mitk::FileWriterWithInformation { public: mitkClassMacro( ConnectomicsNetworkWriter, mitk::FileWriterWithInformation ); //mitkWriterMacro; virtual void Write() { if ( this->GetInput() == NULL ) { itkExceptionMacro(<<"Write:Please specify an input!"); return; } /* Fill in image information.*/ this->UpdateOutputInformation(); (*(this->GetInputs().begin()))->SetRequestedRegionToLargestPossibleRegion(); this->PropagateRequestedRegion(NULL); this->UpdateOutputData(NULL); } virtual void Update() { Write(); } itkFactorylessNewMacro(Self) itkCloneMacro(Self) typedef mitk::ConnectomicsNetwork InputType; typedef std::vector< std::pair< std::pair< mitk::ConnectomicsNetwork::NetworkNode, mitk::ConnectomicsNetwork::NetworkNode > , mitk::ConnectomicsNetwork::NetworkEdge > > EdgeVectorType; typedef std::vector< mitk::ConnectomicsNetwork::NetworkNode > VertexVectorType; /** * Sets the filename of the file to write. * @param _arg the name of the file to write. */ itkSetStringMacro( FileName ); /** * @returns the name of the file to be written to disk. */ itkGetStringMacro( FileName ); /** * @warning multiple write not (yet) supported */ itkSetStringMacro( FilePrefix ); /** * @warning multiple write not (yet) supported */ itkGetStringMacro( FilePrefix ); /** * @warning multiple write not (yet) supported */ itkSetStringMacro( FilePattern ); /** * @warning multiple write not (yet) supported */ itkGetStringMacro( FilePattern ); /** * Sets the input object for the filter. * @param input the diffusion volumes to write to file. */ void SetInputConnectomicsNetwork( InputType* input ); /** * @returns the 0'th input object of the filter. */ InputType* GetInput(); /** * Returns false if an error happened during writing */ itkGetMacro( Success, bool ); /** * @return possible file extensions for the data type associated with the writer */ virtual std::vector GetPossibleFileExtensions(); + std::string GetSupportedBaseData() const; + // FileWriterWithInformation methods virtual const char * GetDefaultFilename() { return "ConnectomicsNetwork.cnf"; } virtual const char * GetFileDialogPattern() { return "ConnectomicsNetwork (*.cnf)"; } virtual const char * GetDefaultExtension() { return ".cnf"; } virtual bool CanWriteBaseDataType(BaseData::Pointer data) { return (dynamic_cast(data.GetPointer()) != NULL); } virtual void DoWrite(BaseData::Pointer data) { if (CanWriteBaseDataType(data)) { this->SetInputConnectomicsNetwork(dynamic_cast(data.GetPointer())); this->Update(); } } protected: ConnectomicsNetworkWriter(); virtual ~ConnectomicsNetworkWriter(); virtual void GenerateData(); std::string m_FileName; std::string m_FilePrefix; std::string m_FilePattern; bool m_Success; }; } // end of namespace mitk #endif //__mitkConnectomicsNetworkWriter_h diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdQBallImageWriter.cpp b/Modules/DiffusionImaging/DiffusionIO/mitkNrrdQBallImageWriter.cpp index fe832b8d97..ad11a48f02 100644 --- a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdQBallImageWriter.cpp +++ b/Modules/DiffusionImaging/DiffusionIO/mitkNrrdQBallImageWriter.cpp @@ -1,155 +1,160 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkNrrdQBallImageWriter.h" #include "itkMetaDataDictionary.h" #include "itkMetaDataObject.h" #include "itkNrrdImageIO.h" #include "itkImageFileWriter.h" #include "mitkImageCast.h" mitk::NrrdQBallImageWriter::NrrdQBallImageWriter() : m_FileName(""), m_FilePrefix(""), m_FilePattern(""), m_Success(false) { this->SetNumberOfRequiredInputs( 1 ); } mitk::NrrdQBallImageWriter::~NrrdQBallImageWriter() {} void mitk::NrrdQBallImageWriter::GenerateData() { m_Success = false; InputType* input = this->GetInput(); if (input == NULL) { itkWarningMacro(<<"Sorry, input to NrrdQBallImageWriter is NULL!"); return; } if ( m_FileName == "" ) { itkWarningMacro( << "Sorry, filename has not been set!" ); return ; } const std::string& locale = "C"; const std::string& currLocale = setlocale( LC_ALL, NULL ); if ( locale.compare(currLocale)!=0 ) { try { setlocale(LC_ALL, locale.c_str()); } catch(...) { MITK_INFO << "Could not set locale " << locale; } } itk::NrrdImageIO::Pointer io = itk::NrrdImageIO::New(); io->SetFileType( itk::ImageIOBase::Binary ); io->UseCompressionOn(); typedef itk::VectorImage VecImgType; typedef itk::Image,3> ImageType; typedef itk::ImageFileWriter WriterType; WriterType::Pointer nrrdWriter = WriterType::New(); ImageType::Pointer outimage = ImageType::New(); CastToItkImage(input, outimage); VecImgType::Pointer vecImg = VecImgType::New(); vecImg->SetSpacing( outimage->GetSpacing() ); // Set the image spacing vecImg->SetOrigin( outimage->GetOrigin() ); // Set the image origin vecImg->SetDirection( outimage->GetDirection() ); // Set the image direction vecImg->SetLargestPossibleRegion( outimage->GetLargestPossibleRegion()); vecImg->SetBufferedRegion( outimage->GetLargestPossibleRegion() ); vecImg->SetVectorLength(QBALL_ODFSIZE); vecImg->Allocate(); itk::ImageRegionIterator ot (vecImg, vecImg->GetLargestPossibleRegion() ); ot.GoToBegin(); itk::ImageRegionIterator it (outimage, outimage->GetLargestPossibleRegion() ); typedef ImageType::PixelType VecPixType; typedef VecImgType::PixelType VarVecType; for (it.GoToBegin(); !it.IsAtEnd(); ++it) { VecPixType vec = it.Get(); VarVecType varVec(vec.GetVnlVector().data_block(), QBALL_ODFSIZE); ot.Set(varVec); ++ot; } nrrdWriter->SetInput( vecImg ); nrrdWriter->SetImageIO(io); nrrdWriter->SetFileName(m_FileName); nrrdWriter->UseCompressionOn(); try { nrrdWriter->Update(); } catch (itk::ExceptionObject e) { std::cout << e << std::endl; } try { setlocale(LC_ALL, currLocale.c_str()); } catch(...) { MITK_INFO << "Could not reset locale " << currLocale; } m_Success = true; } void mitk::NrrdQBallImageWriter::SetInput( InputType* diffVolumes ) { this->ProcessObject::SetNthInput( 0, diffVolumes ); } mitk::QBallImage* mitk::NrrdQBallImageWriter::GetInput() { if ( this->GetNumberOfInputs() < 1 ) { return NULL; } else { return dynamic_cast ( this->ProcessObject::GetInput( 0 ) ); } } std::vector mitk::NrrdQBallImageWriter::GetPossibleFileExtensions() { std::vector possibleFileExtensions; possibleFileExtensions.push_back(".qbi"); possibleFileExtensions.push_back(".hqbi"); return possibleFileExtensions; } + +std::string mitk::NrrdQBallImageWriter::GetSupportedBaseData() const +{ + return InputType::GetStaticNameOfClass(); +} diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdQBallImageWriter.h b/Modules/DiffusionImaging/DiffusionIO/mitkNrrdQBallImageWriter.h index fa23388117..a801ab9953 100644 --- a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdQBallImageWriter.h +++ b/Modules/DiffusionImaging/DiffusionIO/mitkNrrdQBallImageWriter.h @@ -1,131 +1,133 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef _MITK_NRRDQBI_WRITER__H_ #define _MITK_NRRDQBI_WRITER__H_ #include #include #include namespace mitk { /** * Writes diffusion volumes to a file * @ingroup Process */ class NrrdQBallImageWriter : public mitk::FileWriterWithInformation { public: mitkClassMacro( NrrdQBallImageWriter, mitk::FileWriterWithInformation ); mitkWriterMacro; itkFactorylessNewMacro(Self) itkCloneMacro(Self) typedef mitk::QBallImage InputType; /** * Sets the filename of the file to write. * @param FileName the name of the file to write. */ itkSetStringMacro( FileName ); /** * @returns the name of the file to be written to disk. */ itkGetStringMacro( FileName ); /** * @warning multiple write not (yet) supported */ itkSetStringMacro( FilePrefix ); /** * @warning multiple write not (yet) supported */ itkGetStringMacro( FilePrefix ); /** * @warning multiple write not (yet) supported */ itkSetStringMacro( FilePattern ); /** * @warning multiple write not (yet) supported */ itkGetStringMacro( FilePattern ); /** * Sets the input object for the filter. * @param input the diffusion volumes to write to file. */ using itk::ProcessObject::SetInput; void SetInput( InputType* input ); /** * @returns the 0'th input object of the filter. */ InputType* GetInput(); /** * Returns false if an error happened during writing */ itkGetMacro( Success, bool ); /** * @return possible file extensions for the data type associated with the writer */ virtual std::vector GetPossibleFileExtensions(); + std::string GetSupportedBaseData() const; + // FileWriterWithInformation methods virtual const char * GetDefaultFilename() { return "QBalls.qbi"; } virtual const char * GetFileDialogPattern() { return "Q-Ball Images (*.qbi *.hqbi"; } virtual const char * GetDefaultExtension() { return ".qbi"; } virtual bool CanWriteBaseDataType(BaseData::Pointer data) { return (dynamic_cast(data.GetPointer()) != NULL); }; virtual void DoWrite(BaseData::Pointer data) { if (CanWriteBaseDataType(data)) { this->SetInput(dynamic_cast(data.GetPointer())); this->Update(); } }; protected: NrrdQBallImageWriter(); virtual ~NrrdQBallImageWriter(); virtual void GenerateData(); std::string m_FileName; std::string m_FilePrefix; std::string m_FilePattern; bool m_Success; }; } // end of namespace mitk #endif //_MITK_NRRDQBI_WRITER__H_ diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdTensorImageWriter.cpp b/Modules/DiffusionImaging/DiffusionIO/mitkNrrdTensorImageWriter.cpp index 84daf2311c..816af51a52 100644 --- a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdTensorImageWriter.cpp +++ b/Modules/DiffusionImaging/DiffusionIO/mitkNrrdTensorImageWriter.cpp @@ -1,127 +1,132 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkNrrdTensorImageWriter.h" #include "itkMetaDataDictionary.h" #include "itkMetaDataObject.h" #include "itkNrrdImageIO.h" #include "itkImageFileWriter.h" #include "itkDiffusionTensor3D.h" #include "mitkImageCast.h" mitk::NrrdTensorImageWriter::NrrdTensorImageWriter() : m_FileName(""), m_FilePrefix(""), m_FilePattern(""), m_Success(false) { this->SetNumberOfRequiredInputs( 1 ); } mitk::NrrdTensorImageWriter::~NrrdTensorImageWriter() {} void mitk::NrrdTensorImageWriter::GenerateData() { m_Success = false; InputType* input = this->GetInput(); if (input == NULL) { itkWarningMacro(<<"Sorry, input to NrrdTensorImageWriter is NULL!"); return; } if ( m_FileName == "" ) { itkWarningMacro( << "Sorry, filename has not been set!" ); return ; } const std::string& locale = "C"; const std::string& currLocale = setlocale( LC_ALL, NULL ); if ( locale.compare(currLocale)!=0 ) { try { setlocale(LC_ALL, locale.c_str()); } catch(...) { MITK_INFO << "Could not set locale " << locale; } } itk::NrrdImageIO::Pointer io = itk::NrrdImageIO::New(); io->SetFileType( itk::ImageIOBase::Binary ); io->UseCompressionOn(); typedef itk::Image,3> ImageType; typedef itk::ImageFileWriter WriterType; WriterType::Pointer nrrdWriter = WriterType::New(); ImageType::Pointer outimage = ImageType::New(); CastToItkImage(input, outimage); nrrdWriter->SetInput( outimage ); nrrdWriter->SetImageIO(io); nrrdWriter->SetFileName(m_FileName); nrrdWriter->UseCompressionOn(); try { nrrdWriter->Update(); } catch (itk::ExceptionObject e) { std::cout << e << std::endl; } try { setlocale(LC_ALL, currLocale.c_str()); } catch(...) { MITK_INFO << "Could not reset locale " << currLocale; } m_Success = true; } void mitk::NrrdTensorImageWriter::SetInput( InputType* diffVolumes ) { this->ProcessObject::SetNthInput( 0, diffVolumes ); } mitk::TensorImage* mitk::NrrdTensorImageWriter::GetInput() { if ( this->GetNumberOfInputs() < 1 ) { return NULL; } else { return dynamic_cast ( this->ProcessObject::GetInput( 0 ) ); } } std::vector mitk::NrrdTensorImageWriter::GetPossibleFileExtensions() { std::vector possibleFileExtensions; possibleFileExtensions.push_back(".dti"); possibleFileExtensions.push_back(".hdti"); return possibleFileExtensions; } + +std::string mitk::NrrdTensorImageWriter::GetSupportedBaseData() const +{ + return InputType::GetStaticNameOfClass(); +} diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdTensorImageWriter.h b/Modules/DiffusionImaging/DiffusionIO/mitkNrrdTensorImageWriter.h index aa1fa064bf..15af42a65f 100644 --- a/Modules/DiffusionImaging/DiffusionIO/mitkNrrdTensorImageWriter.h +++ b/Modules/DiffusionImaging/DiffusionIO/mitkNrrdTensorImageWriter.h @@ -1,131 +1,133 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef _MITK_NRRDDTI_WRITER__H_ #define _MITK_NRRDDTI_WRITER__H_ #include #include #include namespace mitk { /** * Writes diffusion volumes to a file * @ingroup Process */ class NrrdTensorImageWriter : public mitk::FileWriterWithInformation { public: mitkClassMacro( NrrdTensorImageWriter, mitk::FileWriterWithInformation ); mitkWriterMacro; itkFactorylessNewMacro(Self) itkCloneMacro(Self) typedef mitk::TensorImage InputType; /** * Sets the filename of the file to write. * @param FileName the name of the file to write. */ itkSetStringMacro( FileName ); /** * @returns the name of the file to be written to disk. */ itkGetStringMacro( FileName ); /** * @warning multiple write not (yet) supported */ itkSetStringMacro( FilePrefix ); /** * @warning multiple write not (yet) supported */ itkGetStringMacro( FilePrefix ); /** * @warning multiple write not (yet) supported */ itkSetStringMacro( FilePattern ); /** * @warning multiple write not (yet) supported */ itkGetStringMacro( FilePattern ); /** * Sets the input object for the filter. * @param input the diffusion volumes to write to file. */ using itk::ProcessObject::SetInput; void SetInput( InputType* input ); /** * @returns the 0'th input object of the filter. */ InputType* GetInput(); /** * Returns false if an error happened during writing */ itkGetMacro( Success, bool ); /** * @return possible file extensions for the data type associated with the writer */ virtual std::vector GetPossibleFileExtensions(); + std::string GetSupportedBaseData() const; + // FileWriterWithInformation methods virtual const char * GetDefaultFilename() { return "Tensors.dti"; } virtual const char * GetFileDialogPattern() { return "Tensor Images (*.dti *.hdti)"; } virtual const char * GetDefaultExtension() { return ".dti"; } virtual bool CanWriteBaseDataType(BaseData::Pointer data) { return (dynamic_cast(data.GetPointer()) != NULL); }; virtual void DoWrite(BaseData::Pointer data) { if (CanWriteBaseDataType(data)) { this->SetInput(dynamic_cast(data.GetPointer())); this->Update(); } }; protected: NrrdTensorImageWriter(); virtual ~NrrdTensorImageWriter(); virtual void GenerateData(); std::string m_FileName; std::string m_FilePrefix; std::string m_FilePattern; bool m_Success; }; } // end of namespace mitk #endif //_MITK_NRRDDTI_WRITER__H_ diff --git a/Modules/DiffusionImaging/FiberTracking/IODataStructures/FiberBundleX/mitkFiberBundleXWriter.cpp b/Modules/DiffusionImaging/FiberTracking/IODataStructures/FiberBundleX/mitkFiberBundleXWriter.cpp index c86fb17e9a..94a2815dae 100644 --- a/Modules/DiffusionImaging/FiberTracking/IODataStructures/FiberBundleX/mitkFiberBundleXWriter.cpp +++ b/Modules/DiffusionImaging/FiberTracking/IODataStructures/FiberBundleX/mitkFiberBundleXWriter.cpp @@ -1,135 +1,140 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkFiberBundleXWriter.h" #include #include #include #include #include mitk::FiberBundleXWriter::FiberBundleXWriter() : m_FileName(""), m_FilePrefix(""), m_FilePattern(""), m_Success(false) { this->SetNumberOfRequiredInputs( 1 ); } mitk::FiberBundleXWriter::~FiberBundleXWriter() {} void mitk::FiberBundleXWriter::GenerateData() { try { const std::string& locale = "C"; const std::string& currLocale = setlocale( LC_ALL, NULL ); setlocale(LC_ALL, locale.c_str()); m_Success = false; InputType* input = this->GetInput(); if (input == NULL) { itkWarningMacro(<<"Sorry, input to FiberBundleXWriter is NULL!"); return; } else if ( m_FileName == "" ) { itkWarningMacro( << "Sorry, filename has not been set!" ); return ; } std::string ext = itksys::SystemTools::GetFilenameLastExtension(m_FileName); if (ext==".fib" || ext==".vtk") { MITK_INFO << "Writing fiber bundle as binary VTK"; vtkSmartPointer writer = vtkSmartPointer::New(); writer->SetInputData(input->GetFiberPolyData()); writer->SetFileName(m_FileName.c_str()); writer->SetFileTypeToBinary(); writer->Write(); } else if (ext==".afib") { itksys::SystemTools::ReplaceString(m_FileName,".afib",".fib"); MITK_INFO << "Writing fiber bundle as ascii VTK"; vtkSmartPointer writer = vtkSmartPointer::New(); writer->SetInputData(input->GetFiberPolyData()); writer->SetFileName(m_FileName.c_str()); writer->SetFileTypeToASCII(); writer->Write(); } else if (ext==".avtk") { itksys::SystemTools::ReplaceString(m_FileName,".avtk",".vtk"); MITK_INFO << "Writing fiber bundle as ascii VTK"; vtkSmartPointer writer = vtkSmartPointer::New(); writer->SetInputData(input->GetFiberPolyData()); writer->SetFileName(m_FileName.c_str()); writer->SetFileTypeToASCII(); writer->Write(); } else if (ext==".trk") { MITK_INFO << "Writing fiber bundle as TRK"; TrackVis trk; trk.create(m_FileName, input); trk.writeHdr(); trk.append(input); } setlocale(LC_ALL, currLocale.c_str()); m_Success = true; MITK_INFO << "Fiber bundle written"; } catch(...) { throw; } } void mitk::FiberBundleXWriter::SetInputFiberBundleX( InputType* diffVolumes ) { this->ProcessObject::SetNthInput( 0, diffVolumes ); } mitk::FiberBundleX* mitk::FiberBundleXWriter::GetInput() { if ( this->GetNumberOfInputs() < 1 ) { return NULL; } else { return dynamic_cast ( this->ProcessObject::GetInput( 0 ) ); } } std::vector mitk::FiberBundleXWriter::GetPossibleFileExtensions() { std::vector possibleFileExtensions; possibleFileExtensions.push_back(".fib"); possibleFileExtensions.push_back(".afib"); possibleFileExtensions.push_back(".vtk"); possibleFileExtensions.push_back(".avtk"); possibleFileExtensions.push_back(".trk"); return possibleFileExtensions; } + +string mitk::FiberBundleXWriter::GetSupportedBaseData() const +{ + return FiberBundleX::GetStaticNameOfClass(); +} diff --git a/Modules/DiffusionImaging/FiberTracking/IODataStructures/FiberBundleX/mitkFiberBundleXWriter.h b/Modules/DiffusionImaging/FiberTracking/IODataStructures/FiberBundleX/mitkFiberBundleXWriter.h index b2ab087d6b..94f25579a2 100644 --- a/Modules/DiffusionImaging/FiberTracking/IODataStructures/FiberBundleX/mitkFiberBundleXWriter.h +++ b/Modules/DiffusionImaging/FiberTracking/IODataStructures/FiberBundleX/mitkFiberBundleXWriter.h @@ -1,217 +1,219 @@ /*=================================================================== 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 __mitkFiberBundleXWriter_h #define __mitkFiberBundleXWriter_h #include #include #include "mitkFiberBundleX.h" #include #include namespace mitk { /** * Writes fiber bundles to a file * @ingroup Process */ class MitkFiberTracking_EXPORT FiberBundleXWriter : public mitk::FileWriterWithInformation { public: mitkClassMacro( FiberBundleXWriter, mitk::FileWriterWithInformation ); itkFactorylessNewMacro(Self) itkCloneMacro(Self) //mitkWriterMacro; virtual void Write() { if ( this->GetInput() == NULL ) { itkExceptionMacro(<<"Write:Please specify an input!"); return; } /* Fill in image information.*/ this->UpdateOutputInformation(); (*(this->GetInputs().begin()))->SetRequestedRegionToLargestPossibleRegion(); this->PropagateRequestedRegion(NULL); this->UpdateOutputData(NULL); } virtual void Update() { Write(); } typedef mitk::FiberBundleX InputType; /** * Sets the filename of the file to write. * @param FileName the name of the file to write. */ itkSetStringMacro( FileName ); /** * @returns the name of the file to be written to disk. */ itkGetStringMacro( FileName ); /** * @warning multiple write not (yet) supported */ itkSetStringMacro( FilePrefix ); /** * @warning multiple write not (yet) supported */ itkGetStringMacro( FilePrefix ); /** * @warning multiple write not (yet) supported */ itkSetStringMacro( FilePattern ); /** * @warning multiple write not (yet) supported */ itkGetStringMacro( FilePattern ); /** * Sets the input object for the filter. * @param input the diffusion volumes to write to file. */ void SetInputFiberBundleX( InputType* input ); /** * @returns the 0'th input object of the filter. */ InputType* GetInput(); /** * Returns false if an error happened during writing */ itkGetMacro( Success, bool ); /** * @return possible file extensions for the data type associated with the writer */ virtual std::vector GetPossibleFileExtensions(); + std::string GetSupportedBaseData() const; + // FileWriterWithInformation methods virtual const char * GetDefaultFilename() { return "FiberBundle.fib"; } virtual const char * GetFileDialogPattern() { return "Fiber Bundle (*.fib *.vtk *.trk *.afib *.avtk)"; } virtual const char * GetDefaultExtension() { return ".fib"; } virtual bool CanWriteBaseDataType(BaseData::Pointer data) { return (dynamic_cast(data.GetPointer()) != NULL); }; virtual void DoWrite(BaseData::Pointer data) { if (CanWriteBaseDataType(data)) { this->SetInputFiberBundleX(dynamic_cast(data.GetPointer())); this->Update(); } }; static const char* XML_GEOMETRY; static const char* XML_MATRIX_XX; static const char* XML_MATRIX_XY; static const char* XML_MATRIX_XZ; static const char* XML_MATRIX_YX; static const char* XML_MATRIX_YY; static const char* XML_MATRIX_YZ; static const char* XML_MATRIX_ZX; static const char* XML_MATRIX_ZY; static const char* XML_MATRIX_ZZ; static const char* XML_ORIGIN_X; static const char* XML_ORIGIN_Y; static const char* XML_ORIGIN_Z; static const char* XML_SPACING_X; static const char* XML_SPACING_Y; static const char* XML_SPACING_Z; static const char* XML_SIZE_X; static const char* XML_SIZE_Y; static const char* XML_SIZE_Z; static const char* XML_FIBER_BUNDLE; static const char* XML_FIBER; static const char* XML_PARTICLE; static const char* XML_ID; static const char* XML_POS_X; static const char* XML_POS_Y; static const char* XML_POS_Z; static const char* VERSION_STRING; static const char* XML_FIBER_BUNDLE_FILE; static const char* XML_FILE_VERSION; static const char* XML_NUM_FIBERS; static const char* XML_NUM_PARTICLES; static const char* ASCII_FILE; static const char* FILE_NAME; protected: FiberBundleXWriter(); virtual ~FiberBundleXWriter(); virtual void GenerateData(); std::string m_FileName; std::string m_FilePrefix; std::string m_FilePattern; bool m_Success; }; } // end of namespace mitk #endif //__mitkFiberBundleXWriter_h diff --git a/Modules/DiffusionImaging/Quantification/IODataStructures/TbssImages/mitkNrrdTbssImageWriter.cpp b/Modules/DiffusionImaging/Quantification/IODataStructures/TbssImages/mitkNrrdTbssImageWriter.cpp index a790432044..278976cdba 100644 --- a/Modules/DiffusionImaging/Quantification/IODataStructures/TbssImages/mitkNrrdTbssImageWriter.cpp +++ b/Modules/DiffusionImaging/Quantification/IODataStructures/TbssImages/mitkNrrdTbssImageWriter.cpp @@ -1,160 +1,165 @@ /*=================================================================== 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 __mitkNrrdTbssImageWriter__cpp #define __mitkNrrdTbssImageWriter__cpp #include "mitkNrrdTbssImageWriter.h" #include "itkMetaDataDictionary.h" #include "itkMetaDataObject.h" #include "itkNrrdImageIO.h" //#include "itkNiftiImageIO.h" #include "itkImageFileWriter.h" #include "itksys/SystemTools.hxx" #include "boost/lexical_cast.hpp" #include #include mitk::NrrdTbssImageWriter::NrrdTbssImageWriter() : m_FileName(""), m_FilePrefix(""), m_FilePattern(""), m_Success(false) { this->SetNumberOfRequiredInputs( 1 ); } mitk::NrrdTbssImageWriter::~NrrdTbssImageWriter() {} void mitk::NrrdTbssImageWriter::GenerateData() { m_Success = false; InputType* input = this->GetInput(); if (input == NULL) { itkWarningMacro(<<"Sorry, input to NrrdTbssImageWriter is NULL!"); return; } if ( m_FileName == "" ) { itkWarningMacro( << "Sorry, filename has not been set!" ); return ; } itk::VectorImage::Pointer img = input->GetImage(); std::string key; std::string val; /* For the case of a tbss image containing data of the patients: Save info about the groups and the type of measurement */ std::vector< std::pair > groups = input->GetGroupInfo(); std::vector< std::pair >::iterator it = groups.begin(); int i=0; while(it != groups.end()) { std::pair p = *it; key = "Group_index_" + boost::lexical_cast(i); val = " " + p.first + " " + boost::lexical_cast(p.second); //sprintf( keybuffer, "Group_index_%04d", std::string(i) ); // sprintf( valbuffer, "%1d %1d", p.first, p.second); //std::cout << valbuffer << std::endl; //itk::EncapsulateMetaData< std::string >(input->GetImage()->GetMetaDataDictionary(),std::string(keybuffer),std::string(valbuffer)); itk::EncapsulateMetaData< std::string >(input->GetImage()->GetMetaDataDictionary(),key,val); it++; ++i; } key = "Measurement info"; val = input->GetMeasurementInfo(); itk::EncapsulateMetaData< std::string >(input->GetImage()->GetMetaDataDictionary(),key,val); typedef itk::VectorImage ImageType; itk::NrrdImageIO::Pointer io = itk::NrrdImageIO::New(); io->SetFileType( itk::ImageIOBase::Binary ); io->UseCompressionOn(); typedef itk::ImageFileWriter WriterType; WriterType::Pointer nrrdWriter = WriterType::New(); nrrdWriter->UseInputMetaDataDictionaryOn(); nrrdWriter->SetInput( img ); nrrdWriter->SetImageIO(io); nrrdWriter->SetFileName(m_FileName); nrrdWriter->UseCompressionOn(); nrrdWriter->SetImageIO(io); try { nrrdWriter->Update(); } catch (itk::ExceptionObject e) { std::cout << e << std::endl; } m_Success = true; } void mitk::NrrdTbssImageWriter::SetInput( InputType* tbssVol ) { this->ProcessObject::SetNthInput( 0, tbssVol ); } mitk::TbssImage* mitk::NrrdTbssImageWriter::GetInput() { if ( this->GetNumberOfInputs() < 1 ) { return NULL; } else { return dynamic_cast ( this->ProcessObject::GetInput( 0 ) ); } } std::vector mitk::NrrdTbssImageWriter::GetPossibleFileExtensions() { std::vector possibleFileExtensions; possibleFileExtensions.push_back(".tbss"); return possibleFileExtensions; } +std::string mitk::NrrdTbssImageWriter::GetSupportedBaseData() const +{ + return TbssImage::GetStaticNameOfClass(); +} + #endif //__mitkNrrdTbssImageWriter__cpp diff --git a/Modules/DiffusionImaging/Quantification/IODataStructures/TbssImages/mitkNrrdTbssImageWriter.h b/Modules/DiffusionImaging/Quantification/IODataStructures/TbssImages/mitkNrrdTbssImageWriter.h index 62b3139716..3f85bf0c30 100644 --- a/Modules/DiffusionImaging/Quantification/IODataStructures/TbssImages/mitkNrrdTbssImageWriter.h +++ b/Modules/DiffusionImaging/Quantification/IODataStructures/TbssImages/mitkNrrdTbssImageWriter.h @@ -1,141 +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_NRRDTBSSVOL_WRITER__H_ #define _MITK_NRRDTBSSVOL_WRITER__H_ #include #include #include #include "MitkQuantificationExports.h" namespace mitk { /** * Writes diffusion volumes to a file * @ingroup Process */ class MitkQuantification_EXPORT NrrdTbssImageWriter : public mitk::FileWriterWithInformation { public: mitkClassMacro( NrrdTbssImageWriter, mitk::FileWriterWithInformation ) mitkWriterMacro itkFactorylessNewMacro(Self) itkCloneMacro(Self) typedef mitk::TbssImage InputType; /** * Sets the filename of the file to write. * @param FileName the nameInputType 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 ) /**image * Sets the input object for the filter. * @param input the diffusion volumes to write to file. */ using ProcessObject::SetInput; void SetInput( InputType* input ); /**itk::VectorImage * @returns the 0'th input object of the filter. */ InputType* GetInput(); /** * Returns false if an error happened during writing */ itkGetMacro( Success, bool ) /** * @return possible file extensions for the data type associated with the writer */ virtual std::vector GetPossibleFileExtensions(); + std::string GetSupportedBaseData() const; + // FileWriterWithInformation methods virtual const char * GetDefaultFilename() { return "TbssImage.tbss"; } virtual const char * GetFileDialogPattern() { return "Tbss Images (*.tbss)"; } virtual const char * GetDefaultExtension() { return ".tbss"; } virtual bool CanWriteBaseDataType(BaseData::Pointer data) { return (dynamic_cast(data.GetPointer()) != NULL); } virtual void DoWrite(BaseData::Pointer data) { if (CanWriteBaseDataType(data)) { this->SetInput(dynamic_cast(data.GetPointer())); this->Update(); } } protected: NrrdTbssImageWriter(); virtual ~NrrdTbssImageWriter(); virtual void GenerateData(); std::string m_FileName; std::string m_FilePrefix; std::string m_FilePattern; bool m_Success; }; } // end of namespace mitk #endif diff --git a/Modules/DiffusionImaging/Quantification/IODataStructures/TbssImages/mitkNrrdTbssRoiImageWriter.cpp b/Modules/DiffusionImaging/Quantification/IODataStructures/TbssImages/mitkNrrdTbssRoiImageWriter.cpp index 7373f98e3c..97e33372fe 100644 --- a/Modules/DiffusionImaging/Quantification/IODataStructures/TbssImages/mitkNrrdTbssRoiImageWriter.cpp +++ b/Modules/DiffusionImaging/Quantification/IODataStructures/TbssImages/mitkNrrdTbssRoiImageWriter.cpp @@ -1,142 +1,147 @@ /*=================================================================== 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 __mitkNrrdTbssRoiImageWriter__cpp #define __mitkNrrdTbssRoiImageWriter__cpp #include "mitkNrrdTbssRoiImageWriter.h" #include "itkMetaDataDictionary.h" #include "itkMetaDataObject.h" #include "itkNrrdImageIO.h" //#include "itkNiftiImageIO.h" #include "itkImageFileWriter.h" #include "itksys/SystemTools.hxx" #include #include mitk::NrrdTbssRoiImageWriter::NrrdTbssRoiImageWriter() : m_FileName(""), m_FilePrefix(""), m_FilePattern(""), m_Success(false) { this->SetNumberOfRequiredInputs( 1 ); } mitk::NrrdTbssRoiImageWriter::~NrrdTbssRoiImageWriter() {} void mitk::NrrdTbssRoiImageWriter::GenerateData() { m_Success = false; InputType* input = this->GetInput(); if (input == NULL) { itkWarningMacro(<<"Sorry, input to NrrdTbssImageWriter is NULL!") return; } if ( m_FileName == "" ) { itkWarningMacro( << "Sorry, filename has not been set!" ) return ; } char keybuffer[512]; char valbuffer[512]; std::vector< itk::Index<3> > roi = input->GetRoi(); std::vector< itk::Index<3> >::iterator it = roi.begin(); int i=0; while(it != roi.end()) { itk::Index<3> ix = *it; sprintf( keybuffer, "ROI_index_%04d", i ); sprintf( valbuffer, "%ld %ld %ld", ix[0],ix[1],ix[2]); std::cout << valbuffer << std::endl; //input->GetImage()->GetMetaDataDictionary(); itk::EncapsulateMetaData< std::string >(input->GetImage()->GetMetaDataDictionary(), std::string(keybuffer), std::string(valbuffer)); it++; ++i; } std::string structure = input->GetStructure(); itk::EncapsulateMetaData< std::string >(input->GetImage()->GetMetaDataDictionary(), "structure", structure); typedef itk::Image ImageType; ImageType::Pointer img = input->GetImage(); itk::NrrdImageIO::Pointer io = itk::NrrdImageIO::New(); io->SetFileType( itk::ImageIOBase::Binary ); io->UseCompressionOn(); typedef itk::ImageFileWriter WriterType; WriterType::Pointer nrrdWriter = WriterType::New(); nrrdWriter->UseInputMetaDataDictionaryOn(); nrrdWriter->SetInput( img ); nrrdWriter->SetImageIO(io); nrrdWriter->SetFileName(m_FileName); // nrrdWriter->UseCompressionOn(); nrrdWriter->SetImageIO(io); try { nrrdWriter->Update(); } catch (itk::ExceptionObject e) { std::cout << e << std::endl; } m_Success = true; } void mitk::NrrdTbssRoiImageWriter::SetInput( InputType* tbssVol ) { this->ProcessObject::SetNthInput( 0, tbssVol ); } mitk::TbssRoiImage* mitk::NrrdTbssRoiImageWriter::GetInput() { if ( this->GetNumberOfInputs() < 1 ) { return NULL; } else { return dynamic_cast ( this->ProcessObject::GetInput( 0 ) ); } } std::vector mitk::NrrdTbssRoiImageWriter::GetPossibleFileExtensions() { std::vector possibleFileExtensions; possibleFileExtensions.push_back(".roi"); return possibleFileExtensions; } +std::string mitk::NrrdTbssRoiImageWriter::GetSupportedBaseData() const +{ + return TbssRoiImage::GetStaticNameOfClass(); +} + #endif //__mitkNrrdTbssRoiImageWriter__cpp diff --git a/Modules/DiffusionImaging/Quantification/IODataStructures/TbssImages/mitkNrrdTbssRoiImageWriter.h b/Modules/DiffusionImaging/Quantification/IODataStructures/TbssImages/mitkNrrdTbssRoiImageWriter.h index 8f8c12973c..965fe1603d 100644 --- a/Modules/DiffusionImaging/Quantification/IODataStructures/TbssImages/mitkNrrdTbssRoiImageWriter.h +++ b/Modules/DiffusionImaging/Quantification/IODataStructures/TbssImages/mitkNrrdTbssRoiImageWriter.h @@ -1,139 +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_NRRDTBSSROIVOL_WRITER__H_ #define _MITK_NRRDTBSSROIVOL_WRITER__H_ #include #include #include #include "MitkQuantificationExports.h" namespace mitk { /** * Writes diffusion volumes to a file * @ingroup Process */ class MitkQuantification_EXPORT NrrdTbssRoiImageWriter : public mitk::FileWriterWithInformation { public: typedef itk::Image ImageType; mitkClassMacro( NrrdTbssRoiImageWriter, mitk::FileWriterWithInformation ) mitkWriterMacro itkFactorylessNewMacro(Self) itkCloneMacro(Self) typedef mitk::TbssRoiImage InputType; /** * Sets the filename of the file to write. * @param FileName the nameInputType 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 ); /**image * Sets the input object for the filter. * @param input the diffusion volumes to write to file. */ using ProcessObject::SetInput; void SetInput( InputType* input ); /** * @returns the 0'th input object of the filter. */ InputType* GetInput(); /** * Returns false if an error happened during writing */ itkGetMacro( Success, bool ); /** * @return possible file extensions for the data type associated with the writer */ virtual std::vector GetPossibleFileExtensions(); + std::string GetSupportedBaseData() const; + // FileWriterWithInformation methods virtual const char * GetDefaultFilename() { return "TbssRoiImage.roi"; } virtual const char * GetFileDialogPattern() { return "Tbss Roi Images (*.roi)"; } virtual const char * GetDefaultExtension() { return ".roi"; } virtual bool CanWriteBaseDataType(BaseData::Pointer data) { return (dynamic_cast(data.GetPointer()) != NULL); } virtual void DoWrite(BaseData::Pointer data) { if (CanWriteBaseDataType(data)) { this->SetInput(dynamic_cast(data.GetPointer())); this->Update(); } } protected: NrrdTbssRoiImageWriter(); virtual ~NrrdTbssRoiImageWriter(); virtual void GenerateData(); std::string m_FileName; std::string m_FilePrefix; std::string m_FilePattern; bool m_Success; }; } // end of namespace mitk #endif diff --git a/Modules/IpPicSupport/mitkPicFileWriter.cpp b/Modules/IpPicSupport/mitkPicFileWriter.cpp index 79969fb638..7eabc40734 100644 --- a/Modules/IpPicSupport/mitkPicFileWriter.cpp +++ b/Modules/IpPicSupport/mitkPicFileWriter.cpp @@ -1,306 +1,311 @@ /*=================================================================== 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 "mitkPicFileWriter.h" #include "mitkPicFileReader.h" extern "C" { size_t _mitkIpPicFWrite( const void *ptr, size_t size, size_t nitems, mitkIpPicFile_t stream); } mitk::PicFileWriter::PicFileWriter() { this->SetNumberOfRequiredInputs( 1 ); } mitk::PicFileWriter::~PicFileWriter() { } void mitk::PicFileWriter::GenerateData() { if ( m_FileName == "" ) { itkWarningMacro( << "Sorry, filename has not been set!" ); return ; } std::ofstream testfilehandle( m_FileName.c_str(), std::ios::out); if (!testfilehandle.good()) { testfilehandle.close(); itkExceptionMacro(<<"File location '" << m_FileName << "' not writeable"); } else { testfilehandle.close(); } Image::Pointer input = const_cast(this->GetInput()); if ( input.IsNull() ) { itkExceptionMacro(<< "Nothing to write: Input is NULL." ); } if( input->GetNumberOfChannels() > 1) { std::cout << "Multiple channel. Cannot write. Will throw..."; itkExceptionMacro(<< "The PicFileWriter does not support multiple channel data. Nothing will be written." ); } mitkIpPicDescriptor * picImage = mitkIpPicNew(); mitk::ImageWriteAccessor imageAccess(input); picImage = CastToIpPicDescriptor(input, &imageAccess, picImage); SlicedGeometry3D* slicedGeometry = input->GetSlicedGeometry(); if (slicedGeometry != NULL) { //set tag "REAL PIXEL SIZE" const Vector3D & spacing = slicedGeometry->GetSpacing(); mitkIpPicTSV_t *pixelSizeTag; pixelSizeTag = mitkIpPicQueryTag( picImage, "REAL PIXEL SIZE" ); if (!pixelSizeTag) { pixelSizeTag = (mitkIpPicTSV_t *) malloc( sizeof(mitkIpPicTSV_t) ); pixelSizeTag->type = mitkIpPicFloat; pixelSizeTag->bpe = 32; strcpy(pixelSizeTag->tag, "REAL PIXEL SIZE"); pixelSizeTag->dim = 1; pixelSizeTag->n[0] = 3; pixelSizeTag->value = malloc( sizeof(float) * 3 ); mitkIpPicAddTag (picImage, pixelSizeTag); } ((float*)pixelSizeTag->value)[0] = spacing[0]; ((float*)pixelSizeTag->value)[1] = spacing[1]; ((float*)pixelSizeTag->value)[2] = spacing[2]; //set tag "ISG" //ISG == offset/origin transformation matrix(matrix) spancings //ISG == offset0 offset1 offset2 spalte0_0 spalte0_1 spalte0_2 spalte1_0 spalte1_1 spalte1_2 spalte2_0 spalte2_1 spalte2_2 spacing0 spacing1 spacing2 mitkIpPicTSV_t *geometryTag; geometryTag = mitkIpPicQueryTag( picImage, "ISG" ); if (!geometryTag) { geometryTag = (mitkIpPicTSV_t *) malloc( sizeof(mitkIpPicTSV_t) ); geometryTag->type = mitkIpPicFloat; geometryTag->bpe = 32; strcpy(geometryTag->tag, "ISG"); geometryTag->dim = 2; geometryTag->n[0] = 3; geometryTag->n[1] = 4; geometryTag->value = malloc( sizeof(float) * 3 * 4 ); mitkIpPicAddTag (picImage, geometryTag); } const AffineTransform3D::OffsetType& offset = slicedGeometry->GetIndexToWorldTransform()->GetOffset(); ((float*)geometryTag->value)[0] = offset[0]; ((float*)geometryTag->value)[1] = offset[1]; ((float*)geometryTag->value)[2] = offset[2]; const AffineTransform3D::MatrixType& matrix = slicedGeometry->GetIndexToWorldTransform()->GetMatrix(); const AffineTransform3D::MatrixType::ValueType* row0 = matrix[0]; const AffineTransform3D::MatrixType::ValueType* row1 = matrix[1]; const AffineTransform3D::MatrixType::ValueType* row2 = matrix[2]; Vector3D v; FillVector3D(v, row0[0], row1[0], row2[0]); v.Normalize(); ((float*)geometryTag->value)[3] = v[0]; ((float*)geometryTag->value)[4] = v[1]; ((float*)geometryTag->value)[5] = v[2]; FillVector3D(v, row0[1], row1[1], row2[1]); v.Normalize(); ((float*)geometryTag->value)[6] = v[0]; ((float*)geometryTag->value)[7] = v[1]; ((float*)geometryTag->value)[8] = v[2]; ((float*)geometryTag->value)[9] = spacing[0]; ((float*)geometryTag->value)[10] = spacing[1]; ((float*)geometryTag->value)[11] = spacing[2]; } PicFileReader::ConvertHandedness(picImage); // flip upside-down in MITK coordinates // Following line added to detect write errors. If saving .pic files from the plugin is broken again, // please report a bug, don't just remove this line! int ret = MITKIpPicPut((char*)(m_FileName.c_str()), picImage); if (ret != 0) { PicFileReader::ConvertHandedness(picImage); // flip back from upside-down state throw std::ios_base::failure("Error during .pic file writing in "__FILE__); } PicFileReader::ConvertHandedness(picImage); // flip back from upside-down state } void mitk::PicFileWriter::SetInputImage( Image* image ) { this->ProcessObject::SetNthInput( 0, image ); } const mitk::Image* mitk::PicFileWriter::GetInput() { if ( this->GetNumberOfInputs() < 1 ) { MITK_ERROR << "No input image present."; return NULL; } else { return static_cast< const Image * >( this->ProcessObject::GetInput( 0 ) ); } } int mitk::PicFileWriter::MITKIpPicPut( char *outfile_name, mitkIpPicDescriptor *pic ) { FILE* outfile; mitkIpUInt4_t len; mitkIpUInt4_t tags_len; if( pic->info->write_protect ) { fprintf( stderr, "mitkIpPicPut: sorry, can't write (missing tags !!!)\n" ); //return( -1 ); } if( mitkIpPicEncryptionType(pic) != ' ' ) { fprintf( stderr, "mitkIpPicPut: warning: was encrypted !!!\n" ); } if( outfile_name == NULL ) outfile = stdout; else if( strcmp(outfile_name, "stdout") == 0 ) outfile = stdout; else { mitkIpPicRemoveFile( outfile_name ); // Removed due to linker problems when compiling // an mitk chili plugin using msvc: there appear // unresolved external symbol errors to function // _ipPicGetWriteCompression() /* if( mitkIpPicGetWriteCompression() ) { char buff[1024]; sprintf( buff, "%s.gz", outfile_name ); outfile = (FILE*) mitkIpPicFOpen( buff, "wb" ); // cast to prevent warning. } else */ outfile = fopen( outfile_name, "wb" ); } if( outfile == NULL ) { fprintf( stderr, "mitkIpPicPut: sorry, error opening outfile\n" ); return( -1 ); } tags_len = _mitkIpPicTagsSize( pic->info->tags_head ); len = tags_len + 3 * sizeof(mitkIpUInt4_t) + pic->dim * sizeof(mitkIpUInt4_t); /* write oufile */ if( mitkIpPicEncryptionType(pic) == ' ' ) mitkIpPicFWrite( mitkIpPicVERSION, 1, sizeof(mitkIpPicTag_t), outfile ); else mitkIpPicFWrite( pic->info->version, 1, sizeof(mitkIpPicTag_t), outfile ); mitkIpPicFWriteLE( &len, sizeof(mitkIpUInt4_t), 1, outfile ); mitkIpPicFWriteLE( &(pic->type), sizeof(mitkIpUInt4_t), 1, outfile ); mitkIpPicFWriteLE( &(pic->bpe), sizeof(mitkIpUInt4_t), 1, outfile ); mitkIpPicFWriteLE( &(pic->dim), sizeof(mitkIpUInt4_t), 1, outfile ); mitkIpPicFWriteLE( pic->n, sizeof(mitkIpUInt4_t), pic->dim, outfile ); _mitkIpPicWriteTags( pic->info->tags_head, outfile, mitkIpPicEncryptionType(pic) ); // Removed due to linker problems when compiling // an mitk chili plugin using msvc: there appear // unresolved external symbol errors to function // _ipPicGetWriteCompression() /* if( mitkIpPicGetWriteCompression() ) pic->info->pixel_start_in_file = mitkIpPicFTell( outfile ); else */ pic->info->pixel_start_in_file = ftell( outfile ); if( pic->data ) { size_t number_of_elements = _mitkIpPicElements(pic); size_t bytes_per_element = pic->bpe / 8; size_t number_of_bytes = number_of_elements * bytes_per_element; size_t block_size = 1024*1024; /* Use 1 MB blocks. Make sure that block size is smaller than 2^31 */ size_t number_of_blocks = number_of_bytes / block_size; size_t remaining_bytes = number_of_bytes % block_size; size_t bytes_written = 0; size_t block_nr = 0; mitkIpUInt1_t* data = (mitkIpUInt1_t*) pic->data; assert( data != NULL ); if( pic->type == mitkIpPicNonUniform ) { for ( block_nr = 0 ; block_nr < number_of_blocks ; ++block_nr ) bytes_written += mitkIpPicFWrite( data + ( block_nr * block_size ), 1, block_size, outfile ); bytes_written += mitkIpPicFWrite( data + ( number_of_blocks * block_size ), 1, remaining_bytes, outfile ); } else { for ( block_nr = 0 ; block_nr < number_of_blocks ; ++block_nr ) bytes_written += mitkIpPicFWriteLE( data + ( block_nr * block_size ), 1, block_size, outfile ); bytes_written += mitkIpPicFWriteLE( data + ( number_of_blocks * block_size ), 1, remaining_bytes, outfile ); } if ( bytes_written != number_of_bytes ) { fprintf( stderr, "Error while writing (ferror indicates %u), only %u bytes were written! Eof indicator is %u.\n", ferror(outfile), ( (unsigned int) ( bytes_written ) ), feof(outfile) ); fclose( outfile ); return( -1 ); } } if( outfile != stdout ) { // Removed due to linker problems when compiling // an mitk chili plugin using msvc: there appear // unresolved external symbol errors to function // _ipPicGetWriteCompression() /* if( mitkIpPicGetWriteCompression() ) mitkIpPicFClose( outfile ); else */ fclose( outfile ); } return( 0 ); } std::vector mitk::PicFileWriter::GetPossibleFileExtensions() { std::vector possibleFileExtensions; possibleFileExtensions.push_back(".pic"); return possibleFileExtensions; } + +std::string mitk::PicFileWriter::GetSupportedBaseData() const +{ + return Image::GetStaticNameOfClass(); +} diff --git a/Modules/IpPicSupport/mitkPicFileWriter.h b/Modules/IpPicSupport/mitkPicFileWriter.h index 794c787b0d..3b4f4252ff 100644 --- a/Modules/IpPicSupport/mitkPicFileWriter.h +++ b/Modules/IpPicSupport/mitkPicFileWriter.h @@ -1,120 +1,122 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef _MITK_PIC_FILE_WRITER__H_ #define _MITK_PIC_FILE_WRITER__H_ #include #include #include #include "mitkLegacyAdaptors.h" namespace mitk { class Image; /** * @brief Writer for mitk::Image * @ingroup IO */ class MitkIpPicSupport_EXPORT PicFileWriter : public mitk::FileWriter { public: mitkClassMacro( PicFileWriter, mitk::FileWriter ); 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 ); /** * Sets the 0'th input object for the filter. * @param input the first input for the filter. */ void SetInputImage( mitk::Image* input ); /** * @returns the 0'th input object of the filter. */ const mitk::Image* GetInput(); /** * @return possible file extensions for the data type associated with the writer */ virtual std::vector GetPossibleFileExtensions(); + std::string GetSupportedBaseData() const; + protected: /** * Constructor. */ PicFileWriter(); /** * Virtual destructor. */ virtual ~PicFileWriter(); virtual void GenerateData(); virtual int MITKIpPicPut( char *outfile_name, mitkIpPicDescriptor *pic ); std::string m_FileName; std::string m_FilePrefix; std::string m_FilePattern; }; } #endif //_MITK_PIC_FILE_WRITER__H_ diff --git a/Modules/OpenCVVideoSupport/Testing/mitkOpenCVMitkConversionTest.cpp b/Modules/OpenCVVideoSupport/Testing/mitkOpenCVMitkConversionTest.cpp index cb065e2bdf..4d35449673 100644 --- a/Modules/OpenCVVideoSupport/Testing/mitkOpenCVMitkConversionTest.cpp +++ b/Modules/OpenCVVideoSupport/Testing/mitkOpenCVMitkConversionTest.cpp @@ -1,301 +1,297 @@ /*=================================================================== 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 includes #include "mitkImageToOpenCVImageFilter.h" #include "mitkOpenCVToMitkImageFilter.h" #include #include #include #include -#include "mitkItkImageFileReader.h" #include "mitkImageReadAccessor.h" #include "mitkImageSliceSelector.h" // itk includes #include #include #include // define test pixel indexes and intensities and other values typedef itk::RGBPixel< unsigned char > TestUCRGBPixelType; cv::Size testImageSize; cv::Point pos1; cv::Point pos2; cv::Point pos3; cv::Vec3b color1; cv::Vec3b color2; cv::Vec3b color3; uchar greyValue1; uchar greyValue2; uchar greyValue3; /*! Documentation * Test for image conversion of OpenCV images and mitk::Images. It tests the classes * OpenCVToMitkImageFilter and ImageToOpenCVImageFilter */ // Some declarations template void ComparePixels( itk::Image,VImageDimension>* image ); void ReadImageDataAndConvertForthAndBack(std::string imageFileName); void ConvertIplImageForthAndBack(mitk::Image::Pointer inputForCVMat, std::string imageFileName); void ConvertCVMatForthAndBack(mitk::Image::Pointer inputForCVMat, std::string imageFileName); // Begin the test for mitkImage to OpenCV image conversion and back. int mitkOpenCVMitkConversionTest(int argc, char* argv[]) { MITK_TEST_BEGIN("ImageToOpenCVImageFilter") // the first part of this test checks the conversion of a cv::Mat style OpenCV image. // we build an cv::Mat image MITK_INFO << "setting test values"; testImageSize = cv::Size(11,11); pos1 = cv::Point(0,0); pos2 = cv::Point(5,5); pos3 = cv::Point(10,10); color1 = cv::Vec3b(50,0,0); color2 = cv::Vec3b(0,128,0); color3 = cv::Vec3b(0,0,255); greyValue1 = 0; greyValue2 = 128; greyValue3 = 255; MITK_INFO << "generating test OpenCV image (RGB)"; cv::Mat testRGBImage = cv::Mat::zeros( testImageSize, CV_8UC3 ); // generate some test intensity values testRGBImage.at(pos1)= color1; testRGBImage.at(pos2)= color2; testRGBImage.at(pos3)= color3; //cv::namedWindow("debug", CV_WINDOW_FREERATIO ); //cv::imshow("debug", testRGBImage.clone()); //cv::waitKey(0); // convert it to a mitk::Image MITK_INFO << "converting OpenCV test image to mitk image and comparing scalar rgb values"; mitk::OpenCVToMitkImageFilter::Pointer openCvToMitkFilter = mitk::OpenCVToMitkImageFilter::New(); openCvToMitkFilter->SetOpenCVMat( testRGBImage ); openCvToMitkFilter->Update(); mitk::Image::Pointer mitkImage = openCvToMitkFilter->GetOutput(); AccessFixedTypeByItk(mitkImage.GetPointer(), ComparePixels, (itk::RGBPixel), // rgb image (2) ); // convert it back to OpenCV image MITK_INFO << "converting mitk image to OpenCV image and comparing scalar rgb values"; mitk::ImageToOpenCVImageFilter::Pointer mitkToOpenCv = mitk::ImageToOpenCVImageFilter::New(); mitkToOpenCv->SetImage( mitkImage ); cv::Mat openCvImage = mitkToOpenCv->GetOpenCVMat(); // and test equality of the sentinel pixel cv::Vec3b convertedColor1 = openCvImage.at(pos1); cv::Vec3b convertedColor2 = openCvImage.at(pos2); cv::Vec3b convertedColor3 = openCvImage.at(pos3); MITK_TEST_CONDITION( color1 == convertedColor1, "Testing if initially created color values " << static_cast( color1[0] ) << ", " << static_cast( color1[1] ) << ", " << static_cast( color1[2] ) << " matches the color values " << static_cast( convertedColor1[0] ) << ", " << static_cast( convertedColor1[1] ) << ", " << static_cast( convertedColor1[2] ) << " at the same position " << pos1.x << ", " << pos1.y << " in the back converted OpenCV image" ) MITK_TEST_CONDITION( color2 == convertedColor2, "Testing if initially created color values " << static_cast( color2[0] ) << ", " << static_cast( color2[1] ) << ", " << static_cast( color2[2] ) << " matches the color values " << static_cast( convertedColor2[0] ) << ", " << static_cast( convertedColor2[1] ) << ", " << static_cast( convertedColor2[2] ) << " at the same position " << pos2.x << ", " << pos2.y << " in the back converted OpenCV image" ) MITK_TEST_CONDITION( color3 == convertedColor3, "Testing if initially created color values " << static_cast( color3[0] ) << ", " << static_cast( color3[1] ) << ", " << static_cast( color3[2] ) << " matches the color values " << static_cast( convertedColor3[0] ) << ", " << static_cast( convertedColor3[1] ) << ", " << static_cast( convertedColor3[2] ) << " at the same position " << pos3.x << ", " << pos3.y << " in the back converted OpenCV image" ) // the second part of this test checks the conversion of mitk::Images to Ipl images and cv::Mat and back. for(unsigned int i = 1; i < argc; ++i ) { ReadImageDataAndConvertForthAndBack(argv[i]); } MITK_TEST_END(); } template void ComparePixels( itk::Image,VImageDimension>* image ) { typedef itk::RGBPixel PixelType; typedef itk::Image ImageType; typename ImageType::IndexType pixelIndex; pixelIndex[0] = pos1.x; pixelIndex[1] = pos1.y; PixelType onePixel = image->GetPixel( pixelIndex ); MITK_TEST_CONDITION( color1[0] == onePixel.GetBlue(), "Testing if blue value (= " << static_cast(color1[0]) << ") at postion " << pos1.x << ", " << pos1.y << " in OpenCV image is " << "equals the blue value (= " << static_cast(onePixel.GetBlue()) << ")" << " in the generated mitk image"); pixelIndex[0] = pos2.x; pixelIndex[1] = pos2.y; onePixel = image->GetPixel( pixelIndex ); MITK_TEST_CONDITION( color2[1] == onePixel.GetGreen(), "Testing if green value (= " << static_cast(color2[1]) << ") at postion " << pos2.x << ", " << pos2.y << " in OpenCV image is " << "equals the green value (= " << static_cast(onePixel.GetGreen()) << ")" << " in the generated mitk image"); pixelIndex[0] = pos3.x; pixelIndex[1] = pos3.y; onePixel = image->GetPixel( pixelIndex ); MITK_TEST_CONDITION( color3[2] == onePixel.GetRed(), "Testing if red value (= " << static_cast(color3[2]) << ") at postion " << pos3.x << ", " << pos3.y << " in OpenCV image is " << "equals the red value (= " << static_cast(onePixel.GetRed()) << ")" << " in the generated mitk image"); } void ReadImageDataAndConvertForthAndBack(std::string imageFileName) { // first we load an mitk::Image from the data repository - mitk::ItkImageFileReader::Pointer reader = mitk::ItkImageFileReader::New(); - reader->SetFileName(imageFileName); - reader->Update(); - mitk::Image::Pointer mitkTestImage = reader->GetOutput(); + mitk::Image::Pointer mitkTestImage = mitk::IOUtil::LoadImage(imageFileName); // some format checking mitk::Image::Pointer resultImg = NULL; if( mitkTestImage->GetDimension() <= 3 ) { if( mitkTestImage->GetDimension() > 2 && mitkTestImage->GetDimension(2) == 1 ) { mitk::ImageSliceSelector::Pointer sliceSelector = mitk::ImageSliceSelector::New(); sliceSelector->SetInput(mitkTestImage); sliceSelector->SetSliceNr(0); sliceSelector->Update(); resultImg = sliceSelector->GetOutput()->Clone(); } else if(mitkTestImage->GetDimension() < 3) { resultImg = mitkTestImage; } else { return; // 3D images are not supported, except with just one slice. } } else { return; // 4D images are not supported! } ConvertIplImageForthAndBack(resultImg, imageFileName); ConvertCVMatForthAndBack(resultImg, imageFileName); } void ConvertCVMatForthAndBack(mitk::Image::Pointer inputForCVMat, std::string imageFileName) { // now we convert it to OpenCV IplImage mitk::ImageToOpenCVImageFilter::Pointer toOCvConverter = mitk::ImageToOpenCVImageFilter::New(); toOCvConverter->SetImage(inputForCVMat); cv::Mat cvmatTestImage = toOCvConverter->GetOpenCVMat(); MITK_TEST_CONDITION_REQUIRED( !cvmatTestImage.empty(), "Conversion to cv::Mat successful!"); mitk::OpenCVToMitkImageFilter::Pointer toMitkConverter = mitk::OpenCVToMitkImageFilter::New(); toMitkConverter->SetOpenCVMat(cvmatTestImage); toMitkConverter->Update(); // initialize the image with the input image, since we want to test equality and OpenCV does not feature geometries and spacing mitk::Image::Pointer result = inputForCVMat->Clone(); mitk::ImageReadAccessor resultAcc(toMitkConverter->GetOutput(), toMitkConverter->GetOutput()->GetSliceData()); result->SetImportSlice(const_cast(resultAcc.GetData())); if( result->GetPixelType().GetNumberOfComponents() == 1 ) { MITK_TEST_EQUAL( result, inputForCVMat, "Testing equality of input and output image of cv::Mat conversion for " << imageFileName ); } else if( result->GetPixelType().GetNumberOfComponents() == 3 ) { MITK_TEST_EQUAL( result, inputForCVMat, "Testing equality of input and output image of cv::Mat conversion for " << imageFileName ); } else { MITK_WARN << "Unhandled number of components used to test equality, please enhance test!"; } // change OpenCV image to test if the filter gets updated cv::Mat changedcvmatTestImage = cvmatTestImage.clone(); std::size_t numBits = result->GetPixelType().GetBitsPerComponent(); if (result->GetPixelType().GetBitsPerComponent() == sizeof(char)*8) { changedcvmatTestImage.at(0,0) = cvmatTestImage.at(0,0) != 0 ? 0 : 1; } else if (result->GetPixelType().GetBitsPerComponent() == sizeof(float)*8) { changedcvmatTestImage.at(0,0) = cvmatTestImage.at(0,0) != 0 ? 0 : 1; } /* if (result->GetPixelType().GetBitsPerComponent() == 3*sizeof(char)) { changedcvmatTestImage.at(0,0) = cvmatTestImage.at(0,0) != 0 ? 0 : 1; } */ toMitkConverter->SetOpenCVMat(changedcvmatTestImage); toMitkConverter->Update(); MITK_TEST_NOT_EQUAL(toMitkConverter->GetOutput(), inputForCVMat, "Converted image must not be the same as before."); } void ConvertIplImageForthAndBack(mitk::Image::Pointer inputForIpl, std::string imageFileName) { // now we convert it to OpenCV IplImage mitk::ImageToOpenCVImageFilter::Pointer toOCvConverter = mitk::ImageToOpenCVImageFilter::New(); toOCvConverter->SetImage(inputForIpl); IplImage* iplTestImage = toOCvConverter->GetOpenCVImage(); MITK_TEST_CONDITION_REQUIRED( iplTestImage != NULL, "Conversion to OpenCv IplImage successful!"); mitk::OpenCVToMitkImageFilter::Pointer toMitkConverter = mitk::OpenCVToMitkImageFilter::New(); toMitkConverter->SetOpenCVImage(iplTestImage); toMitkConverter->Update(); // initialize the image with the input image, since we want to test equality and OpenCV does not feature geometries and spacing mitk::Image::Pointer result = inputForIpl->Clone(); mitk::ImageReadAccessor resultAcc(toMitkConverter->GetOutput(), toMitkConverter->GetOutput()->GetSliceData()); result->SetImportSlice(const_cast(resultAcc.GetData())); if( result->GetPixelType().GetNumberOfComponents() == 1 ) { MITK_TEST_EQUAL( result, inputForIpl, "Testing equality of input and output image of IplImage conversion for " << imageFileName ); } else if( result->GetPixelType().GetNumberOfComponents() == 3 ) { MITK_TEST_EQUAL( result, inputForIpl, "Testing equality of input and output image of cv::Mat conversion for " << imageFileName ); } else { MITK_WARN << "Unhandled number of components used to test equality, please enhance test!"; } } diff --git a/Modules/US/USFilters/mitkUSImageLoggingFilter.cpp b/Modules/US/USFilters/mitkUSImageLoggingFilter.cpp index 3cb7dfb9d3..13c039ca4a 100644 --- a/Modules/US/USFilters/mitkUSImageLoggingFilter.cpp +++ b/Modules/US/USFilters/mitkUSImageLoggingFilter.cpp @@ -1,154 +1,154 @@ /*=================================================================== 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 "mitkUSImageLoggingFilter.h" #include #include #include #include mitk::USImageLoggingFilter::USImageLoggingFilter() : m_SystemTimeClock(RealTimeClock::New()), m_ImageExtension(".nrrd") { } mitk::USImageLoggingFilter::~USImageLoggingFilter() { } void mitk::USImageLoggingFilter::GenerateData() { mitk::Image::ConstPointer inputImage = this->GetInput(); mitk::Image::Pointer outputImage = this->GetOutput(); if(inputImage.IsNull() || inputImage->IsEmpty()) { MITK_WARN << "Input image is not valid. Cannot save image!"; return; } //a clone is needed for a output and to store it. mitk::Image::Pointer inputClone = inputImage->Clone(); //simply redirecy the input to the output //this->SetNumberOfRequiredOutputs(1); //this->SetNthOutput(0, inputClone->Clone()); //outputImage->Graft(inputImage); //this->SetOutput(this->GetInput()); /*if (!this->GetOutput()->IsInitialized()) { this->SetNumberOfRequiredOutputs(1); mitk::Image::Pointer newOutput = mitk::Image::New(); this->SetNthOutput(0, newOutput); } memcpy(this->GetOutput(),this->GetInput());*/ //this->SetNthOutput(0,inputImage.); //this->AllocateOutputs(); //this->GraftOutput(inputClone); /* if (!this->GetOutput()->IsInitialized()) { mitk::Image::Pointer newOutput = mitk::Image::New(); this->SetNthOutput(0, newOutput); } this->GetOutput()Graft(this->GetInput()); */ m_LoggedImages.push_back(inputClone); m_LoggedMITKSystemTimes.push_back(m_SystemTimeClock->GetCurrentStamp()); } void mitk::USImageLoggingFilter::AddMessageToCurrentImage(std::string message) { m_LoggedMessages.insert(std::make_pair(static_cast(m_LoggedImages.size()-1),message)); } void mitk::USImageLoggingFilter::SaveImages(std::string path) { std::vector dummy1; std::string dummy2; this->SaveImages(path,dummy1,dummy2); } void mitk::USImageLoggingFilter::SaveImages(std::string path, std::vector& filenames, std::string& csvFileName) { filenames = std::vector(); //test if path is valid Poco::Path testPath(path); if(!testPath.isDirectory()) { mitkThrow() << "Attemting to write to directory " << path << " which is not valid! Aborting!"; } //generate a unique ID which is used as part of the filenames, so we avoid to overwrite old files by mistake. mitk::UIDGenerator myGen = mitk::UIDGenerator("",5); std::string uniqueID = myGen.GetUID(); //first: write the images for(size_t i=0; i::iterator it = m_LoggedMessages.find(i); if (m_LoggedMessages.empty() || (it == m_LoggedMessages.end())) os << filenames.at(i) << ";" << m_LoggedMITKSystemTimes.at(i) << ";" << "" << "\n"; else os << filenames.at(i) << ";" << m_LoggedMITKSystemTimes.at(i) << ";" << it->second << "\n"; } //close file fb.close(); } bool mitk::USImageLoggingFilter::SetImageFilesExtension(std::string extension) { mitk::ImageWriter::Pointer imageWriter = mitk::ImageWriter::New(); if(!imageWriter->IsExtensionValid(extension)) { MITK_WARN << "Extension " << extension << " is not supported; still using " << m_ImageExtension << " as before."; return false; } else { m_ImageExtension = extension; return true; } }