diff --git a/CMake/MITKDashboardSetup.cmake b/CMake/MITKDashboardSetup.cmake index 83df176cf5..fcb292f31c 100644 --- a/CMake/MITKDashboardSetup.cmake +++ b/CMake/MITKDashboardSetup.cmake @@ -1,156 +1,152 @@ # This file is intended to be included at the end of a custom MITKDashboardScript.TEMPLATE.cmake file list(APPEND CTEST_NOTES_FILES "${CTEST_SCRIPT_DIRECTORY}/${CTEST_SCRIPT_NAME}") # # Automatically determined properties # set(MY_OPERATING_SYSTEM "${CMAKE_HOST_SYSTEM}") # Windows 7, Linux-2.6.32, Darwin... site_name(CTEST_SITE) if(QT_BINARY_DIR) set(QT_QMAKE_EXECUTABLE "${QT_BINARY_DIR}/qmake") else() set(QT_QMAKE_EXECUTABLE "qmake") endif() execute_process(COMMAND ${QT_QMAKE_EXECUTABLE} --version OUTPUT_VARIABLE MY_QT_VERSION RESULT_VARIABLE qmake_error) if(qmake_error) message(FATAL_ERROR "Error when executing ${QT_QMAKE_EXECUTABLE} --version\n${qmake_error}") endif() string(REGEX REPLACE ".*Qt version ([0-9.]+) .*" "\\1" MY_QT_VERSION ${MY_QT_VERSION}) # # Project specific properties # if(NOT CTEST_BUILD_NAME) set(CTEST_BUILD_NAME "${MY_OPERATING_SYSTEM}-${MY_COMPILER}-Qt-${MY_QT_VERSION}-${CTEST_BUILD_CONFIGURATION}") endif() set(PROJECT_BUILD_DIR "MITK-build") set(CTEST_PATH "$ENV{PATH}") if(WIN32) set(ANN_BINARY_DIR "${CTEST_BINARY_DIRECTORY}/ANN-build/${CTEST_BUILD_CONFIGURATION}") set(GLEW_BINARY_DIR "${CTEST_BINARY_DIRECTORY}/GLEW-build/${CTEST_BUILD_CONFIGURATION}") set(TINYXML_BINARY_DIR "${CTEST_BINARY_DIRECTORY}/tinyxml-build/${CTEST_BUILD_CONFIGURATION}") set(QWT_BINARY_DIR "${CTEST_BINARY_DIRECTORY}/Qwt-build/${CTEST_BUILD_CONFIGURATION}") set(QXT_BINARY_DIR "${CTEST_BINARY_DIRECTORY}/Qxt-build/${CTEST_BUILD_CONFIGURATION}") set(VTK_BINARY_DIR "${CTEST_BINARY_DIRECTORY}/VTK-build/bin/${CTEST_BUILD_CONFIGURATION}") set(ACVD_BINARY_DIR "${CTEST_BINARY_DIRECTORY}/ACVD-build/bin/${CTEST_BUILD_CONFIGURATION}") set(ITK_BINARY_DIR "${CTEST_BINARY_DIRECTORY}/ITK-build/bin/${CTEST_BUILD_CONFIGURATION}") set(BOOST_BINARY_DIR "${CTEST_BINARY_DIRECTORY}/Boost-install/lib") set(GDCM_BINARY_DIR "${CTEST_BINARY_DIRECTORY}/GDCM-build/bin/${CTEST_BUILD_CONFIGURATION}") set(OPENCV_BINARY_DIR "${CTEST_BINARY_DIRECTORY}/OpenCV-build/bin/${CTEST_BUILD_CONFIGURATION}") set(SOFA_BINARY_DIR "${CTEST_BINARY_DIRECTORY}/SOFA-build/bin/${CTEST_BUILD_CONFIGURATION}") set(BLUEBERRY_OSGI_DIR "${CTEST_BINARY_DIRECTORY}/MITK-build/bin/BlueBerry/org.blueberry.osgi/bin/${CTEST_BUILD_CONFIGURATION}") set(CTEST_PATH "${CTEST_PATH};${QT_BINARY_DIR};${VTK_BINARY_DIR};${ANN_BINARY_DIR};${GLEW_BINARY_DIR};${TINYXML_BINARY_DIR};${QWT_BINARY_DIR};${QXT_BINARY_DIR};${ACVD_BINARY_DIR};${ITK_BINARY_DIR};${BOOST_BINARY_DIR};${GDCM_BINARY_DIR};${OPENCV_BINARY_DIR};${SOFA_BINARY_DIR};${BLUEBERRY_OSGI_DIR}") endif() set(ENV{PATH} "${CTEST_PATH}") set(SUPERBUILD_TARGETS "") # If the dashscript doesn't define a GIT_REPOSITORY variable, let's define it here. if(NOT DEFINED GIT_REPOSITORY OR GIT_REPOSITORY STREQUAL "") set(GIT_REPOSITORY "http://git.mitk.org/MITK.git") endif() # # Display build info # message("Site name: ${CTEST_SITE}") message("Build name: ${CTEST_BUILD_NAME}") message("Script Mode: ${SCRIPT_MODE}") message("Coverage: ${WITH_COVERAGE}, MemCheck: ${WITH_MEMCHECK}") # # Set initial cache options # if(CMAKE_GENERATOR MATCHES "[Mm]ake") set(CTEST_USE_LAUNCHERS 1) else() set(CTEST_USE_LAUNCHERS 0) endif() # Remove this if block after all dartclients work if(DEFINED ADDITIONNAL_CMAKECACHE_OPTION) message(WARNING "Rename ADDITIONNAL to ADDITIONAL in your dartlclient script: ${CTEST_SCRIPT_DIRECTORY}/${CTEST_SCRIPT_NAME}") set(ADDITIONAL_CMAKECACHE_OPTION ${ADDITIONNAL_CMAKECACHE_OPTION}) endif() if(NOT DEFINED MITK_USE_ACVD) set(MITK_USE_ACVD 1) endif() if(NOT DEFINED MITK_USE_Boost) set(MITK_USE_Boost 1) endif() if(NOT DEFINED MITK_USE_OpenCV) set(MITK_USE_OpenCV 1) endif() if(NOT DEFINED MITK_USE_SOFA) set(MITK_USE_SOFA 1) endif() if(NOT DEFINED MITK_BUILD_ALL_APPS) set(MITK_BUILD_ALL_APPS TRUE) endif() if(NOT DEFINED BLUEBERRY_BUILD_ALL_PLUGINS) set(BLUEBERRY_BUILD_ALL_PLUGINS TRUE) endif() if(NOT DEFINED MITK_BUILD_ALL_PLUGINS) set(MITK_BUILD_ALL_PLUGINS TRUE) endif() if(NOT DEFINED MITK_BUILD_EXAMPLES) set(MITK_BUILD_EXAMPLES TRUE) endif() -if(NOT BUILD_DiffusionCoreMiniApps) - set(BUILD_DiffusionCoreMiniApps TRUE) -endif() - -if(NOT BUILD_FiberTrackingMiniApps) - set(BUILD_FiberTrackingMiniApps TRUE) +if(NOT BUILD_DiffusionMiniApps) + set(BUILD_DiffusionMiniApps TRUE) endif() set(INITIAL_CMAKECACHE_OPTIONS " BLUEBERRY_BUILD_ALL_PLUGINS:BOOL=${MITK_BUILD_ALL_PLUGINS} MITK_BUILD_ALL_PLUGINS:BOOL=${MITK_BUILD_ALL_PLUGINS} MITK_BUILD_ALL_APPS:BOOL=${MITK_BUILD_ALL_APPS} MITK_BUILD_EXAMPLES:BOOL=${MITK_BUILD_EXAMPLES} SUPERBUILD_EXCLUDE_MITKBUILD_TARGET:BOOL=TRUE MITK_USE_ACVD:BOOL=${MITK_USE_ACVD} MITK_USE_Boost:BOOL=${MITK_USE_Boost} MITK_USE_OpenCV:BOOL=${MITK_USE_OpenCV} MITK_USE_SOFA:BOOL=${MITK_USE_SOFA} ${ADDITIONAL_CMAKECACHE_OPTION} ") # Write a cache file for populating the MITK initial cache (not the superbuild cache). # This can be used to provide variables which are not passed through the # superbuild process to the MITK configure step) if(MITK_INITIAL_CACHE) set(mitk_cache_file "${CTEST_SCRIPT_DIRECTORY}/mitk_initial_cache.txt") file(WRITE "${mitk_cache_file}" "${MITK_INITIAL_CACHE}") set(INITIAL_CMAKECACHE_OPTIONS "${INITIAL_CMAKECACHE_OPTIONS} MITK_INITIAL_CACHE_FILE:INTERNAL=${mitk_cache_file} ") endif() # # Download and include dashboard driver script # set(url "http://mitk.org/git/?p=MITK.git;a=blob_plain;f=CMake/MITKDashboardDriverScript.cmake;hb=${hb}") set(dest ${CTEST_SCRIPT_DIRECTORY}/${CTEST_SCRIPT_NAME}.driver) downloadFile("${url}" "${dest}") include(${dest}) diff --git a/Modules/DiffusionImaging/CMakeLists.txt b/Modules/DiffusionImaging/CMakeLists.txt index a9eabf6a88..f9e7c07873 100644 --- a/Modules/DiffusionImaging/CMakeLists.txt +++ b/Modules/DiffusionImaging/CMakeLists.txt @@ -1,12 +1,13 @@ set( diffusion_module_dirs DiffusionCore FiberTracking Connectomics Quantification ) foreach(diffusion_module_dir ${diffusion_module_dirs}) add_subdirectory(${diffusion_module_dir}) endforeach() +add_subdirectory(MiniApps) configure_file(${CMAKE_CURRENT_SOURCE_DIR}/mitkDiffusionImagingConfigure.h.in ${CMAKE_CURRENT_BINARY_DIR}/DiffusionCore/mitkDiffusionImagingConfigure.h) diff --git a/Modules/DiffusionImaging/DiffusionCore/CMakeLists.txt b/Modules/DiffusionImaging/DiffusionCore/CMakeLists.txt index ac3f53876c..d5b59858eb 100644 --- a/Modules/DiffusionImaging/DiffusionCore/CMakeLists.txt +++ b/Modules/DiffusionImaging/DiffusionCore/CMakeLists.txt @@ -1,18 +1,17 @@ find_package(ITK) if(ITK_GDCM_DIR) include(${ITK_GDCM_DIR}/GDCMConfig.cmake) if(GDCM_MAJOR_VERSION EQUAL 2) add_definitions(-DGDCM2) set(ITK_USES_GDCM2 1) endif(GDCM_MAJOR_VERSION EQUAL 2) endif(ITK_GDCM_DIR) MITK_CREATE_MODULE( DiffusionCore SUBPROJECTS MITK-DTI INCLUDE_DIRS Algorithms Algorithms/Reconstruction Algorithms/Registration DicomImport IODataStructures/DiffusionWeightedImages IODataStructures/QBallImages IODataStructures/TensorImages IODataStructures Rendering ${CMAKE_CURRENT_BINARY_DIR} DEPENDS MitkExt SceneSerializationBase # QmitkExt PACKAGE_DEPENDS Boost ) add_subdirectory(Testing) -add_subdirectory(MiniApps) diff --git a/Modules/DiffusionImaging/DiffusionCore/MiniApps/CMakeLists.txt b/Modules/DiffusionImaging/DiffusionCore/MiniApps/CMakeLists.txt deleted file mode 100755 index 569d92b2c5..0000000000 --- a/Modules/DiffusionImaging/DiffusionCore/MiniApps/CMakeLists.txt +++ /dev/null @@ -1,51 +0,0 @@ -OPTION(BUILD_DiffusionCoreMiniApps "Build commandline tools for diffusion core" OFF) - -IF(BUILD_DiffusionCoreMiniApps) - - # include necessary modules here MitkExt QmitkExt - MITK_CHECK_MODULE(_RESULT DiffusionCore ) - IF(_RESULT) - MESSAGE("Warning: DiffusionCoreMiniApps is missing ${_RESULT}") - ELSE(_RESULT) - MITK_USE_MODULE( DiffusionCore ) - - # needed include directories - INCLUDE_DIRECTORIES( - ${CMAKE_CURRENT_SOURCE_DIR} - ${CMAKE_CURRENT_BINARY_DIR} - ${ALL_INCLUDE_DIRECTORIES}) - - PROJECT( mitkDiffusionCoreMiniApps ) - - # fill in the standalone executables here - SET(DIFFUSIONCOREMINIAPPS - mitkDiffusionCoreMiniApps - ) - - # set additional files here - SET(DIFFUSIONCORE_ADDITIONAL_FILES - MiniAppManager.cpp - ImageFormatConverter.cpp - TensorReconstruction.cpp - QballReconstruction.cpp - DiffusionIndices.cpp - CopyGeometry.cpp - ) - - # create an executable foreach tool (only one at the moment) - FOREACH(tool ${DIFFUSIONCOREMINIAPPS}) - ADD_EXECUTABLE( - ${tool} - ${tool}.cpp - ${DIFFUSIONCORE_ADDITIONAL_FILES} - ) - - TARGET_LINK_LIBRARIES( - ${tool} - ${ALL_LIBRARIES} ) - ENDFOREACH(tool) - ENDIF() - - MITK_INSTALL_TARGETS(EXECUTABLES mitkDiffusionCoreMiniApps ) - -ENDIF(BUILD_DiffusionCoreMiniApps) diff --git a/Modules/DiffusionImaging/DiffusionCore/MiniApps/QballReconstruction.cpp b/Modules/DiffusionImaging/DiffusionCore/MiniApps/QballReconstruction.cpp deleted file mode 100644 index f011965583..0000000000 --- a/Modules/DiffusionImaging/DiffusionCore/MiniApps/QballReconstruction.cpp +++ /dev/null @@ -1,176 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "MiniAppManager.h" -#include -#include -#include -#include -#include - -#include -#include - -#include -#include - -#include - -#include "itkVectorContainer.h" -#include "vnl/vnl_vector_fixed.h" -#include "itkVectorImage.h" - -#include "mitkBaseDataIOFactory.h" -#include "mitkDiffusionImage.h" -#include "mitkBaseData.h" -#include "mitkDiffusionCoreObjectFactory.h" -#include "mitkCoreObjectFactory.h" -#include "mitkCoreExtObjectFactory.h" -#include "mitkImageWriter.h" -#include "itkAnalyticalDiffusionQballReconstructionImageFilter.h" -#include -#include - -using namespace mitk; -/** - * Convert files from one ending to the other - */ -int QballReconstruction(int argc, char* argv[]) -{ - - if ( argc<6 ) - { - std::cout << std::endl; - std::cout << "Perform QBall reconstruction on an dwi file" << std::endl; - std::cout << std::endl; - std::cout << "usage: " << argv[0] << " " << argv[1] << " " << std::endl; - std::cout << std::endl; - return EXIT_FAILURE; - } - - try - { - RegisterDiffusionCoreObjectFactory(); - - MITK_INFO << "Loading image ..."; - const std::string s1="", s2=""; - std::vector infile = BaseDataIO::LoadBaseDataFromFile( argv[2], s1, s2, false ); - DiffusionImage::Pointer dwi = dynamic_cast*>(infile.at(0).GetPointer()); - dwi->AverageRedundantGradients(0.001); - - mitk::QBallImage::Pointer image = mitk::QBallImage::New(); - - - int shOrder = 4; - if ( argc>6 ) - shOrder = boost::lexical_cast(argv[6]); - MITK_INFO << "Using SH order of " << shOrder; - switch ( shOrder ) - { - case 4: - { - typedef itk::AnalyticalDiffusionQballReconstructionImageFilter FilterType; - FilterType::Pointer filter = FilterType::New(); - filter->SetGradientImage( dwi->GetDirections(), dwi->GetVectorImage() ); - filter->SetBValue(dwi->GetB_Value()); - filter->SetThreshold( boost::lexical_cast(argv[4]) ); - filter->SetLambda(boost::lexical_cast(argv[3])); - filter->SetNormalizationMethod(FilterType::QBAR_SOLID_ANGLE); - filter->Update(); - image->InitializeByItk( filter->GetOutput() ); - image->SetVolume( filter->GetOutput()->GetBufferPointer() ); - break; - } - case 6: - { - typedef itk::AnalyticalDiffusionQballReconstructionImageFilter FilterType; - FilterType::Pointer filter = FilterType::New(); - filter->SetGradientImage( dwi->GetDirections(), dwi->GetVectorImage() ); - filter->SetBValue(dwi->GetB_Value()); - filter->SetThreshold( boost::lexical_cast(argv[4]) ); - filter->SetLambda(boost::lexical_cast(argv[3])); - filter->SetNormalizationMethod(FilterType::QBAR_SOLID_ANGLE); - filter->Update(); - image->InitializeByItk( filter->GetOutput() ); - image->SetVolume( filter->GetOutput()->GetBufferPointer() ); - break; - } - case 8: - { - typedef itk::AnalyticalDiffusionQballReconstructionImageFilter FilterType; - FilterType::Pointer filter = FilterType::New(); - filter->SetGradientImage( dwi->GetDirections(), dwi->GetVectorImage() ); - filter->SetBValue(dwi->GetB_Value()); - filter->SetThreshold( boost::lexical_cast(argv[4]) ); - filter->SetLambda(boost::lexical_cast(argv[3])); - filter->SetNormalizationMethod(FilterType::QBAR_SOLID_ANGLE); - filter->Update(); - image->InitializeByItk( filter->GetOutput() ); - image->SetVolume( filter->GetOutput()->GetBufferPointer() ); - break; - } - case 10: - { - typedef itk::AnalyticalDiffusionQballReconstructionImageFilter FilterType; - FilterType::Pointer filter = FilterType::New(); - filter->SetGradientImage( dwi->GetDirections(), dwi->GetVectorImage() ); - filter->SetBValue(dwi->GetB_Value()); - filter->SetThreshold( boost::lexical_cast(argv[4]) ); - filter->SetLambda(boost::lexical_cast(argv[3])); - filter->SetNormalizationMethod(FilterType::QBAR_SOLID_ANGLE); - filter->Update(); - image->InitializeByItk( filter->GetOutput() ); - image->SetVolume( filter->GetOutput()->GetBufferPointer() ); - break; - } - default: - { - MITK_INFO << "Supplied SH order not supported. Using default order of 4."; - typedef itk::AnalyticalDiffusionQballReconstructionImageFilter FilterType; - FilterType::Pointer filter = FilterType::New(); - filter->SetGradientImage( dwi->GetDirections(), dwi->GetVectorImage() ); - filter->SetBValue(dwi->GetB_Value()); - filter->SetThreshold( boost::lexical_cast(argv[4]) ); - filter->SetLambda(boost::lexical_cast(argv[3])); - filter->SetNormalizationMethod(FilterType::QBAR_SOLID_ANGLE); - filter->Update(); - image->InitializeByItk( filter->GetOutput() ); - image->SetVolume( filter->GetOutput()->GetBufferPointer() ); - } - } - - std::string outfilename = argv[5]; - MITK_INFO << "writing image " << outfilename; - mitk::NrrdQBallImageWriter::Pointer writer = mitk::NrrdQBallImageWriter::New(); - writer->SetInput(image.GetPointer()); - writer->SetFileName(outfilename.c_str()); - writer->Update(); - } - catch ( itk::ExceptionObject &err) - { - MITK_INFO << "Exception: " << err; - } - catch ( std::exception err) - { - MITK_INFO << "Exception: " << err.what(); - } - catch ( ... ) - { - MITK_INFO << "Exception!"; - } - return EXIT_SUCCESS; -} -RegisterDiffusionCoreMiniApp(QballReconstruction); diff --git a/Modules/DiffusionImaging/FiberTracking/CMakeLists.txt b/Modules/DiffusionImaging/FiberTracking/CMakeLists.txt index 0b885f1b05..833650d9e1 100644 --- a/Modules/DiffusionImaging/FiberTracking/CMakeLists.txt +++ b/Modules/DiffusionImaging/FiberTracking/CMakeLists.txt @@ -1,45 +1,44 @@ MITK_CHECK_MODULE(_missing_deps DiffusionCore MitkGraphAlgorithms) if(NOT _missing_deps) set(lut_url http://mitk.org/download/data/FibertrackingLUT.tar.gz) set(lut_tarball ${CMAKE_CURRENT_BINARY_DIR}/FibertrackingLUT.tar.gz) message("Downloading FiberTracking LUT ${lut_url}...") file(DOWNLOAD ${lut_url} ${lut_tarball} EXPECTED_MD5 38ecb6d4a826c9ebb0f4965eb9aeee44 TIMEOUT 20 STATUS status SHOW_PROGRESS ) list(GET status 0 status_code) list(GET status 1 status_msg) if(NOT status_code EQUAL 0) message(SEND_ERROR "${status_msg} (error code ${status_code})") else() message("done.") endif() file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/Resources) message("Unpacking FiberTracking LUT tarball...") execute_process(COMMAND ${CMAKE_COMMAND} -E tar xzf ../FibertrackingLUT.tar.gz WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/Resources RESULT_VARIABLE result ERROR_VARIABLE err_msg) if(result) message(SEND_ERROR "Unpacking FibertrackingLUT.tar.gz failed: ${err_msg}") else() message("done.") endif() endif() MITK_CREATE_MODULE( FiberTracking SUBPROJECTS MITK-DTI INCLUDE_DIRS Algorithms Algorithms/GibbsTracking Algorithms/StochasticTracking IODataStructures IODataStructures/FiberBundleX IODataStructures/PlanarFigureComposite Interactions SignalModels Rendering ${CMAKE_CURRENT_BINARY_DIR} DEPENDS DiffusionCore MitkGraphAlgorithms ) if(MODULE_IS_ENABLED) add_subdirectory(Testing) - add_subdirectory(MiniApps) endif() diff --git a/Modules/DiffusionImaging/FiberTracking/MiniApps/MiniAppManager.cpp b/Modules/DiffusionImaging/FiberTracking/MiniApps/MiniAppManager.cpp deleted file mode 100755 index ff9b82b1ad..0000000000 --- a/Modules/DiffusionImaging/FiberTracking/MiniApps/MiniAppManager.cpp +++ /dev/null @@ -1,91 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "MiniAppManager.h" - -MiniAppManager* MiniAppManager::GetInstance() -{ - static MiniAppManager instance; - return &instance; -} - -// Attention: Name of the miniApp must be the last argument!!! -// it will be cut off from the rest of the arguments and then -// the app will be run -int MiniAppManager::RunMiniApp(int argc, char* argv[]) -{ - try - { - std::string nameOfMiniApp; - std::map< std::string, MiniAppFunction >::iterator it = m_Functions.begin(); - - if( argc < 2) - { - std::cout << "Please choose the mini app to execute: " << std::endl; - - for(int i=0; it != m_Functions.end(); ++i,++it) - { - std::cout << "(" << i << ")" << " " << it->first << std::endl; - } - std::cout << "Please select: "; - int choose; - std::cin >> choose; - - it = m_Functions.begin(); - std::advance(it, choose); - if( it != m_Functions.end() ) - nameOfMiniApp = it->first; - } - else - { - nameOfMiniApp = argv[1]; - //--argc; - } - - it = m_Functions.find(nameOfMiniApp); - if(it == m_Functions.end()) - { - std::ostringstream s; s << "MiniApp (" << nameOfMiniApp << ") not found!"; - throw std::invalid_argument(s.str().c_str()); - } - - MITK_INFO << "Start " << nameOfMiniApp << " .."; - MiniAppFunction func = it->second; - return func( argc, argv ); - } - - catch(std::exception& e) - { - MITK_ERROR << e.what(); - } - - catch(...) - { - MITK_ERROR << "Unknown error occurred"; - } - - return EXIT_FAILURE; -} - -///////////////////// -// MiniAppFunction // -///////////////////// -MiniAppManager::MiniAppFunction -MiniAppManager::AddFunction(const std::string& name, MiniAppFunction func) -{ - m_Functions.insert( std::pair(name, func) ); - return func; -} diff --git a/Modules/DiffusionImaging/FiberTracking/MiniApps/MiniAppManager.h b/Modules/DiffusionImaging/FiberTracking/MiniApps/MiniAppManager.h deleted file mode 100755 index 989baad3cc..0000000000 --- a/Modules/DiffusionImaging/FiberTracking/MiniApps/MiniAppManager.h +++ /dev/null @@ -1,38 +0,0 @@ -#ifndef MiniAppManager_h -#define MiniAppManager_h - -#include - -struct MiniAppManager -{ - -public: - - typedef int (*MiniAppFunction)(int argc, char* argv[]); - -public: - - static MiniAppManager* GetInstance(); - - // Attention: Name of the miniApp must be the last argument!!! - // it will be cut off from the rest of the arguments and then - // the app will be run - int RunMiniApp(int argc, char* argv[]); - - // - // Add miniApp - // - MiniAppFunction AddFunction(const std::string& name, MiniAppFunction func); - -protected: - - std::map< std::string, MiniAppFunction > m_Functions; -}; - -// -// Register miniApps -// -#define RegisterFiberTrackingMiniApp(functionName) \ - static MiniAppManager::MiniAppFunction MiniApp##functionName = \ - MiniAppManager::GetInstance()->AddFunction(#functionName, &functionName) -#endif diff --git a/Modules/DiffusionImaging/FiberTracking/MiniApps/ctkCommandLineParser.cpp b/Modules/DiffusionImaging/FiberTracking/MiniApps/ctkCommandLineParser.cpp deleted file mode 100755 index 1a9442ea8b..0000000000 --- a/Modules/DiffusionImaging/FiberTracking/MiniApps/ctkCommandLineParser.cpp +++ /dev/null @@ -1,727 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ -/*========================================================================= - - Library: CTK - - Copyright (c) Kitware Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0.txt - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=========================================================================*/ - -// STL includes -#include - - -// CTK includes -#include "ctkCommandLineParser.h" - -using namespace std; - -namespace -{ -// -------------------------------------------------------------------------- -class CommandLineParserArgumentDescription -{ -public: - - - CommandLineParserArgumentDescription( - const string& longArg, const string& longArgPrefix, - const string& shortArg, const string& shortArgPrefix, - ctkCommandLineParser::Type type, const string& argHelp, - const us::Any& defaultValue, bool ignoreRest, - bool deprecated, bool optional) - : LongArg(longArg), LongArgPrefix(longArgPrefix), - ShortArg(shortArg), ShortArgPrefix(shortArgPrefix), - ArgHelp(argHelp), IgnoreRest(ignoreRest), NumberOfParametersToProcess(0), - Deprecated(deprecated), DefaultValue(defaultValue), Value(type), ValueType(type), Optional(optional) - { - Value = defaultValue; - - switch (type) - { - case ctkCommandLineParser::String: - { - NumberOfParametersToProcess = 1; - } - break; - case ctkCommandLineParser::Bool: - { - NumberOfParametersToProcess = 0; - } - break; - case ctkCommandLineParser::StringList: - { - NumberOfParametersToProcess = -1; - } - break; - case ctkCommandLineParser::Int: - { - NumberOfParametersToProcess = 1; - } - break; - case ctkCommandLineParser::Float: - { - NumberOfParametersToProcess = 1; - } - break; - default: - MITK_INFO << "Type not supported: " << static_cast(type); - } - - } - - ~CommandLineParserArgumentDescription(){} - - bool addParameter(const string& value); - - string helpText(); - - string LongArg; - string LongArgPrefix; - string ShortArg; - string ShortArgPrefix; - string ArgHelp; - bool IgnoreRest; - int NumberOfParametersToProcess; - bool Deprecated; - bool Optional; - - us::Any DefaultValue; - us::Any Value; - ctkCommandLineParser::Type ValueType; -}; - -// -------------------------------------------------------------------------- -bool CommandLineParserArgumentDescription::addParameter(const string &value) -{ - switch (ValueType) - { - case ctkCommandLineParser::String: - { - Value = value; - } - break; - case ctkCommandLineParser::Bool: - { - if (value.compare("true")==0) - Value = true; - else - Value = false; - } - break; - case ctkCommandLineParser::StringList: - { - try - { - ctkCommandLineParser::StringContainerType list = us::any_cast(Value); - list.push_back(value); - Value = list; - } - catch(...) - { - ctkCommandLineParser::StringContainerType list; - list.push_back(value); - Value = list; - } - } - break; - case ctkCommandLineParser::Int: - { - stringstream ss(value); - int i; - ss >> i; - Value = i; - } - break; - case ctkCommandLineParser::Float: - { - stringstream ss(value); - float f; - ss >> f; - Value = f; - } - break; - default: - return false; - } - - return true; -} - -// -------------------------------------------------------------------------- -string CommandLineParserArgumentDescription::helpText() -{ - string text; - - string shortAndLongArg; - if (!this->ShortArg.empty()) - { - shortAndLongArg = " "; - shortAndLongArg += this->ShortArgPrefix; - shortAndLongArg += this->ShortArg; - } - - if (!this->LongArg.empty()) - { - if (this->ShortArg.empty()) - shortAndLongArg.append(" "); - else - shortAndLongArg.append(", "); - - shortAndLongArg += this->LongArgPrefix; - shortAndLongArg += this->LongArg; - } - - text = text + shortAndLongArg + ", " + this->ArgHelp; - - if (this->Optional) - text += " (optional)"; - - if (!this->DefaultValue.Empty()) - { - text = text + ", (default: " + this->DefaultValue.ToString() + ")"; - } - text += "\n"; - return text; -} - -} - -// -------------------------------------------------------------------------- -// ctkCommandLineParser::ctkInternal class - -// -------------------------------------------------------------------------- -class ctkCommandLineParser::ctkInternal -{ -public: - ctkInternal() - : Debug(false), FieldWidth(0), StrictMode(false) - {} - - ~ctkInternal() { } - - CommandLineParserArgumentDescription* argumentDescription(const string& argument); - - vector ArgumentDescriptionList; - map ArgNameToArgumentDescriptionMap; - map > GroupToArgumentDescriptionListMap; - - StringContainerType UnparsedArguments; - StringContainerType ProcessedArguments; - string ErrorString; - bool Debug; - int FieldWidth; - string LongPrefix; - string ShortPrefix; - string CurrentGroup; - string DisableQSettingsLongArg; - string DisableQSettingsShortArg; - bool StrictMode; -}; - -// -------------------------------------------------------------------------- -// ctkCommandLineParser::ctkInternal methods - -// -------------------------------------------------------------------------- -CommandLineParserArgumentDescription* -ctkCommandLineParser::ctkInternal::argumentDescription(const string& argument) -{ - string unprefixedArg = argument; - - if (!LongPrefix.empty() && argument.compare(0, LongPrefix.size(), LongPrefix)==0) - { - // Case when (ShortPrefix + UnPrefixedArgument) matches LongPrefix - if (argument == LongPrefix && !ShortPrefix.empty() && argument.compare(0, ShortPrefix.size(), ShortPrefix)==0) - { - unprefixedArg = argument.substr(ShortPrefix.size(),argument.size()); - } - else - { - unprefixedArg = argument.substr(LongPrefix.size(),argument.size()); - } - } - else if (!ShortPrefix.empty() && argument.compare(0, ShortPrefix.size(), ShortPrefix)==0) - { - unprefixedArg = argument.substr(ShortPrefix.size(),argument.size()); - } - else if (!LongPrefix.empty() && !ShortPrefix.empty()) - { - return 0; - } - - if (ArgNameToArgumentDescriptionMap.count(unprefixedArg)) - { - return this->ArgNameToArgumentDescriptionMap[unprefixedArg]; - } - return 0; -} - -// -------------------------------------------------------------------------- -// ctkCommandLineParser methods - -// -------------------------------------------------------------------------- -ctkCommandLineParser::ctkCommandLineParser() -{ - this->Internal = new ctkInternal(); -} - -// -------------------------------------------------------------------------- -ctkCommandLineParser::~ctkCommandLineParser() -{ - delete this->Internal; -} - -// -------------------------------------------------------------------------- -map ctkCommandLineParser::parseArguments(const StringContainerType& arguments, - bool* ok) -{ - // Reset - this->Internal->UnparsedArguments.clear(); - this->Internal->ProcessedArguments.clear(); - this->Internal->ErrorString.clear(); - // foreach (CommandLineParserArgumentDescription* desc, this->Internal->ArgumentDescriptionList) - for (int i=0; iArgumentDescriptionList.size(); i++) - { - CommandLineParserArgumentDescription* desc = Internal->ArgumentDescriptionList.at(i); - desc->Value = us::Any(desc->ValueType); - if (!desc->DefaultValue.Empty()) - { - desc->Value = desc->DefaultValue; - } - } - - bool error = false; - bool ignoreRest = false; - CommandLineParserArgumentDescription * currentArgDesc = 0; - vector parsedArgDescriptions; - for(int i = 1; i < arguments.size(); ++i) - { - string argument = arguments.at(i); - if (this->Internal->Debug) { MITK_DEBUG << "Processing" << argument; } - - // should argument be ignored ? - if (ignoreRest) - { - if (this->Internal->Debug) - { - MITK_DEBUG << " Skipping: IgnoreRest flag was been set"; - } - this->Internal->UnparsedArguments.push_back(argument); - continue; - } - - // Skip if the argument does not start with the defined prefix - if (!(argument.compare(0, Internal->LongPrefix.size(), Internal->LongPrefix)==0 - || argument.compare(0, Internal->ShortPrefix.size(), Internal->ShortPrefix)==0)) - { - if (this->Internal->StrictMode) - { - this->Internal->ErrorString = "Unknown argument "; - this->Internal->ErrorString += argument; - error = true; - break; - } - if (this->Internal->Debug) - { - MITK_DEBUG << " Skipping: It does not start with the defined prefix"; - } - this->Internal->UnparsedArguments.push_back(argument); - continue; - } - - // Skip if argument has already been parsed ... - bool alreadyProcessed = false; - for (int i=0; iProcessedArguments.size(); i++) - if (argument.compare(Internal->ProcessedArguments.at(i))==0) - { - alreadyProcessed = true; - break; - } - - if (alreadyProcessed) - { - if (this->Internal->StrictMode) - { - this->Internal->ErrorString = "Argument "; - this->Internal->ErrorString += argument; - this->Internal->ErrorString += " already processed !"; - error = true; - break; - } - if (this->Internal->Debug) - { - MITK_DEBUG << " Skipping: Already processed !"; - } - continue; - } - - // Retrieve corresponding argument description - currentArgDesc = this->Internal->argumentDescription(argument); - - // Is there a corresponding argument description ? - if (currentArgDesc) - { - // If the argument is deprecated, print the help text but continue processing - if (currentArgDesc->Deprecated) - { - MITK_WARN << "Deprecated argument " << argument << ": " << currentArgDesc->ArgHelp; - } - else - { - parsedArgDescriptions.push_back(currentArgDesc); - } - - this->Internal->ProcessedArguments.push_back(currentArgDesc->ShortArg); - this->Internal->ProcessedArguments.push_back(currentArgDesc->LongArg); - int numberOfParametersToProcess = currentArgDesc->NumberOfParametersToProcess; - ignoreRest = currentArgDesc->IgnoreRest; - if (this->Internal->Debug && ignoreRest) - { - MITK_DEBUG << " IgnoreRest flag is True"; - } - - // Is the number of parameters associated with the argument being processed known ? - if (numberOfParametersToProcess == 0) - { - currentArgDesc->addParameter("true"); - } - else if (numberOfParametersToProcess > 0) - { - string missingParameterError = - "Argument %1 has %2 value(s) associated whereas exacly %3 are expected."; - for(int j=1; j <= numberOfParametersToProcess; ++j) - { - if (i + j >= arguments.size()) - { -// this->Internal->ErrorString = -// missingParameterError.arg(argument).arg(j-1).arg(numberOfParametersToProcess); -// if (this->Internal->Debug) { MITK_DEBUG << this->Internal->ErrorString; } - if (ok) { *ok = false; } - return map(); - } - string parameter = arguments.at(i + j); - if (this->Internal->Debug) - { - MITK_DEBUG << " Processing parameter" << j << ", value:" << parameter; - } - if (this->argumentAdded(parameter)) - { -// this->Internal->ErrorString = -// missingParameterError.arg(argument).arg(j-1).arg(numberOfParametersToProcess); -// if (this->Internal->Debug) { MITK_DEBUG << this->Internal->ErrorString; } - if (ok) { *ok = false; } - return map(); - } - if (!currentArgDesc->addParameter(parameter)) - { -// this->Internal->ErrorString = string( -// "Value(s) associated with argument %1 are incorrect. %2"). -// arg(argument).arg(currentArgDesc->ExactMatchFailedMessage); -// if (this->Internal->Debug) { MITK_DEBUG << this->Internal->ErrorString; } - if (ok) { *ok = false; } - return map(); - } - } - // Update main loop increment - i = i + numberOfParametersToProcess; - } - else if (numberOfParametersToProcess == -1) - { - if (this->Internal->Debug) - { - MITK_DEBUG << " Proccessing StringList ..."; - } - int j = 1; - while(j + i < arguments.size()) - { - if (this->argumentAdded(arguments.at(j + i))) - { - if (this->Internal->Debug) - { - MITK_DEBUG << " No more parameter for" << argument; - } - break; - } - string parameter = arguments.at(j + i); - - if (parameter.compare(0, Internal->LongPrefix.size(), Internal->LongPrefix)==0 - || parameter.compare(0, Internal->ShortPrefix.size(), Internal->ShortPrefix)==0) - { - j--; - break; - } - - if (this->Internal->Debug) - { - MITK_DEBUG << " Processing parameter" << j << ", value:" << parameter; - } - if (!currentArgDesc->addParameter(parameter)) - { -// this->Internal->ErrorString = string( -// "Value(s) associated with argument %1 are incorrect. %2"). -// arg(argument).arg(currentArgDesc->ExactMatchFailedMessage); -// if (this->Internal->Debug) { MITK_DEBUG << this->Internal->ErrorString; } - if (ok) { *ok = false; } - return map(); - } - j++; - } - // Update main loop increment - i = i + j; - } - } - else - { - if (this->Internal->StrictMode) - { - this->Internal->ErrorString = "Unknown argument "; - this->Internal->ErrorString += argument; - error = true; - break; - } - if (this->Internal->Debug) - { - MITK_DEBUG << " Skipping: Unknown argument"; - } - this->Internal->UnparsedArguments.push_back(argument); - } - } - - if (ok) - { - *ok = !error; - } - - map parsedArguments; - - int obligatoryArgs = 0; - vector::iterator it; - for(it = Internal->ArgumentDescriptionList.begin(); it != Internal->ArgumentDescriptionList.end();++it) - { - CommandLineParserArgumentDescription* desc = *it; - - if(!desc->Optional) - obligatoryArgs++; - } - - int parsedObligatoryArgs = 0; - for(it = parsedArgDescriptions.begin(); it != parsedArgDescriptions.end();++it) - { - CommandLineParserArgumentDescription* desc = *it; - - string key; - if (!desc->LongArg.empty()) - { - key = desc->LongArg; - } - else - { - key = desc->ShortArg; - } - - if(!desc->Optional) - parsedObligatoryArgs++; - - std::pair elem; elem.first = key; elem.second = desc->Value; - parsedArguments.insert(elem); - } - - if (obligatoryArgs>parsedObligatoryArgs) - { - parsedArguments.clear(); - cout << helpText(); - } - - return parsedArguments; -} - -// ------------------------------------------------------------------------- -map ctkCommandLineParser::parseArguments(int argc, char** argv, bool* ok) -{ - StringContainerType arguments; - - // Create a StringContainerType of arguments - for(int i = 0; i < argc; ++i) - arguments.push_back(argv[i]); - - return this->parseArguments(arguments, ok); -} - -// ------------------------------------------------------------------------- -string ctkCommandLineParser::errorString() const -{ - return this->Internal->ErrorString; -} - -// ------------------------------------------------------------------------- -const ctkCommandLineParser::StringContainerType& ctkCommandLineParser::unparsedArguments() const -{ - return this->Internal->UnparsedArguments; -} - -// -------------------------------------------------------------------------- -void ctkCommandLineParser::addArgument(const string& longarg, const string& shortarg, - Type type, const string& argHelp, - const us::Any& defaultValue, bool optional, bool ignoreRest, - bool deprecated) -{ - if (longarg.empty() && shortarg.empty()) { return; } - - /* Make sure it's not already added */ - bool added = this->Internal->ArgNameToArgumentDescriptionMap.count(longarg); - if (added) { return; } - - added = this->Internal->ArgNameToArgumentDescriptionMap.count(shortarg); - if (added) { return; } - - CommandLineParserArgumentDescription* argDesc = - new CommandLineParserArgumentDescription(longarg, this->Internal->LongPrefix, - shortarg, this->Internal->ShortPrefix, type, - argHelp, defaultValue, ignoreRest, deprecated, optional); - - int argWidth = 0; - if (!longarg.empty()) - { - this->Internal->ArgNameToArgumentDescriptionMap[longarg] = argDesc; - argWidth += longarg.size() + this->Internal->LongPrefix.size(); - } - if (!shortarg.empty()) - { - this->Internal->ArgNameToArgumentDescriptionMap[shortarg] = argDesc; - argWidth += shortarg.size() + this->Internal->ShortPrefix.size() + 2; - } - argWidth += 5; - - // Set the field width for the arguments - if (argWidth > this->Internal->FieldWidth) - { - this->Internal->FieldWidth = argWidth; - } - - this->Internal->ArgumentDescriptionList.push_back(argDesc); - this->Internal->GroupToArgumentDescriptionListMap[this->Internal->CurrentGroup].push_back(argDesc); -} - -// -------------------------------------------------------------------------- -void ctkCommandLineParser::addDeprecatedArgument( - const string& longarg, const string& shortarg, const string& argHelp) -{ - addArgument(longarg, shortarg, StringList, argHelp, us::Any(), false, true); -} - -// -------------------------------------------------------------------------- -int ctkCommandLineParser::fieldWidth() const -{ - return this->Internal->FieldWidth; -} - -// -------------------------------------------------------------------------- -void ctkCommandLineParser::beginGroup(const string& description) -{ - this->Internal->CurrentGroup = description; -} - -// -------------------------------------------------------------------------- -void ctkCommandLineParser::endGroup() -{ - this->Internal->CurrentGroup.clear(); -} - -// -------------------------------------------------------------------------- -string ctkCommandLineParser::helpText() const -{ - string text; - vector deprecatedArgs; - - // Loop over grouped argument descriptions - map >::iterator it; - for(it = Internal->GroupToArgumentDescriptionListMap.begin(); it != Internal->GroupToArgumentDescriptionListMap.end();++it) - { - if (!(*it).first.empty()) - { - text = text + "\n" + (*it).first + "\n"; - } - - vector::iterator it2; - for(it2 = (*it).second.begin(); it2 != (*it).second.end(); ++it2) - { - CommandLineParserArgumentDescription* argDesc = *it2; - if (argDesc->Deprecated) - { - deprecatedArgs.push_back(argDesc); - } - else - { - text += argDesc->helpText(); - } - } - } - - if (!deprecatedArgs.empty()) - { - text += "\nDeprecated arguments:\n"; - vector::iterator it2; - for(it2 = deprecatedArgs.begin(); it2 != deprecatedArgs.end(); ++it2) - { - CommandLineParserArgumentDescription* argDesc = *it2; - text += argDesc->helpText(); - } - } - - return text; -} - -// -------------------------------------------------------------------------- -bool ctkCommandLineParser::argumentAdded(const string& argument) const -{ - return this->Internal->ArgNameToArgumentDescriptionMap.count(argument); -} - -// -------------------------------------------------------------------------- -bool ctkCommandLineParser::argumentParsed(const string& argument) const -{ - for (int i=0; iProcessedArguments.size(); i++) - if (argument.compare(Internal->ProcessedArguments.at(i))==0) - return true; - return false; -} - -// -------------------------------------------------------------------------- -void ctkCommandLineParser::setArgumentPrefix(const string& longPrefix, const string& shortPrefix) -{ - this->Internal->LongPrefix = longPrefix; - this->Internal->ShortPrefix = shortPrefix; -} - -// -------------------------------------------------------------------------- -void ctkCommandLineParser::setStrictModeEnabled(bool strictMode) -{ - this->Internal->StrictMode = strictMode; -} - diff --git a/Modules/DiffusionImaging/FiberTracking/MiniApps/ctkCommandLineParser.h b/Modules/DiffusionImaging/FiberTracking/MiniApps/ctkCommandLineParser.h deleted file mode 100755 index 8ff1f180ff..0000000000 --- a/Modules/DiffusionImaging/FiberTracking/MiniApps/ctkCommandLineParser.h +++ /dev/null @@ -1,422 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ -/*========================================================================= - - Library: CTK - - Copyright (c) Kitware Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0.txt - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=========================================================================*/ - -#ifndef __ctkCommandLineParser_h -#define __ctkCommandLineParser_h - -#include -#include - - -/** - * \ingroup Core - * - * The CTK command line parser. - * - * Use this class to add information about the command line arguments - * your program understands and to easily parse them from a given list - * of strings. - * - * This parser provides the following features: - * - *
    - *
  • Add arguments by supplying a long name and/or a short name. - * Arguments are validated using a regular expression. They can have - * a default value and a help string.
  • - *
  • Deprecated arguments.
  • - *
  • Custom regular expressions for argument validation.
  • - *
  • Set different argument name prefixes for native platform look and feel.
  • - *
  • QSettings support. Default values for arguments can be read from - * a QSettings object.
  • - *
  • Create a help text for the command line arguments with support for - * grouping arguments.
  • - *
- * - * Here is an example how to use this class inside a main function: - * - * \code - * #include - * #include - * #include - * - * int main(int argc, char** argv) - * { - * QCoreApplication app(argc, argv); - * // This is used by QSettings - * QCoreApplication::setOrganizationName("MyOrg"); - * QCoreApplication::setApplicationName("MyApp"); - * - * ctkCommandLineParser parser; - * // Use Unix-style argument names - * parser.setArgumentPrefix("--", "-"); - * // Enable QSettings support - * parser.enableSettings("disable-settings"); - * - * // Add command line argument names - * parser.addArgument("disable-settings", "", us::Any::Bool, "Do not use QSettings"); - * parser.addArgument("help", "h", us::Any::Bool, "Show this help text"); - * parser.addArgument("search-paths", "s", us::Any::StringList, "A list of paths to search"); - * - * // Parse the command line arguments - * bool ok = false; - * map parsedArgs = parser.parseArguments(QCoreApplication::arguments(), &ok); - * if (!ok) - * { - * QTextStream(stderr, QIODevice::WriteOnly) << "Error parsing arguments: " - * << parser.errorString() << "\n"; - * return EXIT_FAILURE; - * } - * - * // Show a help message - * if (parsedArgs.contains("help") || parsedArgs.contains("h")) - * { - * QTextStream(stdout, QIODevice::WriteOnly) << parser.helpText(); - * return EXIT_SUCCESS; - * } - * - * // Do something - * - * return EXIT_SUCCESS; - * } - * \endcode - */ - -using namespace std; - -class ctkCommandLineParser -{ - -public: - - enum Type { - String = 0, - Bool = 1, - StringList = 2, - Int = 3, - Float = 4 - }; - - typedef std::vector< std::string > StringContainerType; - - /** - * Constructs a parser instance. - * - * If QSettings support is enabled by a call to enableSettings() - * a default constructed QSettings instance will be used when parsing - * the command line arguments. Make sure to call QCoreApplication::setOrganizationName() - * and QCoreApplication::setApplicationName() before using default - * constructed QSettings objects. - * - * @param newParent The QObject parent. - */ - ctkCommandLineParser(); - - ~ctkCommandLineParser(); - - /** - * Parse a given list of command line arguments. - * - * This method parses a list of string elements considering the known arguments - * added by calls to addArgument(). If any one of the argument - * values does not match the corresponding regular expression, - * ok is set to false and an empty map object is returned. - * - * The keys in the returned map object correspond to the long argument string, - * if it is not empty. Otherwise, the short argument string is used as key. The - * us::Any values can safely be converted to the type specified in the - * addArgument() method call. - * - * @param arguments A StringContainerType containing command line arguments. Usually - * given by QCoreApplication::arguments(). - * @param ok A pointer to a boolean variable. Will be set to true - * if all regular expressions matched, false otherwise. - * @return A map object mapping the long argument (if empty, the short one) - * to a us::Any containing the value. - */ - - map parseArguments(const StringContainerType &arguments, bool* ok = 0); - - /** - * Convenient method allowing to parse a given list of command line arguments. - * @see parseArguments(const StringContainerType &, bool*) - */ - map parseArguments(int argc, char** argv, bool* ok = 0); - - /** - * Returns a detailed error description if a call to parseArguments() - * failed. - * - * @return The error description, empty if no error occured. - * @see parseArguments(const StringContainerType&, bool*) - */ - string errorString() const; - - /** - * This method returns all unparsed arguments, i.e. all arguments - * for which no long or short name has been registered via a call - * to addArgument(). - * - * @see addArgument() - * - * @return A list containing unparsed arguments. - */ - const StringContainerType& unparsedArguments() const; - - /** - * Checks if the given argument has been added via a call - * to addArgument(). - * - * @see addArgument() - * - * @param argument The argument to be checked. - * @return true if the argument was added, false - * otherwise. - */ - bool argumentAdded(const string& argument) const; - - /** - * Checks if the given argument has been parsed successfully by a previous - * call to parseArguments(). - * - * @param argument The argument to be checked. - * @return true if the argument was parsed, false - * otherwise. - */ - bool argumentParsed(const string& argument) const; - - /** - * Adds a command line argument. An argument can have a long name - * (like --long-argument-name), a short name (like -l), or both. The type - * of the argument can be specified by using the type parameter. - * The following types are supported: - * - * - * - * - * - * - * - * - *
Type# of parametersDefault regular exprExample
us::Any::String1.*--test-string StringParameter
us::Any::Bool0does not apply--enable-something
us::Any::StringList-1.*--test-list string1 string2
us::Any::Int1-?[0-9]+--test-int -5
- * - * The regular expressions are used to validate the parameters of command line - * arguments. You can restrict the valid set of parameters by calling - * setExactMatchRegularExpression() for your argument. - * - * Optionally, a help string and a default value can be provided for the argument. If - * the us::Any type of the default value does not match type, an - * exception is thrown. Arguments with default values are always returned by - * parseArguments(). - * - * You can also declare an argument deprecated, by setting deprecated - * to true. Alternatively you can add a deprecated argument by calling - * addDeprecatedArgument(). - * - * If the long or short argument has already been added, or if both are empty strings, - * the method call has no effect. - * - * @param longarg The long argument name. - * @param shortarg The short argument name. - * @param type The argument type (see the list above for supported types). - * @param argHelp A help string describing the argument. - * @param defaultValue A default value for the argument. - * @param ignoreRest All arguments after the current one will be ignored. - * @param deprecated Declares the argument deprecated. - * - * @see setExactMatchRegularExpression() - * @see addDeprecatedArgument() - * @throws std::logic_error If the us::Any type of defaultValue - * does not match type, a std::logic_error is thrown. - */ - void addArgument(const string& longarg, const string& shortarg, - Type type, const string& argHelp = string(), - const us::Any& defaultValue = us::Any(), bool optional=true, - bool ignoreRest = false, bool deprecated = false); - - /** - * Adds a deprecated command line argument. If a deprecated argument is provided - * on the command line, argHelp is displayed in the console and - * processing continues with the next argument. - * - * Deprecated arguments are grouped separately at the end of the help text - * returned by helpText(). - * - * @param longarg The long argument name. - * @param shortarg The short argument name. - * @param argHelp A help string describing alternatives to the deprecated argument. - */ - void addDeprecatedArgument(const string& longarg, const string& shortarg, - const string& argHelp); - - /** - * Sets a custom regular expression for validating argument parameters. The method - * errorString() can be used the get the last error description. - * - * @param argument The previously added long or short argument name. - * @param expression A regular expression which the arugment parameters must match. - * @param exactMatchFailedMessage An error message explaining why the parameter did - * not match. - * - * @return true if the argument was found and the regular expression was set, - * false otherwise. - * - * @see errorString() - */ - bool setExactMatchRegularExpression(const string& argument, const string& expression, - const string& exactMatchFailedMessage); - - /** - * The field width for the argument names without the help text. - * - * @return The argument names field width in the help text. - */ - int fieldWidth() const; - - /** - * Creates a help text containing properly formatted argument names and help strings - * provided by calls to addArgument(). The arguments can be grouped by - * using beginGroup() and endGroup(). - * - * @param charPad The padding character. - * @return The formatted help text. - */ - string helpText() const; - - /** - * Sets the argument prefix for long and short argument names. This can be used - * to create native command line arguments without changing the calls to - * addArgument(). For example on Unix-based systems, long argument - * names start with "--" and short names with "-", while on Windows argument names - * always start with "/". - * - * Note that all methods in ctkCommandLineParser which take an argument name - * expect the name as it was supplied to addArgument. - * - * Example usage: - * - * \code - * ctkCommandLineParser parser; - * parser.setArgumentPrefix("--", "-"); - * parser.addArgument("long-argument", "l", us::Any::String); - * StringContainerType args; - * args << "program name" << "--long-argument Hi"; - * parser.parseArguments(args); - * \endcode - * - * @param longPrefix The prefix for long argument names. - * @param shortPrefix The prefix for short argument names. - */ - void setArgumentPrefix(const string& longPrefix, const string& shortPrefix); - - /** - * Begins a new group for documenting arguments. All newly added arguments via - * addArgument() will be put in the new group. You can close the - * current group by calling endGroup() or be opening a new group. - * - * Note that groups cannot be nested and all arguments which do not belong to - * a group will be listed at the top of the text created by helpText(). - * - * @param description The description of the group - */ - void beginGroup(const string& description); - - /** - * Ends the current group. - * - * @see beginGroup(const string&) - */ - void endGroup(); - - /** - * Enables QSettings support in ctkCommandLineParser. If an argument name is found - * in the QSettings instance with a valid us::Any, the value is considered as - * a default value and overwrites default values registered with - * addArgument(). User supplied values on the command line overwrite - * values in the QSettings instance, except for arguments with multiple parameters - * which are merged with QSettings values. Call mergeSettings(false) - * to disable merging. - * - * See ctkCommandLineParser(QSettings*) for information about how to - * supply a QSettings instance. - * - * Additionally, a long and short argument name can be specified which will disable - * QSettings support if supplied on the command line. The argument name must be - * registered as a regular argument via addArgument(). - * - * @param disableLongArg Long argument name. - * @param disableShortArg Short argument name. - * - * @see ctkCommandLineParser(QSettings*) - */ - void enableSettings(const string& disableLongArg = "", - const string& disableShortArg = ""); - - /** - * Controlls the merging behavior of user values and QSettings values. - * - * If merging is on (the default), user supplied values for an argument - * which can take more than one parameter are merged with values stored - * in the QSettings instance. If merging is off, the user values overwrite - * the QSettings values. - * - * @param merge true enables QSettings merging, false - * disables it. - */ - void mergeSettings(bool merge); - - /** - * Can be used to check if QSettings support has been enabled by a call to - * enableSettings(). - * - * @return true if QSettings support is enabled, false - * otherwise. - */ - bool settingsEnabled() const; - - - /** - * Can be used to teach the parser to stop parsing the arguments and return False when - * an unknown argument is encountered. By default StrictMode is disabled. - * - * @see parseArguments(const StringContainerType &, bool*) - */ - void setStrictModeEnabled(bool strictMode); - -private: - class ctkInternal; - ctkInternal * Internal; -}; - -#endif diff --git a/Modules/DiffusionImaging/FiberTracking/MiniApps/mitkFiberTrackingMiniApps.cpp b/Modules/DiffusionImaging/FiberTracking/MiniApps/mitkFiberTrackingMiniApps.cpp deleted file mode 100755 index c7d6ac601a..0000000000 --- a/Modules/DiffusionImaging/FiberTracking/MiniApps/mitkFiberTrackingMiniApps.cpp +++ /dev/null @@ -1,22 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include - -int main(int argc, char* argv[]) -{ - return MiniAppManager::GetInstance()->RunMiniApp(argc, argv); -} diff --git a/Modules/DiffusionImaging/FiberTracking/files.cmake b/Modules/DiffusionImaging/FiberTracking/files.cmake index d29b958166..8ea747434e 100644 --- a/Modules/DiffusionImaging/FiberTracking/files.cmake +++ b/Modules/DiffusionImaging/FiberTracking/files.cmake @@ -1,108 +1,103 @@ set(CPP_FILES - - MiniApps/ctkCommandLineParser.h - # DataStructures -> FiberBundleX IODataStructures/FiberBundleX/mitkFiberBundleX.cpp IODataStructures/FiberBundleX/mitkFiberBundleXWriter.cpp IODataStructures/FiberBundleX/mitkFiberBundleXReader.cpp IODataStructures/FiberBundleX/mitkFiberBundleXIOFactory.cpp IODataStructures/FiberBundleX/mitkFiberBundleXWriterFactory.cpp IODataStructures/FiberBundleX/mitkFiberBundleXSerializer.cpp IODataStructures/FiberBundleX/mitkTrackvis.cpp # IODataStructures/FiberBundleX/mitkFiberBundleXThreadMonitor.cpp # DataStructures -> PlanarFigureComposite IODataStructures/PlanarFigureComposite/mitkPlanarFigureComposite.cpp # DataStructures IODataStructures/mitkFiberTrackingObjectFactory.cpp # Rendering Rendering/mitkFiberBundleXMapper2D.cpp Rendering/mitkFiberBundleXMapper3D.cpp # Rendering/mitkFiberBundleXThreadMonitorMapper3D.cpp #Rendering/mitkPlanarFigureMapper3D.cpp # Interactions Interactions/mitkFiberBundleInteractor.cpp # Tractography Algorithms/GibbsTracking/mitkParticleGrid.cpp Algorithms/GibbsTracking/mitkMetropolisHastingsSampler.cpp Algorithms/GibbsTracking/mitkEnergyComputer.cpp Algorithms/GibbsTracking/mitkGibbsEnergyComputer.cpp Algorithms/GibbsTracking/mitkFiberBuilder.cpp Algorithms/GibbsTracking/mitkSphereInterpolator.cpp ) set(H_FILES - MiniApps/ctkCommandLineParser.h - # Rendering Rendering/mitkFiberBundleXMapper3D.h Rendering/mitkFiberBundleXMapper2D.h # Rendering/mitkFiberBundleXThreadMonitorMapper3D.h #Rendering/mitkPlanarFigureMapper3D.h # DataStructures -> FiberBundleX IODataStructures/FiberBundleX/mitkFiberBundleX.h IODataStructures/FiberBundleX/mitkFiberBundleXWriter.h IODataStructures/FiberBundleX/mitkFiberBundleXReader.h IODataStructures/FiberBundleX/mitkFiberBundleXIOFactory.h IODataStructures/FiberBundleX/mitkFiberBundleXWriterFactory.h IODataStructures/FiberBundleX/mitkFiberBundleXSerializer.h # IODataStructures/FiberBundleX/mitkFiberBundleXThreadMonitor.h IODataStructures/FiberBundleX/mitkTrackvis.h IODataStructures/mitkFiberTrackingObjectFactory.h # Algorithms Algorithms/itkTractDensityImageFilter.h Algorithms/itkTractsToFiberEndingsImageFilter.h Algorithms/itkTractsToRgbaImageFilter.h Algorithms/itkElectrostaticRepulsionDiffusionGradientReductionFilter.h Algorithms/itkFibersFromPlanarFiguresFilter.h Algorithms/itkTractsToDWIImageFilter.h Algorithms/itkTractsToVectorImageFilter.h Algorithms/itkKspaceImageFilter.h Algorithms/itkDftImageFilter.h Algorithms/itkAddArtifactsToDwiImageFilter.h Algorithms/itkFieldmapGeneratorFilter.h Algorithms/itkEvaluateDirectionImagesFilter.h Algorithms/itkEvaluateTractogramDirectionsFilter.h # (old) Tractography Algorithms/itkGibbsTrackingFilter.h Algorithms/itkStochasticTractographyFilter.h Algorithms/itkStreamlineTrackingFilter.h Algorithms/GibbsTracking/mitkParticle.h Algorithms/GibbsTracking/mitkParticleGrid.h Algorithms/GibbsTracking/mitkMetropolisHastingsSampler.h Algorithms/GibbsTracking/mitkSimpSamp.h Algorithms/GibbsTracking/mitkEnergyComputer.h Algorithms/GibbsTracking/mitkGibbsEnergyComputer.h Algorithms/GibbsTracking/mitkSphereInterpolator.h Algorithms/GibbsTracking/mitkFiberBuilder.h # Signal Models SignalModels/mitkDiffusionSignalModel.h SignalModels/mitkTensorModel.h SignalModels/mitkBallModel.h SignalModels/mitkDotModel.h SignalModels/mitkAstroStickModel.h SignalModels/mitkStickModel.h SignalModels/mitkDiffusionNoiseModel.h SignalModels/mitkRicianNoiseModel.h SignalModels/mitkKspaceArtifact.h ) set(RESOURCE_FILES # Binary directory resources FiberTrackingLUTBaryCoords.bin FiberTrackingLUTIndices.bin # Shaders Shaders/mitkShaderFiberClipping.xml ) diff --git a/Modules/DiffusionImaging/FiberTracking/MiniApps/CMakeLists.txt b/Modules/DiffusionImaging/MiniApps/CMakeLists.txt similarity index 59% rename from Modules/DiffusionImaging/FiberTracking/MiniApps/CMakeLists.txt rename to Modules/DiffusionImaging/MiniApps/CMakeLists.txt index 395b444218..6d16e2324e 100755 --- a/Modules/DiffusionImaging/FiberTracking/MiniApps/CMakeLists.txt +++ b/Modules/DiffusionImaging/MiniApps/CMakeLists.txt @@ -1,53 +1,58 @@ -OPTION(BUILD_FiberTrackingMiniApps "Build commandline tools for fiber tracking" OFF) +OPTION(BUILD_DiffusionMiniApps "Build commandline tools for diffusion" OFF) -IF(BUILD_FiberTrackingMiniApps) +IF(BUILD_DiffusionMiniApps) # include necessary modules here MitkExt QmitkExt MITK_CHECK_MODULE(_RESULT DiffusionCore FiberTracking ) IF(_RESULT) - MESSAGE("Warning: FiberTrackingMiniApps is missing ${_RESULT}") + MESSAGE("Warning: DiffusionMiniApps is missing ${_RESULT}") ELSE(_RESULT) MITK_USE_MODULE( DiffusionCore FiberTracking ) # needed include directories INCLUDE_DIRECTORIES( ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR} ${ALL_INCLUDE_DIRECTORIES}) - PROJECT( mitkFiberTrackingMiniApps ) + PROJECT( mitkDiffusionMiniApps ) # fill in the standalone executables here - SET(FIBERTRACKINGMINIAPPS - mitkFiberTrackingMiniApps + SET(DIFFUSIONMINIAPPS + mitkDiffusionMiniApps ) # set additional files here - SET(FIBERTRACKING_ADDITIONAL_FILES + SET(DIFFUSIONCORE_ADDITIONAL_FILES MiniAppManager.cpp + FileFormatConverter.cpp + TensorReconstruction.cpp + QballReconstruction.cpp + DiffusionIndices.cpp + CopyGeometry.cpp GibbsTracking.cpp StreamlineTracking.cpp FiberProcessing.cpp TractometerAngularErrorTool.cpp TractogramAngularError.cpp FiberDirectionExtraction.cpp PeakExtraction.cpp ) # create an executable foreach tool (only one at the moment) - FOREACH(tool ${FIBERTRACKINGMINIAPPS}) + FOREACH(tool ${DIFFUSIONMINIAPPS}) ADD_EXECUTABLE( ${tool} ${tool}.cpp - ${FIBERTRACKING_ADDITIONAL_FILES} + ${DIFFUSIONCORE_ADDITIONAL_FILES} ) TARGET_LINK_LIBRARIES( ${tool} ${ALL_LIBRARIES} ) ENDFOREACH(tool) ENDIF() - MITK_INSTALL_TARGETS(EXECUTABLES mitkFiberTrackingMiniApps ) + MITK_INSTALL_TARGETS(EXECUTABLES mitkDiffusionMiniApps ) -ENDIF(BUILD_FiberTrackingMiniApps) +ENDIF(BUILD_DiffusionMiniApps) diff --git a/Modules/DiffusionImaging/DiffusionCore/MiniApps/CopyGeometry.cpp b/Modules/DiffusionImaging/MiniApps/CopyGeometry.cpp similarity index 98% rename from Modules/DiffusionImaging/DiffusionCore/MiniApps/CopyGeometry.cpp rename to Modules/DiffusionImaging/MiniApps/CopyGeometry.cpp index 35b9ef5e89..ce9f4a78e0 100755 --- a/Modules/DiffusionImaging/DiffusionCore/MiniApps/CopyGeometry.cpp +++ b/Modules/DiffusionImaging/MiniApps/CopyGeometry.cpp @@ -1,93 +1,93 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "MiniAppManager.h" #include #include #include #include #include #include #include "ctkCommandLineParser.h" using namespace mitk; #include "ctkCommandLineParser.h" int CopyGeometry(int argc, char* argv[]) { ctkCommandLineParser parser; parser.setArgumentPrefix("--", "-"); parser.addArgument("in", "i", ctkCommandLineParser::String, "input image", us::Any(), false); parser.addArgument("ref", "r", ctkCommandLineParser::String, "reference image", us::Any(), false); parser.addArgument("out", "o", ctkCommandLineParser::String, "output image", us::Any(), false); map parsedArgs = parser.parseArguments(argc, argv); if (parsedArgs.size()==0) return EXIT_FAILURE; // mandatory arguments string imageName = us::any_cast(parsedArgs["in"]); string refImage = us::any_cast(parsedArgs["ref"]); string outImage = us::any_cast(parsedArgs["out"]); try { RegisterDiffusionCoreObjectFactory(); MITK_INFO << "Loading image " << imageName; const std::string s1="", s2=""; std::vector infile = BaseDataIO::LoadBaseDataFromFile( refImage, s1, s2, false ); Image::Pointer source = dynamic_cast(infile.at(0).GetPointer()); infile = BaseDataIO::LoadBaseDataFromFile( imageName, s1, s2, false ); Image::Pointer target = dynamic_cast(infile.at(0).GetPointer()); mitk::Geometry3D* s_geom = source->GetGeometry(); mitk::Geometry3D* t_geom = target->GetGeometry(); t_geom->SetIndexToWorldTransform(s_geom->GetIndexToWorldTransform()); target->SetGeometry(t_geom); if ( dynamic_cast*>(target.GetPointer()) ) { MITK_INFO << "Writing " << outImage; DiffusionImage::Pointer dwi = dynamic_cast*>(target.GetPointer()); NrrdDiffusionImageWriter::Pointer writer = NrrdDiffusionImageWriter::New(); writer->SetFileName(outImage); writer->SetInput(dwi); writer->Update(); } else mitk::IOUtil::SaveImage(target, outImage); } catch (itk::ExceptionObject e) { MITK_INFO << e; return EXIT_FAILURE; } catch (std::exception e) { MITK_INFO << e.what(); return EXIT_FAILURE; } catch (...) { MITK_INFO << "ERROR!?!"; return EXIT_FAILURE; } MITK_INFO << "DONE"; return EXIT_SUCCESS; } -RegisterDiffusionCoreMiniApp(CopyGeometry); +RegisterDiffusionMiniApp(CopyGeometry); diff --git a/Modules/DiffusionImaging/DiffusionCore/MiniApps/DiffusionIndices.cpp b/Modules/DiffusionImaging/MiniApps/DiffusionIndices.cpp similarity index 94% rename from Modules/DiffusionImaging/DiffusionCore/MiniApps/DiffusionIndices.cpp rename to Modules/DiffusionImaging/MiniApps/DiffusionIndices.cpp index c01941e9fc..738fb86c89 100644 --- a/Modules/DiffusionImaging/DiffusionCore/MiniApps/DiffusionIndices.cpp +++ b/Modules/DiffusionImaging/MiniApps/DiffusionIndices.cpp @@ -1,141 +1,148 @@ /*=================================================================== 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 "MiniAppManager.h" #include #include #include #include #include #include #include #include #include #include "ctkCommandLineParser.h" #include +#include /** * Calculate indices derived from Qball or tensor images */ int DiffusionIndices(int argc, char* argv[]) { ctkCommandLineParser parser; parser.setArgumentPrefix("--", "-"); parser.addArgument("input", "i", ctkCommandLineParser::String, "input image (tensor, Q-ball or FSL/MRTrix SH-coefficient image)", us::Any(), false); parser.addArgument("index", "idx", ctkCommandLineParser::String, "index (fa, gfa, ra, ad, rd, ca, l2, l3, md)", us::Any(), false); parser.addArgument("outFile", "o", ctkCommandLineParser::String, "output file", us::Any(), false); map parsedArgs = parser.parseArguments(argc, argv); if (parsedArgs.size()==0) return EXIT_FAILURE; string inFileName = us::any_cast(parsedArgs["input"]); string index = us::any_cast(parsedArgs["index"]); string outFileName = us::any_cast(parsedArgs["outFile"]); + string ext = itksys::SystemTools::GetFilenameLastExtension(outFileName); + if (ext.empty()) + outFileName += ".nrrd"; + try { RegisterDiffusionCoreObjectFactory(); // load input image const std::string s1="", s2=""; std::vector infile = mitk::BaseDataIO::LoadBaseDataFromFile( inFileName, s1, s2, false ); if( boost::algorithm::ends_with(inFileName, ".qbi") && index=="gfa" ) { typedef itk::Vector OdfVectorType; typedef itk::Image ItkQballImageType; mitk::QBallImage::Pointer mitkQballImage = dynamic_cast(infile.at(0).GetPointer()); ItkQballImageType::Pointer itk_qbi = ItkQballImageType::New(); mitk::CastToItkImage(mitkQballImage, itk_qbi); typedef itk::DiffusionQballGeneralizedFaImageFilter GfaFilterType; GfaFilterType::Pointer gfaFilter = GfaFilterType::New(); gfaFilter->SetInput(itk_qbi); gfaFilter->SetComputationMethod(GfaFilterType::GFA_STANDARD); gfaFilter->Update(); MITK_INFO << "Writing " << outFileName; itk::ImageFileWriter< itk::Image >::Pointer fileWriter = itk::ImageFileWriter< itk::Image >::New(); fileWriter->SetInput(gfaFilter->GetOutput()); fileWriter->SetFileName(outFileName); fileWriter->Update(); } else if( boost::algorithm::ends_with(inFileName, ".dti") ) { typedef itk::Image< itk::DiffusionTensor3D, 3 > ItkTensorImage; mitk::TensorImage::Pointer mitkTensorImage = dynamic_cast(infile.at(0).GetPointer()); ItkTensorImage::Pointer itk_dti = ItkTensorImage::New(); mitk::CastToItkImage(mitkTensorImage, itk_dti); typedef itk::TensorDerivedMeasurementsFilter MeasurementsType; MeasurementsType::Pointer measurementsCalculator = MeasurementsType::New(); measurementsCalculator->SetInput(itk_dti.GetPointer() ); if(index=="fa") measurementsCalculator->SetMeasure(MeasurementsType::FA); else if(index=="ra") measurementsCalculator->SetMeasure(MeasurementsType::RA); else if(index=="ad") measurementsCalculator->SetMeasure(MeasurementsType::AD); else if(index=="rd") measurementsCalculator->SetMeasure(MeasurementsType::RD); else if(index=="ca") measurementsCalculator->SetMeasure(MeasurementsType::CA); else if(index=="l2") measurementsCalculator->SetMeasure(MeasurementsType::L2); else if(index=="l3") measurementsCalculator->SetMeasure(MeasurementsType::L3); else if(index=="md") measurementsCalculator->SetMeasure(MeasurementsType::MD); else { MITK_WARN << "No valid diffusion index for input image (tensor image) defined"; return EXIT_FAILURE; } measurementsCalculator->Update(); MITK_INFO << "Writing " << outFileName; itk::ImageFileWriter< itk::Image >::Pointer fileWriter = itk::ImageFileWriter< itk::Image >::New(); fileWriter->SetInput(measurementsCalculator->GetOutput()); fileWriter->SetFileName(outFileName); fileWriter->Update(); } + else + MITK_INFO << "Diffusion index " << index << " not supported for supplied file type."; } catch (itk::ExceptionObject e) { MITK_INFO << e; return EXIT_FAILURE; } catch (std::exception e) { MITK_INFO << e.what(); return EXIT_FAILURE; } catch (...) { MITK_INFO << "ERROR!?!"; return EXIT_FAILURE; } return EXIT_SUCCESS; } -RegisterDiffusionCoreMiniApp(DiffusionIndices); +RegisterDiffusionMiniApp(DiffusionIndices); diff --git a/Modules/DiffusionImaging/FiberTracking/MiniApps/FiberDirectionExtraction.cpp b/Modules/DiffusionImaging/MiniApps/FiberDirectionExtraction.cpp similarity index 99% rename from Modules/DiffusionImaging/FiberTracking/MiniApps/FiberDirectionExtraction.cpp rename to Modules/DiffusionImaging/MiniApps/FiberDirectionExtraction.cpp index 8d2113a4f4..f7f97cb4c9 100755 --- a/Modules/DiffusionImaging/FiberTracking/MiniApps/FiberDirectionExtraction.cpp +++ b/Modules/DiffusionImaging/MiniApps/FiberDirectionExtraction.cpp @@ -1,167 +1,167 @@ /*=================================================================== 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 "MiniAppManager.h" #include #include #include #include #include #include #include #include "ctkCommandLineParser.h" #include #include #include #include #include #include #define _USE_MATH_DEFINES #include int FiberDirectionExtraction(int argc, char* argv[]) { ctkCommandLineParser parser; parser.setArgumentPrefix("--", "-"); parser.addArgument("input", "i", ctkCommandLineParser::String, "input tractogram (.fib, vtk ascii file format)", us::Any(), false); parser.addArgument("out", "o", ctkCommandLineParser::String, "output root", us::Any(), false); parser.addArgument("mask", "m", ctkCommandLineParser::String, "mask image"); parser.addArgument("athresh", "a", ctkCommandLineParser::Float, "angular threshold in degrees. closer fiber directions are regarded as one direction and clustered together.", 25, true); parser.addArgument("verbose", "v", ctkCommandLineParser::Bool, "output optional and intermediate calculation results"); map parsedArgs = parser.parseArguments(argc, argv); if (parsedArgs.size()==0) return EXIT_FAILURE; string fibFile = us::any_cast(parsedArgs["input"]); string maskImage(""); if (parsedArgs.count("mask")) maskImage = us::any_cast(parsedArgs["mask"]); float angularThreshold = 25; if (parsedArgs.count("athresh")) angularThreshold = us::any_cast(parsedArgs["athresh"]); string outRoot = us::any_cast(parsedArgs["out"]); bool verbose = false; if (parsedArgs.count("verbose")) verbose = us::any_cast(parsedArgs["verbose"]); try { RegisterDiffusionCoreObjectFactory(); RegisterFiberTrackingObjectFactory(); typedef itk::Image ItkUcharImgType; typedef itk::Image< itk::Vector< float, 3>, 3 > ItkDirectionImage3DType; typedef itk::VectorContainer< int, ItkDirectionImage3DType::Pointer > ItkDirectionImageContainerType; // load fiber bundle mitk::FiberBundleX::Pointer inputTractogram = dynamic_cast(mitk::IOUtil::LoadDataNode(fibFile)->GetData()); // load/create mask image ItkUcharImgType::Pointer itkMaskImage = NULL; if (maskImage.compare("")!=0) { MITK_INFO << "Using mask image"; itkMaskImage = ItkUcharImgType::New(); mitk::Image::Pointer mitkMaskImage = dynamic_cast(mitk::IOUtil::LoadDataNode(maskImage)->GetData()); mitk::CastToItkImage(mitkMaskImage, itkMaskImage); } // extract directions from fiber bundle itk::TractsToVectorImageFilter::Pointer fOdfFilter = itk::TractsToVectorImageFilter::New(); fOdfFilter->SetFiberBundle(inputTractogram); fOdfFilter->SetMaskImage(itkMaskImage); fOdfFilter->SetAngularThreshold(cos(angularThreshold*M_PI/180)); fOdfFilter->SetNormalizeVectors(true); fOdfFilter->SetUseWorkingCopy(false); fOdfFilter->Update(); ItkDirectionImageContainerType::Pointer directionImageContainer = fOdfFilter->GetDirectionImageContainer(); // write direction images for (int i=0; iSize(); i++) { itk::TractsToVectorImageFilter::ItkDirectionImageType::Pointer itkImg = directionImageContainer->GetElement(i); typedef itk::ImageFileWriter< itk::TractsToVectorImageFilter::ItkDirectionImageType > WriterType; WriterType::Pointer writer = WriterType::New(); string outfilename = outRoot; outfilename.append("_DIRECTION_"); outfilename.append(boost::lexical_cast(i)); outfilename.append(".nrrd"); MITK_INFO << "writing " << outfilename; writer->SetFileName(outfilename.c_str()); writer->SetInput(itkImg); writer->Update(); } if (verbose) { // write vector field mitk::FiberBundleX::Pointer directions = fOdfFilter->GetOutputFiberBundle(); mitk::CoreObjectFactory::FileWriterList fileWriters = mitk::CoreObjectFactory::GetInstance()->GetFileWriters(); for (mitk::CoreObjectFactory::FileWriterList::iterator it = fileWriters.begin() ; it != fileWriters.end() ; ++it) { if ( (*it)->CanWriteBaseDataType(directions.GetPointer()) ) { string outfilename = outRoot; outfilename.append("_VECTOR_FIELD.fib"); (*it)->SetFileName( outfilename.c_str() ); (*it)->DoWrite( directions.GetPointer() ); } } // write num direction image { ItkUcharImgType::Pointer numDirImage = fOdfFilter->GetNumDirectionsImage(); typedef itk::ImageFileWriter< ItkUcharImgType > WriterType; WriterType::Pointer writer = WriterType::New(); string outfilename = outRoot; outfilename.append("_NUM_DIRECTIONS.nrrd"); MITK_INFO << "writing " << outfilename; writer->SetFileName(outfilename.c_str()); writer->SetInput(numDirImage); writer->Update(); } } MITK_INFO << "DONE"; } catch (itk::ExceptionObject e) { MITK_INFO << e; return EXIT_FAILURE; } catch (std::exception e) { MITK_INFO << e.what(); return EXIT_FAILURE; } catch (...) { MITK_INFO << "ERROR!?!"; return EXIT_FAILURE; } return EXIT_SUCCESS; } -RegisterFiberTrackingMiniApp(FiberDirectionExtraction); +RegisterDiffusionMiniApp(FiberDirectionExtraction); diff --git a/Modules/DiffusionImaging/FiberTracking/MiniApps/FiberProcessing.cpp b/Modules/DiffusionImaging/MiniApps/FiberProcessing.cpp similarity index 99% rename from Modules/DiffusionImaging/FiberTracking/MiniApps/FiberProcessing.cpp rename to Modules/DiffusionImaging/MiniApps/FiberProcessing.cpp index 191c697f3c..40a45d1775 100644 --- a/Modules/DiffusionImaging/FiberTracking/MiniApps/FiberProcessing.cpp +++ b/Modules/DiffusionImaging/MiniApps/FiberProcessing.cpp @@ -1,160 +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 "MiniAppManager.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "ctkCommandLineParser.h" #include /** * Short program to average redundant gradients in dwi-files */ mitk::FiberBundleX::Pointer LoadFib(std::string filename) { const std::string s1="", s2=""; std::vector fibInfile = mitk::BaseDataIO::LoadBaseDataFromFile( filename, s1, s2, false ); if( fibInfile.empty() ) MITK_INFO << "File " << filename << " could not be read!"; mitk::BaseData::Pointer baseData = fibInfile.at(0); return dynamic_cast(baseData.GetPointer()); } int FiberProcessing(int argc, char* argv[]) { ctkCommandLineParser parser; parser.setArgumentPrefix("--", "-"); parser.addArgument("input", "i", ctkCommandLineParser::String, "input fiber bundle (.fib)", us::Any(), false); parser.addArgument("outFile", "o", ctkCommandLineParser::String, "output fiber bundle (.fib)", us::Any(), false); parser.addArgument("resample", "r", ctkCommandLineParser::Float, "Resample fiber with the given point distance (in mm)"); parser.addArgument("smooth", "s", ctkCommandLineParser::Float, "Smooth fiber with the given point distance (in mm)"); parser.addArgument("minLength", "l", ctkCommandLineParser::Float, "Minimum fiber length (in mm)"); parser.addArgument("maxLength", "m", ctkCommandLineParser::Float, "Maximum fiber length (in mm)"); parser.addArgument("minCurv", "a", ctkCommandLineParser::Float, "Minimum curvature radius (in mm)"); parser.addArgument("mirror", "p", ctkCommandLineParser::Int, "Invert fiber coordinates XYZ (e.g. 010 to invert y-coordinate of each fiber point)"); map parsedArgs = parser.parseArguments(argc, argv); if (parsedArgs.size()==0) return EXIT_FAILURE; float pointDist = -1; if (parsedArgs.count("resample")) pointDist = us::any_cast(parsedArgs["resample"]); float smoothDist = -1; if (parsedArgs.count("smooth")) smoothDist = us::any_cast(parsedArgs["smooth"]); float minFiberLength = -1; if (parsedArgs.count("minLength")) minFiberLength = us::any_cast(parsedArgs["minLength"]); float maxFiberLength = -1; if (parsedArgs.count("maxLength")) maxFiberLength = us::any_cast(parsedArgs["maxLength"]); float curvThres = -1; if (parsedArgs.count("minCurv")) curvThres = us::any_cast(parsedArgs["minCurv"]); int axis = 0; if (parsedArgs.count("mirror")) axis = us::any_cast(parsedArgs["mirror"]); string inFileName = us::any_cast(parsedArgs["input"]); string outFileName = us::any_cast(parsedArgs["outFile"]); try { RegisterDiffusionCoreObjectFactory(); RegisterFiberTrackingObjectFactory(); mitk::FiberBundleX::Pointer fib = LoadFib(inFileName); if (minFiberLength>0) fib->RemoveShortFibers(minFiberLength); if (maxFiberLength>0) fib->RemoveLongFibers(maxFiberLength); if (curvThres>0) fib->ApplyCurvatureThreshold(curvThres, false); if (pointDist>0) fib->ResampleFibers(pointDist); if (smoothDist>0) fib->DoFiberSmoothing(smoothDist); if (axis/100==1) fib->MirrorFibers(0); if ((axis%100)/10==1) fib->MirrorFibers(1); if (axis%10==1) fib->MirrorFibers(2); mitk::CoreObjectFactory::FileWriterList fileWriters = mitk::CoreObjectFactory::GetInstance()->GetFileWriters(); for (mitk::CoreObjectFactory::FileWriterList::iterator it = fileWriters.begin() ; it != fileWriters.end() ; ++it) { if ( (*it)->CanWriteBaseDataType(fib.GetPointer()) ) { MITK_INFO << "writing " << outFileName; (*it)->SetFileName( outFileName.c_str() ); (*it)->DoWrite( fib.GetPointer() ); } } } catch (itk::ExceptionObject e) { MITK_INFO << e; return EXIT_FAILURE; } catch (std::exception e) { MITK_INFO << e.what(); return EXIT_FAILURE; } catch (...) { MITK_INFO << "ERROR!?!"; return EXIT_FAILURE; } } -RegisterFiberTrackingMiniApp(FiberProcessing); +RegisterDiffusionMiniApp(FiberProcessing); diff --git a/Modules/DiffusionImaging/DiffusionCore/MiniApps/ImageFormatConverter.cpp b/Modules/DiffusionImaging/MiniApps/FileFormatConverter.cpp similarity index 58% rename from Modules/DiffusionImaging/DiffusionCore/MiniApps/ImageFormatConverter.cpp rename to Modules/DiffusionImaging/MiniApps/FileFormatConverter.cpp index 7add2929c5..dcf0441ffe 100755 --- a/Modules/DiffusionImaging/DiffusionCore/MiniApps/ImageFormatConverter.cpp +++ b/Modules/DiffusionImaging/MiniApps/FileFormatConverter.cpp @@ -1,86 +1,99 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "MiniAppManager.h" #include #include #include #include +#include #include #include +#include +#include #include "ctkCommandLineParser.h" #include "ctkCommandLineParser.cpp" using namespace mitk; -#include "ctkCommandLineParser.h" -int ImageFormatConverter(int argc, char* argv[]) +int FileFormatConverter(int argc, char* argv[]) { ctkCommandLineParser parser; parser.setArgumentPrefix("--", "-"); - parser.addArgument("in", "i", ctkCommandLineParser::String, "input image", us::Any(), false); - parser.addArgument("out", "o", ctkCommandLineParser::String, "output image", us::Any(), false); + parser.addArgument("in", "i", ctkCommandLineParser::String, "input file", us::Any(), false); + parser.addArgument("out", "o", ctkCommandLineParser::String, "output file", us::Any(), false); map parsedArgs = parser.parseArguments(argc, argv); if (parsedArgs.size()==0) return EXIT_FAILURE; // mandatory arguments - string imageName = us::any_cast(parsedArgs["in"]); - string outImage = us::any_cast(parsedArgs["out"]); + string inName = us::any_cast(parsedArgs["in"]); + string outName = us::any_cast(parsedArgs["out"]); try { RegisterDiffusionCoreObjectFactory(); + RegisterFiberTrackingObjectFactory(); - MITK_INFO << "Loading image " << imageName; + MITK_INFO << "Loading " << inName; const std::string s1="", s2=""; - std::vector infile = BaseDataIO::LoadBaseDataFromFile( imageName, s1, s2, false ); + std::vector infile = BaseDataIO::LoadBaseDataFromFile( inName, s1, s2, false ); + mitk::BaseData::Pointer baseData = infile.at(0); - if ( dynamic_cast*>(infile.at(0).GetPointer()) ) + if ( dynamic_cast*>(baseData.GetPointer()) ) { - MITK_INFO << "Writing " << outImage; - DiffusionImage::Pointer dwi = dynamic_cast*>(infile.at(0).GetPointer()); + MITK_INFO << "Writing " << outName; + DiffusionImage::Pointer dwi = dynamic_cast*>(baseData.GetPointer()); NrrdDiffusionImageWriter::Pointer writer = NrrdDiffusionImageWriter::New(); - writer->SetFileName(outImage); + writer->SetFileName(outName); writer->SetInput(dwi); writer->Update(); } - else if ( dynamic_cast(infile.at(0).GetPointer()) ) + else if ( dynamic_cast(baseData.GetPointer()) ) + { + Image::Pointer image = dynamic_cast(baseData.GetPointer()); + mitk::IOUtil::SaveImage(image, outName); + } + else if ( dynamic_cast(baseData.GetPointer()) ) { - Image::Pointer image = dynamic_cast(infile.at(0).GetPointer()); - mitk::IOUtil::SaveImage(image, outImage); + MITK_INFO << "Writing " << outName; + FiberBundleXWriter::Pointer fibWriter = FiberBundleXWriter::New(); + fibWriter->SetFileName(outName.c_str()); + fibWriter->DoWrite( dynamic_cast(baseData.GetPointer()) ); } + else + MITK_INFO << "File type currently not supported!"; } catch (itk::ExceptionObject e) { MITK_INFO << e; return EXIT_FAILURE; } catch (std::exception e) { MITK_INFO << e.what(); return EXIT_FAILURE; } catch (...) { MITK_INFO << "ERROR!?!"; return EXIT_FAILURE; } MITK_INFO << "DONE"; return EXIT_SUCCESS; } -RegisterDiffusionCoreMiniApp(ImageFormatConverter); +RegisterDiffusionMiniApp(FileFormatConverter); diff --git a/Modules/DiffusionImaging/FiberTracking/MiniApps/GibbsTracking.cpp b/Modules/DiffusionImaging/MiniApps/GibbsTracking.cpp similarity index 99% rename from Modules/DiffusionImaging/FiberTracking/MiniApps/GibbsTracking.cpp rename to Modules/DiffusionImaging/MiniApps/GibbsTracking.cpp index 14259fca23..6d6129c9f3 100755 --- a/Modules/DiffusionImaging/FiberTracking/MiniApps/GibbsTracking.cpp +++ b/Modules/DiffusionImaging/MiniApps/GibbsTracking.cpp @@ -1,215 +1,215 @@ /*=================================================================== 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 "MiniAppManager.h" #include #include #include #include #include #include #include #include #include #include #include #include #include "ctkCommandLineParser.h" #include template typename itk::ShCoefficientImageImporter< float, shOrder >::QballImageType::Pointer TemplatedConvertShCoeffs(mitk::Image* mitkImg, int toolkit) { typedef itk::ShCoefficientImageImporter< float, shOrder > FilterType; typedef mitk::ImageToItk< itk::Image< float, 4 > > CasterType; CasterType::Pointer caster = CasterType::New(); caster->SetInput(mitkImg); caster->Update(); typename FilterType::Pointer filter = FilterType::New(); switch (toolkit) { case 0: filter->SetToolkit(FilterType::FSL); break; case 1: filter->SetToolkit(FilterType::MRTRIX); break; default: filter->SetToolkit(FilterType::FSL); } filter->SetInputImage(caster->GetOutput()); filter->GenerateData(); return filter->GetQballImage(); } int GibbsTracking(int argc, char* argv[]) { ctkCommandLineParser parser; parser.setArgumentPrefix("--", "-"); parser.addArgument("input", "i", ctkCommandLineParser::String, "input image (tensor, Q-ball or FSL/MRTrix SH-coefficient image)", us::Any(), false); parser.addArgument("parameters", "p", ctkCommandLineParser::String, "parameter file (.gtp)", us::Any(), false); parser.addArgument("mask", "m", ctkCommandLineParser::String, "binary mask image"); parser.addArgument("shConvention", "s", ctkCommandLineParser::String, "sh coefficient convention (FSL, MRtrix)", string("FSL"), true); parser.addArgument("outFile", "o", ctkCommandLineParser::String, "output fiber bundle (.fib)", us::Any(), false); map parsedArgs = parser.parseArguments(argc, argv); if (parsedArgs.size()==0) return EXIT_FAILURE; string inFileName = us::any_cast(parsedArgs["input"]); string paramFileName = us::any_cast(parsedArgs["parameters"]); string outFileName = us::any_cast(parsedArgs["outFile"]); try { RegisterDiffusionCoreObjectFactory(); RegisterFiberTrackingObjectFactory(); // instantiate gibbs tracker typedef itk::Vector OdfVectorType; typedef itk::Image ItkQballImageType; typedef itk::GibbsTrackingFilter GibbsTrackingFilterType; GibbsTrackingFilterType::Pointer gibbsTracker = GibbsTrackingFilterType::New(); // load input image const std::string s1="", s2=""; std::vector infile = mitk::BaseDataIO::LoadBaseDataFromFile( inFileName, s1, s2, false ); // try to cast to qball image if( boost::algorithm::ends_with(inFileName, ".qbi") ) { MITK_INFO << "Loading qball image ..."; mitk::QBallImage::Pointer mitkQballImage = dynamic_cast(infile.at(0).GetPointer()); ItkQballImageType::Pointer itk_qbi = ItkQballImageType::New(); mitk::CastToItkImage(mitkQballImage, itk_qbi); gibbsTracker->SetQBallImage(itk_qbi.GetPointer()); } else if( boost::algorithm::ends_with(inFileName, ".dti") ) { MITK_INFO << "Loading tensor image ..."; typedef itk::Image< itk::DiffusionTensor3D, 3 > ItkTensorImage; mitk::TensorImage::Pointer mitkTensorImage = dynamic_cast(infile.at(0).GetPointer()); ItkTensorImage::Pointer itk_dti = ItkTensorImage::New(); mitk::CastToItkImage(mitkTensorImage, itk_dti); gibbsTracker->SetTensorImage(itk_dti); } else if ( boost::algorithm::ends_with(inFileName, ".nii") ) { MITK_INFO << "Loading sh-coefficient image ..."; mitk::Image::Pointer mitkImage = dynamic_cast(infile.at(0).GetPointer()); int nrCoeffs = mitkImage->GetLargestPossibleRegion().GetSize()[3]; int c=3, d=2-2*nrCoeffs; double D = c*c-4*d; int shOrder; if (D>0) { shOrder = (-c+sqrt(D))/2.0; if (shOrder<0) shOrder = (-c-sqrt(D))/2.0; } else if (D==0) shOrder = -c/2.0; MITK_INFO << "using SH-order " << shOrder; int toolkitConvention = 0; if (parsedArgs.count("shConvention")) { string convention = us::any_cast(parsedArgs["shConvention"]).c_str(); if ( boost::algorithm::equals(convention, "MRtrix") ) { toolkitConvention = 1; MITK_INFO << "Using MRtrix style sh-coefficient convention"; } else MITK_INFO << "Using FSL style sh-coefficient convention"; } else MITK_INFO << "Using FSL style sh-coefficient convention"; switch (shOrder) { case 4: gibbsTracker->SetQBallImage(TemplatedConvertShCoeffs<4>(mitkImage, toolkitConvention)); break; case 6: gibbsTracker->SetQBallImage(TemplatedConvertShCoeffs<6>(mitkImage, toolkitConvention)); break; case 8: gibbsTracker->SetQBallImage(TemplatedConvertShCoeffs<8>(mitkImage, toolkitConvention)); break; case 10: gibbsTracker->SetQBallImage(TemplatedConvertShCoeffs<10>(mitkImage, toolkitConvention)); break; case 12: gibbsTracker->SetQBallImage(TemplatedConvertShCoeffs<12>(mitkImage, toolkitConvention)); break; default: MITK_INFO << "SH-order " << shOrder << " not supported"; } } else return EXIT_FAILURE; // global tracking if (parsedArgs.count("mask")) { typedef itk::Image MaskImgType; mitk::Image::Pointer mitkMaskImage = mitk::IOUtil::LoadImage(us::any_cast(parsedArgs["mask"])); MaskImgType::Pointer itk_mask = MaskImgType::New(); mitk::CastToItkImage(mitkMaskImage, itk_mask); gibbsTracker->SetMaskImage(itk_mask); } gibbsTracker->SetDuplicateImage(false); gibbsTracker->SetLoadParameterFile( paramFileName ); // gibbsTracker->SetLutPath( "" ); gibbsTracker->Update(); mitk::FiberBundleX::Pointer mitkFiberBundle = mitk::FiberBundleX::New(gibbsTracker->GetFiberBundle()); mitk::CoreObjectFactory::FileWriterList fileWriters = mitk::CoreObjectFactory::GetInstance()->GetFileWriters(); for (mitk::CoreObjectFactory::FileWriterList::iterator it = fileWriters.begin() ; it != fileWriters.end() ; ++it) { if ( (*it)->CanWriteBaseDataType(mitkFiberBundle.GetPointer()) ) { (*it)->SetFileName( outFileName.c_str() ); (*it)->DoWrite( mitkFiberBundle.GetPointer() ); } } } catch (itk::ExceptionObject e) { MITK_INFO << e; return EXIT_FAILURE; } catch (std::exception e) { MITK_INFO << e.what(); return EXIT_FAILURE; } catch (...) { MITK_INFO << "ERROR!?!"; return EXIT_FAILURE; } return EXIT_SUCCESS; } -RegisterFiberTrackingMiniApp(GibbsTracking); +RegisterDiffusionMiniApp(GibbsTracking); diff --git a/Modules/DiffusionImaging/DiffusionCore/MiniApps/MiniAppManager.cpp b/Modules/DiffusionImaging/MiniApps/MiniAppManager.cpp similarity index 100% rename from Modules/DiffusionImaging/DiffusionCore/MiniApps/MiniAppManager.cpp rename to Modules/DiffusionImaging/MiniApps/MiniAppManager.cpp diff --git a/Modules/DiffusionImaging/DiffusionCore/MiniApps/MiniAppManager.h b/Modules/DiffusionImaging/MiniApps/MiniAppManager.h similarity index 93% rename from Modules/DiffusionImaging/DiffusionCore/MiniApps/MiniAppManager.h rename to Modules/DiffusionImaging/MiniApps/MiniAppManager.h index 02bdcd2869..ea9afddf9f 100755 --- a/Modules/DiffusionImaging/DiffusionCore/MiniApps/MiniAppManager.h +++ b/Modules/DiffusionImaging/MiniApps/MiniAppManager.h @@ -1,38 +1,38 @@ #ifndef MiniAppManager_h #define MiniAppManager_h #include struct MiniAppManager { public: typedef int (*MiniAppFunction)(int argc, char* argv[]); public: static MiniAppManager* GetInstance(); // Attention: Name of the miniApp must be the last argument!!! // it will be cut off from the rest of the arguments and then // the app will be run int RunMiniApp(int argc, char* argv[]); // // Add miniApp // MiniAppFunction AddFunction(const std::string& name, MiniAppFunction func); protected: std::map< std::string, MiniAppFunction > m_Functions; }; // // Register miniApps // -#define RegisterDiffusionCoreMiniApp(functionName) \ +#define RegisterDiffusionMiniApp(functionName) \ static MiniAppManager::MiniAppFunction MiniApp##functionName = \ MiniAppManager::GetInstance()->AddFunction(#functionName, &functionName) #endif diff --git a/Modules/DiffusionImaging/FiberTracking/MiniApps/PeakExtraction.cpp b/Modules/DiffusionImaging/MiniApps/PeakExtraction.cpp similarity index 99% rename from Modules/DiffusionImaging/FiberTracking/MiniApps/PeakExtraction.cpp rename to Modules/DiffusionImaging/MiniApps/PeakExtraction.cpp index 092e723123..59f470d123 100755 --- a/Modules/DiffusionImaging/FiberTracking/MiniApps/PeakExtraction.cpp +++ b/Modules/DiffusionImaging/MiniApps/PeakExtraction.cpp @@ -1,375 +1,375 @@ /*=================================================================== 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 "MiniAppManager.h" #include #include #include #include #include #include #include #include #include #include #include #include #include "ctkCommandLineParser.h" #include #include #include #include #include #include mitk::Image::Pointer LoadData(std::string filename) { if( filename.empty() ) return NULL; const std::string s1="", s2=""; std::vector infile = mitk::BaseDataIO::LoadBaseDataFromFile( filename, s1, s2, false ); if( infile.empty() ) { MITK_INFO << "File " << filename << " could not be read!"; return NULL; } mitk::BaseData::Pointer baseData = infile.at(0); return dynamic_cast(baseData.GetPointer()); } template int Start(int argc, char* argv[]) { ctkCommandLineParser parser; parser.setArgumentPrefix("--", "-"); parser.addArgument("image", "i", ctkCommandLineParser::String, "sh coefficient image", us::Any(), false); parser.addArgument("outroot", "o", ctkCommandLineParser::String, "output root", us::Any(), false); parser.addArgument("mask", "m", ctkCommandLineParser::String, "mask image"); parser.addArgument("normalization", "n", ctkCommandLineParser::Int, "0=no norm, 1=max norm, 2=single vec norm", 1, true); parser.addArgument("numpeaks", "p", ctkCommandLineParser::Int, "maximum number of extracted peaks", 2, true); parser.addArgument("peakthres", "r", ctkCommandLineParser::Float, "peak threshold relative to largest peak", 0.4, true); parser.addArgument("abspeakthres", "a", ctkCommandLineParser::Float, "absolute peak threshold weighted with local GFA value", 0.06, true); parser.addArgument("shConvention", "s", ctkCommandLineParser::String, "use specified SH-basis (MITK, FSL, MRtrix)", string("MITK"), true); parser.addArgument("noFlip", "f", ctkCommandLineParser::Bool, "do not flip input image to match MITK coordinate convention"); map parsedArgs = parser.parseArguments(argc, argv); if (parsedArgs.size()==0) return EXIT_FAILURE; // mandatory arguments string imageName = us::any_cast(parsedArgs["image"]); string outRoot = us::any_cast(parsedArgs["outroot"]); // optional arguments string maskImageName(""); if (parsedArgs.count("mask")) maskImageName = us::any_cast(parsedArgs["mask"]); int normalization = 1; if (parsedArgs.count("normalization")) normalization = us::any_cast(parsedArgs["normalization"]); int numPeaks = 2; if (parsedArgs.count("numpeaks")) numPeaks = us::any_cast(parsedArgs["numpeaks"]); float peakThres = 0.4; if (parsedArgs.count("peakthres")) peakThres = us::any_cast(parsedArgs["peakthres"]); float absPeakThres = 0.06; if (parsedArgs.count("abspeakthres")) absPeakThres = us::any_cast(parsedArgs["abspeakthres"]); bool noFlip = false; if (parsedArgs.count("noFlip")) noFlip = us::any_cast(parsedArgs["noFlip"]); MITK_INFO << "image: " << imageName; MITK_INFO << "outroot: " << outRoot; if (!maskImageName.empty()) MITK_INFO << "mask: " << maskImageName; else MITK_INFO << "no mask image selected"; MITK_INFO << "numpeaks: " << numPeaks; MITK_INFO << "peakthres: " << peakThres; MITK_INFO << "abspeakthres: " << absPeakThres; MITK_INFO << "shOrder: " << shOrder; try { mitk::CoreObjectFactory::GetInstance(); RegisterDiffusionCoreObjectFactory(); mitk::Image::Pointer image = LoadData(imageName); mitk::Image::Pointer mask = LoadData(maskImageName); typedef itk::Image ItkUcharImgType; typedef itk::FiniteDiffOdfMaximaExtractionFilter< float, shOrder, 20242 > MaximaExtractionFilterType; typename MaximaExtractionFilterType::Pointer filter = MaximaExtractionFilterType::New(); int toolkitConvention = 0; if (parsedArgs.count("shConvention")) { string convention = us::any_cast(parsedArgs["shConvention"]).c_str(); if ( boost::algorithm::equals(convention, "FSL") ) { toolkitConvention = 1; MITK_INFO << "Using FSL SH-basis"; } else if ( boost::algorithm::equals(convention, "MRtrix") ) { toolkitConvention = 2; MITK_INFO << "Using MRtrix SH-basis"; } else MITK_INFO << "Using MITK SH-basis"; } else MITK_INFO << "Using MITK SH-basis"; ItkUcharImgType::Pointer itkMaskImage = NULL; if (mask.IsNotNull()) { try{ itkMaskImage = ItkUcharImgType::New(); mitk::CastToItkImage(mask, itkMaskImage); filter->SetMaskImage(itkMaskImage); } catch(...) { } } if (toolkitConvention>0) { MITK_INFO << "Converting coefficient image to MITK format"; typedef itk::ShCoefficientImageImporter< float, shOrder > ConverterType; typedef mitk::ImageToItk< itk::Image< float, 4 > > CasterType; CasterType::Pointer caster = CasterType::New(); caster->SetInput(image); caster->Update(); itk::Image< float, 4 >::Pointer itkImage = caster->GetOutput(); typename ConverterType::Pointer converter = ConverterType::New(); if (noFlip) { converter->SetInputImage(itkImage); } else { MITK_INFO << "Flipping image"; itk::FixedArray flipAxes; flipAxes[0] = true; flipAxes[1] = true; flipAxes[2] = false; flipAxes[3] = false; itk::FlipImageFilter< itk::Image< float, 4 > >::Pointer flipper = itk::FlipImageFilter< itk::Image< float, 4 > >::New(); flipper->SetInput(itkImage); flipper->SetFlipAxes(flipAxes); flipper->Update(); itk::Image< float, 4 >::Pointer flipped = flipper->GetOutput(); flipped->SetDirection(itkImage->GetDirection()); flipped->SetOrigin(itkImage->GetOrigin()); converter->SetInputImage(flipped); } MITK_INFO << "Starting conversion"; switch (toolkitConvention) { case 1: converter->SetToolkit(ConverterType::FSL); filter->SetToolkit(MaximaExtractionFilterType::FSL); break; case 2: converter->SetToolkit(ConverterType::MRTRIX); filter->SetToolkit(MaximaExtractionFilterType::MRTRIX); break; default: converter->SetToolkit(ConverterType::FSL); filter->SetToolkit(MaximaExtractionFilterType::FSL); break; } converter->GenerateData(); filter->SetInput(converter->GetCoefficientImage()); } else { try{ typedef mitk::ImageToItk< typename MaximaExtractionFilterType::CoefficientImageType > CasterType; typename CasterType::Pointer caster = CasterType::New(); caster->SetInput(image); caster->Update(); filter->SetInput(caster->GetOutput()); } catch(...) { MITK_INFO << "wrong image type"; return EXIT_FAILURE; } } filter->SetMaxNumPeaks(numPeaks); filter->SetPeakThreshold(peakThres); filter->SetAbsolutePeakThreshold(absPeakThres); filter->SetAngularThreshold(1); switch (normalization) { case 0: filter->SetNormalizationMethod(MaximaExtractionFilterType::NO_NORM); break; case 1: filter->SetNormalizationMethod(MaximaExtractionFilterType::MAX_VEC_NORM); break; case 2: filter->SetNormalizationMethod(MaximaExtractionFilterType::SINGLE_VEC_NORM); break; } MITK_INFO << "Starting extraction"; filter->Update(); // write direction images { typedef typename MaximaExtractionFilterType::ItkDirectionImageContainer ItkDirectionImageContainer; typename ItkDirectionImageContainer::Pointer container = filter->GetDirectionImageContainer(); for (int i=0; iSize(); i++) { typename MaximaExtractionFilterType::ItkDirectionImage::Pointer itkImg = container->GetElement(i); if (itkMaskImage.IsNotNull()) { itkImg->SetDirection(itkMaskImage->GetDirection()); itkImg->SetOrigin(itkMaskImage->GetOrigin()); } string outfilename = outRoot; outfilename.append("_DIRECTION_"); outfilename.append(boost::lexical_cast(i)); outfilename.append(".nrrd"); MITK_INFO << "writing " << outfilename; typedef itk::ImageFileWriter< typename MaximaExtractionFilterType::ItkDirectionImage > WriterType; typename WriterType::Pointer writer = WriterType::New(); writer->SetFileName(outfilename); writer->SetInput(itkImg); writer->Update(); } } // write num directions image { ItkUcharImgType::Pointer numDirImage = filter->GetNumDirectionsImage(); if (itkMaskImage.IsNotNull()) { numDirImage->SetDirection(itkMaskImage->GetDirection()); numDirImage->SetOrigin(itkMaskImage->GetOrigin()); } string outfilename = outRoot.c_str(); outfilename.append("_NUM_DIRECTIONS.nrrd"); MITK_INFO << "writing " << outfilename; typedef itk::ImageFileWriter< ItkUcharImgType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName(outfilename); writer->SetInput(numDirImage); writer->Update(); } // write vector field { mitk::FiberBundleX::Pointer directions = filter->GetOutputFiberBundle(); string outfilename = outRoot.c_str(); outfilename.append("_VECTOR_FIELD.fib"); mitk::FiberBundleXWriter::Pointer fibWriter = mitk::FiberBundleXWriter::New(); fibWriter->SetFileName(outfilename.c_str()); fibWriter->DoWrite(directions.GetPointer()); } } catch (itk::ExceptionObject e) { MITK_INFO << e; return EXIT_FAILURE; } catch (std::exception e) { MITK_INFO << e.what(); return EXIT_FAILURE; } catch (...) { MITK_INFO << "ERROR!?!"; return EXIT_FAILURE; } MITK_INFO << "DONE"; return EXIT_SUCCESS; } int PeakExtraction(int argc, char* argv[]) { ctkCommandLineParser parser; parser.setArgumentPrefix("--", "-"); parser.addArgument("image", "i", ctkCommandLineParser::String, "sh coefficient image", us::Any(), false); parser.addArgument("shOrder", "sh", ctkCommandLineParser::Int, "spherical harmonics order"); parser.addArgument("outroot", "o", ctkCommandLineParser::String, "output root", us::Any(), false); parser.addArgument("mask", "m", ctkCommandLineParser::String, "mask image"); parser.addArgument("normalization", "n", ctkCommandLineParser::Int, "0=no norm, 1=max norm, 2=single vec norm", 1, true); parser.addArgument("numpeaks", "p", ctkCommandLineParser::Int, "maximum number of extracted peaks", 2, true); parser.addArgument("peakthres", "r", ctkCommandLineParser::Float, "peak threshold relative to largest peak", 0.4, true); parser.addArgument("abspeakthres", "a", ctkCommandLineParser::Float, "absolute peak threshold weighted with local GFA value", 0.06, true); parser.addArgument("shConvention", "s", ctkCommandLineParser::String, "use specified SH-basis (MITK, FSL, MRtrix)", string("MITK"), true); parser.addArgument("noFlip", "f", ctkCommandLineParser::Bool, "do not flip input image to match MITK coordinate convention"); map parsedArgs = parser.parseArguments(argc, argv); if (parsedArgs.size()==0) return EXIT_FAILURE; int shOrder = -1; if (parsedArgs.count("shOrder")) shOrder = us::any_cast(parsedArgs["shOrder"]); switch (shOrder) { case 4: return Start<4>(argc, argv); case 6: return Start<6>(argc, argv); case 8: return Start<8>(argc, argv); case 10: return Start<10>(argc, argv); case 12: return Start<12>(argc, argv); } return EXIT_FAILURE; } -RegisterFiberTrackingMiniApp(PeakExtraction); +RegisterDiffusionMiniApp(PeakExtraction); diff --git a/Modules/DiffusionImaging/MiniApps/QballReconstruction.cpp b/Modules/DiffusionImaging/MiniApps/QballReconstruction.cpp new file mode 100644 index 0000000000..ba08bb75cf --- /dev/null +++ b/Modules/DiffusionImaging/MiniApps/QballReconstruction.cpp @@ -0,0 +1,215 @@ +/*=================================================================== + +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 "MiniAppManager.h" + +#include "mitkBaseDataIOFactory.h" +#include "mitkDiffusionImage.h" +#include "mitkDiffusionCoreObjectFactory.h" +#include "itkAnalyticalDiffusionQballReconstructionImageFilter.h" +#include +#include +#include "ctkCommandLineParser.h" +#include +#include + +using namespace mitk; +/** + * Perform Q-ball reconstruction using a spherical harmonics basis + */ +int QballReconstruction(int argc, char* argv[]) +{ + ctkCommandLineParser parser; + parser.setArgumentPrefix("--", "-"); + parser.addArgument("input", "i", ctkCommandLineParser::String, "input raw dwi (.dwi or .fsl/.fslgz)", us::Any(), false); + parser.addArgument("outFile", "o", ctkCommandLineParser::String, "output file", us::Any(), false); + parser.addArgument("shOrder", "sh", ctkCommandLineParser::Int, "spherical harmonics order", 4, true); + parser.addArgument("b0Threshold", "t", ctkCommandLineParser::Int, "baseline image intensity threshold", 0, true); + parser.addArgument("lambda", "r", ctkCommandLineParser::Float, "ragularization factor lambda", 0.006, true); + parser.addArgument("csa", "csa", ctkCommandLineParser::Bool, "use constant solid angle consideration"); + parser.addArgument("outputCoeffs", "shc", ctkCommandLineParser::Bool, "output file containing the SH coefficients"); + + map parsedArgs = parser.parseArguments(argc, argv); + if (parsedArgs.size()==0) + return EXIT_FAILURE; + + std::string inFileName = us::any_cast(parsedArgs["input"]); + std::string outfilename = us::any_cast(parsedArgs["outFile"]); + outfilename = itksys::SystemTools::GetFilenameWithoutExtension(outfilename); + + int threshold = 0; + if (parsedArgs.count("b0Threshold")) + threshold = us::any_cast(parsedArgs["b0Threshold"]); + + int shOrder = 4; + if (parsedArgs.count("shOrder")) + shOrder = us::any_cast(parsedArgs["shOrder"]); + + float lambda = 0.006; + if (parsedArgs.count("lambda")) + lambda = us::any_cast(parsedArgs["lambda"]); + + int normalization = 0; + if (parsedArgs.count("csa") && us::any_cast(parsedArgs["csa"])) + normalization = 6; + + bool outCoeffs = false; + if (parsedArgs.count("outputCoeffs")) + outCoeffs = us::any_cast(parsedArgs["outputCoeffs"]); + + try + { + RegisterDiffusionCoreObjectFactory(); + + MITK_INFO << "Loading image ..."; + const std::string s1="", s2=""; + std::vector infile = BaseDataIO::LoadBaseDataFromFile( inFileName, s1, s2, false ); + DiffusionImage::Pointer dwi = dynamic_cast*>(infile.at(0).GetPointer()); + dwi->AverageRedundantGradients(0.001); + + mitk::QBallImage::Pointer image = mitk::QBallImage::New(); + mitk::Image::Pointer coeffsImage = mitk::Image::New(); + + MITK_INFO << "SH order: " << shOrder; + MITK_INFO << "lambda: " << lambda; + MITK_INFO << "B0 threshold: " << threshold; + switch ( shOrder ) + { + case 4: + { + typedef itk::AnalyticalDiffusionQballReconstructionImageFilter FilterType; + FilterType::Pointer filter = FilterType::New(); + filter->SetGradientImage( dwi->GetDirections(), dwi->GetVectorImage() ); + filter->SetBValue(dwi->GetB_Value()); + filter->SetThreshold( threshold ); + filter->SetLambda(lambda); + if (normalization==0) + filter->SetNormalizationMethod(FilterType::QBAR_STANDARD); + else + filter->SetNormalizationMethod(FilterType::QBAR_SOLID_ANGLE); + filter->Update(); + image->InitializeByItk( filter->GetOutput() ); + image->SetVolume( filter->GetOutput()->GetBufferPointer() ); + coeffsImage->InitializeByItk( filter->GetCoefficientImage().GetPointer() ); + coeffsImage->SetVolume( filter->GetCoefficientImage()->GetBufferPointer() ); + break; + } + case 6: + { + typedef itk::AnalyticalDiffusionQballReconstructionImageFilter FilterType; + FilterType::Pointer filter = FilterType::New(); + filter->SetGradientImage( dwi->GetDirections(), dwi->GetVectorImage() ); + filter->SetBValue(dwi->GetB_Value()); + filter->SetThreshold( threshold ); + filter->SetLambda(lambda); + if (normalization==0) + filter->SetNormalizationMethod(FilterType::QBAR_STANDARD); + else + filter->SetNormalizationMethod(FilterType::QBAR_SOLID_ANGLE); + filter->Update(); + image->InitializeByItk( filter->GetOutput() ); + image->SetVolume( filter->GetOutput()->GetBufferPointer() ); + coeffsImage->InitializeByItk( filter->GetCoefficientImage().GetPointer() ); + coeffsImage->SetVolume( filter->GetCoefficientImage()->GetBufferPointer() ); + break; + } + case 8: + { + typedef itk::AnalyticalDiffusionQballReconstructionImageFilter FilterType; + FilterType::Pointer filter = FilterType::New(); + filter->SetGradientImage( dwi->GetDirections(), dwi->GetVectorImage() ); + filter->SetBValue(dwi->GetB_Value()); + filter->SetThreshold( threshold ); + filter->SetLambda(lambda); + if (normalization==0) + filter->SetNormalizationMethod(FilterType::QBAR_STANDARD); + else + filter->SetNormalizationMethod(FilterType::QBAR_SOLID_ANGLE); + filter->Update(); + image->InitializeByItk( filter->GetOutput() ); + image->SetVolume( filter->GetOutput()->GetBufferPointer() ); + coeffsImage->InitializeByItk( filter->GetCoefficientImage().GetPointer() ); + coeffsImage->SetVolume( filter->GetCoefficientImage()->GetBufferPointer() ); + break; + } + case 10: + { + typedef itk::AnalyticalDiffusionQballReconstructionImageFilter FilterType; + FilterType::Pointer filter = FilterType::New(); + filter->SetGradientImage( dwi->GetDirections(), dwi->GetVectorImage() ); + filter->SetBValue(dwi->GetB_Value()); + filter->SetThreshold( threshold ); + filter->SetLambda(lambda); + if (normalization==0) + filter->SetNormalizationMethod(FilterType::QBAR_STANDARD); + else + filter->SetNormalizationMethod(FilterType::QBAR_SOLID_ANGLE); + filter->Update(); + image->InitializeByItk( filter->GetOutput() ); + image->SetVolume( filter->GetOutput()->GetBufferPointer() ); + coeffsImage->InitializeByItk( filter->GetCoefficientImage().GetPointer() ); + coeffsImage->SetVolume( filter->GetCoefficientImage()->GetBufferPointer() ); + break; + } + default: + { + MITK_INFO << "Supplied SH order not supported. Using default order of 4."; + typedef itk::AnalyticalDiffusionQballReconstructionImageFilter FilterType; + FilterType::Pointer filter = FilterType::New(); + filter->SetGradientImage( dwi->GetDirections(), dwi->GetVectorImage() ); + filter->SetBValue(dwi->GetB_Value()); + filter->SetThreshold( threshold ); + filter->SetLambda(lambda); + if (normalization==0) + filter->SetNormalizationMethod(FilterType::QBAR_STANDARD); + else + filter->SetNormalizationMethod(FilterType::QBAR_SOLID_ANGLE); + filter->Update(); + image->InitializeByItk( filter->GetOutput() ); + image->SetVolume( filter->GetOutput()->GetBufferPointer() ); + coeffsImage->InitializeByItk( filter->GetCoefficientImage().GetPointer() ); + coeffsImage->SetVolume( filter->GetCoefficientImage()->GetBufferPointer() ); + } + } + + std::string coeffout = outfilename; + coeffout += "_shcoeffs.nrrd"; + + outfilename += ".qbi"; + MITK_INFO << "writing image " << outfilename; + mitk::NrrdQBallImageWriter::Pointer writer = mitk::NrrdQBallImageWriter::New(); + writer->SetInput(image.GetPointer()); + writer->SetFileName(outfilename.c_str()); + writer->Update(); + + if (outCoeffs) + mitk::IOUtil::SaveImage(coeffsImage, coeffout); + } + catch ( itk::ExceptionObject &err) + { + MITK_INFO << "Exception: " << err; + } + catch ( std::exception err) + { + MITK_INFO << "Exception: " << err.what(); + } + catch ( ... ) + { + MITK_INFO << "Exception!"; + } + return EXIT_SUCCESS; +} +RegisterDiffusionMiniApp(QballReconstruction); diff --git a/Modules/DiffusionImaging/FiberTracking/MiniApps/StreamlineTracking.cpp b/Modules/DiffusionImaging/MiniApps/StreamlineTracking.cpp similarity index 99% rename from Modules/DiffusionImaging/FiberTracking/MiniApps/StreamlineTracking.cpp rename to Modules/DiffusionImaging/MiniApps/StreamlineTracking.cpp index adb943a9c7..376205940d 100755 --- a/Modules/DiffusionImaging/FiberTracking/MiniApps/StreamlineTracking.cpp +++ b/Modules/DiffusionImaging/MiniApps/StreamlineTracking.cpp @@ -1,174 +1,174 @@ /*=================================================================== 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 "MiniAppManager.h" #include #include #include #include #include #include #include #include #include #include "ctkCommandLineParser.h" int StreamlineTracking(int argc, char* argv[]) { ctkCommandLineParser parser; parser.setArgumentPrefix("--", "-"); parser.addArgument("input", "i", ctkCommandLineParser::String, "input tensor image (.dti)", us::Any(), false); parser.addArgument("seed", "si", ctkCommandLineParser::String, "binary seed image"); parser.addArgument("mask", "mi", ctkCommandLineParser::String, "binary mask image"); parser.addArgument("minFA", "fa", ctkCommandLineParser::Float, "minimum fractional anisotropy threshold", 0.15, true); parser.addArgument("minCurv", "c", ctkCommandLineParser::Float, "minimum curvature radius in mm (default = 0.5*minimum-spacing)"); parser.addArgument("stepSize", "s", ctkCommandLineParser::Float, "stepsize in mm (default = 0.1*minimum-spacing)"); parser.addArgument("tendf", "f", ctkCommandLineParser::Float, "Weighting factor between first eigenvector (f=1 equals FACT tracking) and input vector dependent direction (f=0).", 1.0, true); parser.addArgument("tendg", "g", ctkCommandLineParser::Float, "Weighting factor between input vector (g=0) and tensor deflection (g=1 equals TEND tracking)", 0.0, true); parser.addArgument("numSeeds", "n", ctkCommandLineParser::Int, "Number of seeds per voxel.", 1, true); parser.addArgument("minLength", "l", ctkCommandLineParser::Float, "minimum fiber length in mm", 20, true); parser.addArgument("interpolate", "ip", ctkCommandLineParser::Bool, "Use linear interpolation", false, true); parser.addArgument("outFile", "o", ctkCommandLineParser::String, "output fiber bundle (.fib)", us::Any(), false); map parsedArgs = parser.parseArguments(argc, argv); if (parsedArgs.size()==0) return EXIT_FAILURE; string dtiFileName = us::any_cast(parsedArgs["input"]); string outFileName = us::any_cast(parsedArgs["outFile"]); float minFA = 0.15; float minCurv = -1; float stepSize = -1; float tendf = 1; float tendg = 0; float minLength = 20; int numSeeds = 1; bool interpolate = false; if (parsedArgs.count("minCurv")) minCurv = us::any_cast(parsedArgs["minCurv"]); if (parsedArgs.count("minFA")) minFA = us::any_cast(parsedArgs["minFA"]); if (parsedArgs.count("stepSize")) stepSize = us::any_cast(parsedArgs["stepSize"]); if (parsedArgs.count("tendf")) tendf = us::any_cast(parsedArgs["tendf"]); if (parsedArgs.count("tendg")) tendg = us::any_cast(parsedArgs["tendg"]); if (parsedArgs.count("minLength")) minLength = us::any_cast(parsedArgs["minLength"]); if (parsedArgs.count("numSeeds")) numSeeds = us::any_cast(parsedArgs["numSeeds"]); if (parsedArgs.count("interpolate")) interpolate = us::any_cast(parsedArgs["interpolate"]); try { RegisterDiffusionCoreObjectFactory(); RegisterFiberTrackingObjectFactory(); // load input image const std::string s1="", s2=""; std::vector infile = mitk::BaseDataIO::LoadBaseDataFromFile( dtiFileName, s1, s2, false ); MITK_INFO << "Loading tensor image ..."; typedef itk::Image< itk::DiffusionTensor3D, 3 > ItkTensorImage; mitk::TensorImage::Pointer mitkTensorImage = dynamic_cast(infile.at(0).GetPointer()); ItkTensorImage::Pointer itk_dti = ItkTensorImage::New(); mitk::CastToItkImage(mitkTensorImage, itk_dti); MITK_INFO << "Loading seed image ..."; typedef itk::Image< unsigned char, 3 > ItkUCharImageType; mitk::Image::Pointer mitkSeedImage = NULL; if (parsedArgs.count("seed")) mitkSeedImage = mitk::IOUtil::LoadImage(us::any_cast(parsedArgs["seed"])); MITK_INFO << "Loading mask image ..."; mitk::Image::Pointer mitkMaskImage = NULL; if (parsedArgs.count("mask")) mitkMaskImage = mitk::IOUtil::LoadImage(us::any_cast(parsedArgs["mask"])); // instantiate tracker typedef itk::StreamlineTrackingFilter< float > FilterType; FilterType::Pointer filter = FilterType::New(); filter->SetInput(itk_dti); filter->SetSeedsPerVoxel(numSeeds); filter->SetFaThreshold(minFA); filter->SetMinCurvatureRadius(minCurv); filter->SetStepSize(stepSize); filter->SetF(tendf); filter->SetG(tendg); filter->SetInterpolate(interpolate); filter->SetMinTractLength(minLength); if (mitkSeedImage.IsNotNull()) { ItkUCharImageType::Pointer mask = ItkUCharImageType::New(); mitk::CastToItkImage(mitkSeedImage, mask); filter->SetSeedImage(mask); } if (mitkMaskImage.IsNotNull()) { ItkUCharImageType::Pointer mask = ItkUCharImageType::New(); mitk::CastToItkImage(mitkMaskImage, mask); filter->SetMaskImage(mask); } filter->Update(); vtkSmartPointer fiberBundle = filter->GetFiberPolyData(); if ( fiberBundle->GetNumberOfLines()==0 ) { MITK_INFO << "No fibers reconstructed. Check parametrization."; return EXIT_FAILURE; } mitk::FiberBundleX::Pointer fib = mitk::FiberBundleX::New(fiberBundle); mitk::CoreObjectFactory::FileWriterList fileWriters = mitk::CoreObjectFactory::GetInstance()->GetFileWriters(); for (mitk::CoreObjectFactory::FileWriterList::iterator it = fileWriters.begin() ; it != fileWriters.end() ; ++it) { if ( (*it)->CanWriteBaseDataType(fib.GetPointer()) ) { (*it)->SetFileName( outFileName.c_str() ); (*it)->DoWrite( fib.GetPointer() ); } } } catch (itk::ExceptionObject e) { MITK_INFO << e; return EXIT_FAILURE; } catch (std::exception e) { MITK_INFO << e.what(); return EXIT_FAILURE; } catch (...) { MITK_INFO << "ERROR!?!"; return EXIT_FAILURE; } MITK_INFO << "DONE"; return EXIT_SUCCESS; } -RegisterFiberTrackingMiniApp(StreamlineTracking); +RegisterDiffusionMiniApp(StreamlineTracking); diff --git a/Modules/DiffusionImaging/DiffusionCore/MiniApps/TensorReconstruction.cpp b/Modules/DiffusionImaging/MiniApps/TensorReconstruction.cpp similarity index 68% rename from Modules/DiffusionImaging/DiffusionCore/MiniApps/TensorReconstruction.cpp rename to Modules/DiffusionImaging/MiniApps/TensorReconstruction.cpp index 1f9eea61a3..ac7701e4db 100644 --- a/Modules/DiffusionImaging/DiffusionCore/MiniApps/TensorReconstruction.cpp +++ b/Modules/DiffusionImaging/MiniApps/TensorReconstruction.cpp @@ -1,89 +1,100 @@ /*=================================================================== 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 "MiniAppManager.h" #include "mitkBaseDataIOFactory.h" #include "mitkDiffusionImage.h" #include "mitkBaseData.h" #include "mitkDiffusionCoreObjectFactory.h" #include #include #include #include +#include "ctkCommandLineParser.h" +#include using namespace mitk; /** * Convert files from one ending to the other */ int TensorReconstruction(int argc, char* argv[]) { - if ( argc!=4 ) - { - std::cout << std::endl; - std::cout << "Perform Tensor estimation on an dwi file" << std::endl; - std::cout << std::endl; - std::cout << "usage: " << argv[0] << " " << argv[1] << " " << std::endl; - std::cout << std::endl; + ctkCommandLineParser parser; + parser.setArgumentPrefix("--", "-"); + parser.addArgument("input", "i", ctkCommandLineParser::String, "input raw dwi (.dwi or .fsl/.fslgz)", us::Any(), false); + parser.addArgument("outFile", "o", ctkCommandLineParser::String, "output file", us::Any(), false); + parser.addArgument("b0Threshold", "t", ctkCommandLineParser::Int, "baseline image intensity threshold", 0, true); + + map parsedArgs = parser.parseArguments(argc, argv); + if (parsedArgs.size()==0) return EXIT_FAILURE; - } + + std::string inFileName = us::any_cast(parsedArgs["input"]); + std::string outfilename = us::any_cast(parsedArgs["outFile"]); + outfilename = itksys::SystemTools::GetFilenameWithoutExtension(outfilename); + outfilename += ".dti"; + + int threshold = 0; + if (parsedArgs.count("b0Threshold")) + threshold = us::any_cast(parsedArgs["b0Threshold"]); try { RegisterDiffusionCoreObjectFactory(); MITK_INFO << "Loading image ..."; const std::string s1="", s2=""; - std::vector infile = BaseDataIO::LoadBaseDataFromFile( argv[2], s1, s2, false ); + std::vector infile = BaseDataIO::LoadBaseDataFromFile( inFileName, s1, s2, false ); DiffusionImage::Pointer dwi = dynamic_cast*>(infile.at(0).GetPointer()); - std::string outfilename = argv[3]; - + MITK_INFO << "B0 threshold: " << threshold; typedef itk::DiffusionTensor3DReconstructionImageFilter< short, short, float > TensorReconstructionImageFilterType; TensorReconstructionImageFilterType::Pointer filter = TensorReconstructionImageFilterType::New(); filter->SetGradientImage( dwi->GetDirections(), dwi->GetVectorImage() ); filter->SetBValue(dwi->GetB_Value()); + filter->SetThreshold(threshold); filter->Update(); // Save tensor image MITK_INFO << "writing image " << outfilename; itk::NrrdImageIO::Pointer io = itk::NrrdImageIO::New(); io->SetFileType( itk::ImageIOBase::Binary ); io->UseCompressionOn(); itk::ImageFileWriter< itk::Image< itk::DiffusionTensor3D< float >, 3 > >::Pointer writer = itk::ImageFileWriter< itk::Image< itk::DiffusionTensor3D< float >, 3 > >::New(); writer->SetInput(filter->GetOutput()); writer->SetFileName(outfilename); writer->SetImageIO(io); writer->UseCompressionOn(); writer->Update(); } catch ( itk::ExceptionObject &err) { MITK_INFO << "Exception: " << err; } catch ( std::exception err) { MITK_INFO << "Exception: " << err.what(); } catch ( ... ) { MITK_INFO << "Exception!"; } return EXIT_SUCCESS; } -RegisterDiffusionCoreMiniApp(TensorReconstruction); +RegisterDiffusionMiniApp(TensorReconstruction); diff --git a/Modules/DiffusionImaging/FiberTracking/MiniApps/TractogramAngularError.cpp b/Modules/DiffusionImaging/MiniApps/TractogramAngularError.cpp similarity index 99% rename from Modules/DiffusionImaging/FiberTracking/MiniApps/TractogramAngularError.cpp rename to Modules/DiffusionImaging/MiniApps/TractogramAngularError.cpp index 1f3c5c09d8..2b745330de 100755 --- a/Modules/DiffusionImaging/FiberTracking/MiniApps/TractogramAngularError.cpp +++ b/Modules/DiffusionImaging/MiniApps/TractogramAngularError.cpp @@ -1,205 +1,205 @@ /*=================================================================== 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 "MiniAppManager.h" #include #include #include #include #include #include #include #include "ctkCommandLineParser.h" #include #include #include #include #include #include #include #define _USE_MATH_DEFINES #include int TractogramAngularError(int argc, char* argv[]) { ctkCommandLineParser parser; parser.setArgumentPrefix("--", "-"); parser.addArgument("input", "i", ctkCommandLineParser::String, "input tractogram (.fib, vtk ascii file format)", us::Any(), false); parser.addArgument("reference", "r", ctkCommandLineParser::StringList, "reference direction images", us::Any(), false); parser.addArgument("out", "o", ctkCommandLineParser::String, "output root", us::Any(), false); parser.addArgument("mask", "m", ctkCommandLineParser::String, "mask image"); parser.addArgument("verbose", "v", ctkCommandLineParser::Bool, "output optional and intermediate calculation results"); parser.addArgument("ignore", "n", ctkCommandLineParser::Bool, "don't increase error for missing or too many directions"); parser.addArgument("trilinear", "t", ctkCommandLineParser::Bool, "use trilinear instead of nearest neighbor interpolation"); map parsedArgs = parser.parseArguments(argc, argv); if (parsedArgs.size()==0) return EXIT_FAILURE; ctkCommandLineParser::StringContainerType referenceImages = us::any_cast(parsedArgs["reference"]); string fibFile = us::any_cast(parsedArgs["input"]); string maskImage(""); if (parsedArgs.count("mask")) maskImage = us::any_cast(parsedArgs["mask"]); string outRoot = us::any_cast(parsedArgs["out"]); bool verbose = false; if (parsedArgs.count("verbose")) verbose = us::any_cast(parsedArgs["verbose"]); bool ignore = false; if (parsedArgs.count("ignore")) ignore = us::any_cast(parsedArgs["ignore"]); bool interpolate = false; if (parsedArgs.count("interpolate")) interpolate = us::any_cast(parsedArgs["interpolate"]); try { RegisterDiffusionCoreObjectFactory(); RegisterFiberTrackingObjectFactory(); typedef itk::Image ItkUcharImgType; typedef itk::Image< itk::Vector< float, 3>, 3 > ItkDirectionImage3DType; typedef itk::VectorContainer< int, ItkDirectionImage3DType::Pointer > ItkDirectionImageContainerType; typedef itk::EvaluateTractogramDirectionsFilter< float > EvaluationFilterType; // load fiber bundle mitk::FiberBundleX::Pointer inputTractogram = dynamic_cast(mitk::IOUtil::LoadDataNode(fibFile)->GetData()); if (!inputTractogram) return EXIT_FAILURE; // load reference directions ItkDirectionImageContainerType::Pointer referenceImageContainer = ItkDirectionImageContainerType::New(); for (int i=0; i(mitk::IOUtil::LoadDataNode(referenceImages.at(i))->GetData()); typedef mitk::ImageToItk< ItkDirectionImage3DType > CasterType; CasterType::Pointer caster = CasterType::New(); caster->SetInput(img); caster->Update(); ItkDirectionImage3DType::Pointer itkImg = caster->GetOutput(); referenceImageContainer->InsertElement(referenceImageContainer->Size(),itkImg); } catch(...){ MITK_INFO << "could not load: " << referenceImages.at(i); } } // load/create mask image ItkUcharImgType::Pointer itkMaskImage = ItkUcharImgType::New(); if (maskImage.compare("")==0) { ItkDirectionImage3DType::Pointer dirImg = referenceImageContainer->GetElement(0); itkMaskImage->SetSpacing( dirImg->GetSpacing() ); itkMaskImage->SetOrigin( dirImg->GetOrigin() ); itkMaskImage->SetDirection( dirImg->GetDirection() ); itkMaskImage->SetLargestPossibleRegion( dirImg->GetLargestPossibleRegion() ); itkMaskImage->SetBufferedRegion( dirImg->GetLargestPossibleRegion() ); itkMaskImage->SetRequestedRegion( dirImg->GetLargestPossibleRegion() ); itkMaskImage->Allocate(); itkMaskImage->FillBuffer(1); } else { mitk::Image::Pointer mitkMaskImage = dynamic_cast(mitk::IOUtil::LoadDataNode(maskImage)->GetData()); mitk::CastToItkImage(mitkMaskImage, itkMaskImage); } // evaluate directions EvaluationFilterType::Pointer evaluationFilter = EvaluationFilterType::New(); evaluationFilter->SetTractogram(inputTractogram); evaluationFilter->SetReferenceImageSet(referenceImageContainer); evaluationFilter->SetMaskImage(itkMaskImage); evaluationFilter->SetIgnoreMissingDirections(ignore); evaluationFilter->SetUseInterpolation(interpolate); evaluationFilter->Update(); if (verbose) { EvaluationFilterType::OutputImageType::Pointer angularErrorImage = evaluationFilter->GetOutput(0); typedef itk::ImageFileWriter< EvaluationFilterType::OutputImageType > WriterType; WriterType::Pointer writer = WriterType::New(); string outfilename = outRoot; outfilename.append("_ERROR_IMAGE.nrrd"); MITK_INFO << "writing " << outfilename; writer->SetFileName(outfilename.c_str()); writer->SetInput(angularErrorImage); writer->Update(); } string logFile = outRoot; logFile.append("_ANGULAR_ERROR.csv"); ofstream file; file.open (logFile.c_str()); string sens = "Mean:"; sens.append(","); sens.append(boost::lexical_cast(evaluationFilter->GetMeanAngularError())); sens.append(";\n"); sens.append("Median:"); sens.append(","); sens.append(boost::lexical_cast(evaluationFilter->GetMedianAngularError())); sens.append(";\n"); sens.append("Maximum:"); sens.append(","); sens.append(boost::lexical_cast(evaluationFilter->GetMaxAngularError())); sens.append(";\n"); sens.append("Minimum:"); sens.append(","); sens.append(boost::lexical_cast(evaluationFilter->GetMinAngularError())); sens.append(";\n"); sens.append("STDEV:"); sens.append(","); sens.append(boost::lexical_cast(std::sqrt(evaluationFilter->GetVarAngularError()))); sens.append(";\n"); file << sens; file.close(); MITK_INFO << "DONE"; } catch (itk::ExceptionObject e) { MITK_INFO << e; return EXIT_FAILURE; } catch (std::exception e) { MITK_INFO << e.what(); return EXIT_FAILURE; } catch (...) { MITK_INFO << "ERROR!?!"; return EXIT_FAILURE; } return EXIT_SUCCESS; } -RegisterFiberTrackingMiniApp(TractogramAngularError); +RegisterDiffusionMiniApp(TractogramAngularError); diff --git a/Modules/DiffusionImaging/FiberTracking/MiniApps/TractometerAngularErrorTool.cpp b/Modules/DiffusionImaging/MiniApps/TractometerAngularErrorTool.cpp similarity index 99% rename from Modules/DiffusionImaging/FiberTracking/MiniApps/TractometerAngularErrorTool.cpp rename to Modules/DiffusionImaging/MiniApps/TractometerAngularErrorTool.cpp index d236ed1a8c..294bb67ea9 100755 --- a/Modules/DiffusionImaging/FiberTracking/MiniApps/TractometerAngularErrorTool.cpp +++ b/Modules/DiffusionImaging/MiniApps/TractometerAngularErrorTool.cpp @@ -1,264 +1,263 @@ /*=================================================================== 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 "MiniAppManager.h" #include #include #include #include #include #include #include #include #include "ctkCommandLineParser.h" -#include "ctkCommandLineParser.cpp" #include #include #include #include #include #include #include #define _USE_MATH_DEFINES #include int TractometerAngularErrorTool(int argc, char* argv[]) { ctkCommandLineParser parser; parser.setArgumentPrefix("--", "-"); parser.addArgument("input", "i", ctkCommandLineParser::String, "input tractogram (.fib, vtk ascii file format)", us::Any(), false); parser.addArgument("reference", "r", ctkCommandLineParser::StringList, "reference direction images", us::Any(), false); parser.addArgument("out", "o", ctkCommandLineParser::String, "output root", us::Any(), false); parser.addArgument("mask", "m", ctkCommandLineParser::String, "mask image"); parser.addArgument("athresh", "a", ctkCommandLineParser::Float, "angular threshold in degrees. closer fiber directions are regarded as one direction and clustered together.", 25, true); parser.addArgument("verbose", "v", ctkCommandLineParser::Bool, "output optional and intermediate calculation results"); parser.addArgument("ignore", "n", ctkCommandLineParser::Bool, "don't increase error for missing or too many directions"); map parsedArgs = parser.parseArguments(argc, argv); if (parsedArgs.size()==0) return EXIT_FAILURE; ctkCommandLineParser::StringContainerType referenceImages = us::any_cast(parsedArgs["reference"]); string fibFile = us::any_cast(parsedArgs["input"]); string maskImage(""); if (parsedArgs.count("mask")) maskImage = us::any_cast(parsedArgs["mask"]); float angularThreshold = 25; if (parsedArgs.count("athresh")) angularThreshold = us::any_cast(parsedArgs["athresh"]); string outRoot = us::any_cast(parsedArgs["out"]); bool verbose = false; if (parsedArgs.count("verbose")) verbose = us::any_cast(parsedArgs["verbose"]); bool ignore = false; if (parsedArgs.count("ignore")) ignore = us::any_cast(parsedArgs["ignore"]); try { RegisterDiffusionCoreObjectFactory(); RegisterFiberTrackingObjectFactory(); typedef itk::Image ItkUcharImgType; typedef itk::Image< itk::Vector< float, 3>, 3 > ItkDirectionImage3DType; typedef itk::VectorContainer< int, ItkDirectionImage3DType::Pointer > ItkDirectionImageContainerType; typedef itk::EvaluateDirectionImagesFilter< float > EvaluationFilterType; // load fiber bundle mitk::FiberBundleX::Pointer inputTractogram = dynamic_cast(mitk::IOUtil::LoadDataNode(fibFile)->GetData()); // load reference directions ItkDirectionImageContainerType::Pointer referenceImageContainer = ItkDirectionImageContainerType::New(); for (int i=0; i(mitk::IOUtil::LoadDataNode(referenceImages.at(i))->GetData()); typedef mitk::ImageToItk< ItkDirectionImage3DType > CasterType; CasterType::Pointer caster = CasterType::New(); caster->SetInput(img); caster->Update(); ItkDirectionImage3DType::Pointer itkImg = caster->GetOutput(); referenceImageContainer->InsertElement(referenceImageContainer->Size(),itkImg); } catch(...){ MITK_INFO << "could not load: " << referenceImages.at(i); } } // load/create mask image ItkUcharImgType::Pointer itkMaskImage = ItkUcharImgType::New(); if (maskImage.compare("")==0) { ItkDirectionImage3DType::Pointer dirImg = referenceImageContainer->GetElement(0); itkMaskImage->SetSpacing( dirImg->GetSpacing() ); itkMaskImage->SetOrigin( dirImg->GetOrigin() ); itkMaskImage->SetDirection( dirImg->GetDirection() ); itkMaskImage->SetLargestPossibleRegion( dirImg->GetLargestPossibleRegion() ); itkMaskImage->SetBufferedRegion( dirImg->GetLargestPossibleRegion() ); itkMaskImage->SetRequestedRegion( dirImg->GetLargestPossibleRegion() ); itkMaskImage->Allocate(); itkMaskImage->FillBuffer(1); } else { mitk::Image::Pointer mitkMaskImage = dynamic_cast(mitk::IOUtil::LoadDataNode(maskImage)->GetData()); mitk::CastToItkImage(mitkMaskImage, itkMaskImage); } // extract directions from fiber bundle itk::TractsToVectorImageFilter::Pointer fOdfFilter = itk::TractsToVectorImageFilter::New(); fOdfFilter->SetFiberBundle(inputTractogram); fOdfFilter->SetMaskImage(itkMaskImage); fOdfFilter->SetAngularThreshold(cos(angularThreshold*M_PI/180)); fOdfFilter->SetNormalizeVectors(true); fOdfFilter->SetUseWorkingCopy(false); fOdfFilter->Update(); ItkDirectionImageContainerType::Pointer directionImageContainer = fOdfFilter->GetDirectionImageContainer(); if (verbose) { // write vector field mitk::FiberBundleX::Pointer directions = fOdfFilter->GetOutputFiberBundle(); mitk::CoreObjectFactory::FileWriterList fileWriters = mitk::CoreObjectFactory::GetInstance()->GetFileWriters(); for (mitk::CoreObjectFactory::FileWriterList::iterator it = fileWriters.begin() ; it != fileWriters.end() ; ++it) { if ( (*it)->CanWriteBaseDataType(directions.GetPointer()) ) { string outfilename = outRoot; outfilename.append("_VECTOR_FIELD.fib"); (*it)->SetFileName( outfilename.c_str() ); (*it)->DoWrite( directions.GetPointer() ); } } // write direction images for (int i=0; iSize(); i++) { itk::TractsToVectorImageFilter::ItkDirectionImageType::Pointer itkImg = directionImageContainer->GetElement(i); typedef itk::ImageFileWriter< itk::TractsToVectorImageFilter::ItkDirectionImageType > WriterType; WriterType::Pointer writer = WriterType::New(); string outfilename = outRoot; outfilename.append("_DIRECTION_"); outfilename.append(boost::lexical_cast(i)); outfilename.append(".nrrd"); MITK_INFO << "writing " << outfilename; writer->SetFileName(outfilename.c_str()); writer->SetInput(itkImg); writer->Update(); } // write num direction image { ItkUcharImgType::Pointer numDirImage = fOdfFilter->GetNumDirectionsImage(); typedef itk::ImageFileWriter< ItkUcharImgType > WriterType; WriterType::Pointer writer = WriterType::New(); string outfilename = outRoot; outfilename.append("_NUM_DIRECTIONS.nrrd"); MITK_INFO << "writing " << outfilename; writer->SetFileName(outfilename.c_str()); writer->SetInput(numDirImage); writer->Update(); } } // evaluate directions EvaluationFilterType::Pointer evaluationFilter = EvaluationFilterType::New(); evaluationFilter->SetImageSet(directionImageContainer); evaluationFilter->SetReferenceImageSet(referenceImageContainer); evaluationFilter->SetMaskImage(itkMaskImage); evaluationFilter->SetIgnoreMissingDirections(ignore); evaluationFilter->Update(); if (verbose) { EvaluationFilterType::OutputImageType::Pointer angularErrorImage = evaluationFilter->GetOutput(0); typedef itk::ImageFileWriter< EvaluationFilterType::OutputImageType > WriterType; WriterType::Pointer writer = WriterType::New(); string outfilename = outRoot; outfilename.append("_ERROR_IMAGE.nrrd"); MITK_INFO << "writing " << outfilename; writer->SetFileName(outfilename.c_str()); writer->SetInput(angularErrorImage); writer->Update(); } string logFile = outRoot; logFile.append("_ANGULAR_ERROR.csv"); ofstream file; file.open (logFile.c_str()); string sens = "Mean:"; sens.append(","); sens.append(boost::lexical_cast(evaluationFilter->GetMeanAngularError())); sens.append(";\n"); sens.append("Median:"); sens.append(","); sens.append(boost::lexical_cast(evaluationFilter->GetMedianAngularError())); sens.append(";\n"); sens.append("Maximum:"); sens.append(","); sens.append(boost::lexical_cast(evaluationFilter->GetMaxAngularError())); sens.append(";\n"); sens.append("Minimum:"); sens.append(","); sens.append(boost::lexical_cast(evaluationFilter->GetMinAngularError())); sens.append(";\n"); sens.append("STDEV:"); sens.append(","); sens.append(boost::lexical_cast(std::sqrt(evaluationFilter->GetVarAngularError()))); sens.append(";\n"); file << sens; file.close(); MITK_INFO << "DONE"; } catch (itk::ExceptionObject e) { MITK_INFO << e; return EXIT_FAILURE; } catch (std::exception e) { MITK_INFO << e.what(); return EXIT_FAILURE; } catch (...) { MITK_INFO << "ERROR!?!"; return EXIT_FAILURE; } return EXIT_SUCCESS; } -RegisterFiberTrackingMiniApp(TractometerAngularErrorTool); +RegisterDiffusionMiniApp(TractometerAngularErrorTool); diff --git a/Modules/DiffusionImaging/DiffusionCore/MiniApps/ctkCommandLineParser.cpp b/Modules/DiffusionImaging/MiniApps/ctkCommandLineParser.cpp similarity index 100% rename from Modules/DiffusionImaging/DiffusionCore/MiniApps/ctkCommandLineParser.cpp rename to Modules/DiffusionImaging/MiniApps/ctkCommandLineParser.cpp diff --git a/Modules/DiffusionImaging/DiffusionCore/MiniApps/ctkCommandLineParser.h b/Modules/DiffusionImaging/MiniApps/ctkCommandLineParser.h similarity index 100% rename from Modules/DiffusionImaging/DiffusionCore/MiniApps/ctkCommandLineParser.h rename to Modules/DiffusionImaging/MiniApps/ctkCommandLineParser.h diff --git a/Modules/DiffusionImaging/DiffusionCore/MiniApps/mitkDiffusionCoreMiniApps.cpp b/Modules/DiffusionImaging/MiniApps/mitkDiffusionMiniApps.cpp similarity index 100% rename from Modules/DiffusionImaging/DiffusionCore/MiniApps/mitkDiffusionCoreMiniApps.cpp rename to Modules/DiffusionImaging/MiniApps/mitkDiffusionMiniApps.cpp