diff --git a/CMake/BuildConfigurations/All.cmake b/CMake/BuildConfigurations/All.cmake index 3fb1ead7fb..a389d0a1a4 100644 --- a/CMake/BuildConfigurations/All.cmake +++ b/CMake/BuildConfigurations/All.cmake @@ -1,73 +1,70 @@ set(MITK_CONFIG_PACKAGES ) set(_apple_package_excludes) set(_python_excludes ) if(NOT (CMAKE_SIZEOF_VOID_P EQUAL 8) ) set(_python_excludes Python Numpy ) endif() set(_package_excludes ${_apple_package_excludes} ${_python_excludes} - Gflags - Caffe - Caffe2 OpenCL SYSTEM_Boost Boost_LIBRARIES SYSTEM_PYTHON SUPERBUILD BiophotonicsHardware_SpectroCam POLHEMUS_TRACKER US_DiPhAS_SDK GALIL_HARDWARE OPHIR_PRYO_HARDWARE KWSTYLE MICROBIRD_TRACKER MICROBIRD_TRACKER_INCLUDE_DIR MICROBIRD_TRACKER_LIB MICRON_TRACKER OPTITRACK_TRACKER SPACENAVIGATOR TOF_KINECT TOF_KINECTV2 TOF_MESASR4000 TOF_PMDCAMBOARD TOF_PMDCAMCUBE TOF_PMDO3 US_TELEMED_SDK videoInput WIIMOTE ) get_cmake_property(_cache_vars CACHE_VARIABLES) foreach(_cache_var ${_cache_vars}) string(REGEX REPLACE "MITK_USE_(.+)" "\\1" _package "${_cache_var}") if(_package AND NOT _package STREQUAL _cache_var) list(FIND _package_excludes ${_package} _index) if(_index EQUAL -1) list(APPEND MITK_CONFIG_PACKAGES ${_package}) endif() endif() endforeach() set(MITK_BUILD_ALL_APPS ON CACHE BOOL "Build all MITK applications" FORCE) set(MITK_BUILD_ALL_PLUGINS ON CACHE BOOL "Build all MITK plugins" FORCE) set(MITK_BUILD_EXAMPLES ON CACHE BOOL "Build the MITK examples" FORCE) set(BLUEBERRY_BUILD_ALL_PLUGINS ON CACHE BOOL "Build all BlueBerry plugins" FORCE) set(BUILD_DiffusionCoreCmdApps ON CACHE BOOL "Build commandline tools for diffusion" FORCE) set(BUILD_DiffusionFiberProcessingCmdApps ON CACHE BOOL "Build commandline tools for diffusion fiber processing" FORCE) set(BUILD_DiffusionFiberfoxCmdApps ON CACHE BOOL "Build commandline tools for diffusion data simulation (Fiberfox)" FORCE) set(BUILD_DiffusionMiscCmdApps ON CACHE BOOL "Build miscellaneous commandline tools for diffusion" FORCE) set(BUILD_DiffusionQuantificationCmdApps ON CACHE BOOL "Build commandline tools for diffusion quantification (IVIM, ADC, ...)" FORCE) set(BUILD_DiffusionTractographyCmdApps ON CACHE BOOL "Build commandline tools for diffusion fiber tractography" FORCE) set(BUILD_DiffusionTractographyEvaluationCmdApps ON CACHE BOOL "Build commandline tools for diffusion fiber tractography evaluation" FORCE) set(BUILD_DiffusionConnectomicsCmdApps ON CACHE BOOL "Build commandline tools for diffusion connectomics" FORCE) diff --git a/CMake/FindCaffe2.cmake b/CMake/FindCaffe2.cmake deleted file mode 100644 index bfe21dae44..0000000000 --- a/CMake/FindCaffe2.cmake +++ /dev/null @@ -1,90 +0,0 @@ - -set(Caffe2_DIR ${MITK_EXTERNAL_PROJECT_PREFIX}) -set(Caffe2_INCLUDE_DIR ${Caffe2_DIR}/include) -set(Caffe2_CMAKE_DEBUG_POSTFIX d) -set(Caffe2_LIBRARIES) - -set(CUDA_DIR $ENV{CUDA_DIR}) -if (NOT CUDA_DIR) - find_path(CUDA_INSTALL_DIR cuda) - set(CUDA_DIR ${CUDA_INSTALL_DIR}/cuda) -endif() - -if (CUDA_DIR) - find_library (CUDART_LIB cudart PATHS ${CUDA_DIR}/lib64) - find_library (CUDNN_LIB cudnn PATHS ${CUDA_DIR}/lib64) - find_library (CUBLAS_LIB cublas PATHS ${CUDA_DIR}/lib64) - find_library (CURAND_LIB curand PATHS ${CUDA_DIR}/lib64) - find_library (CUDA_LIB cuda) -endif() -find_library (PROTOBUF_LIB protobuf) - -set(NCCL_LIB_DIR ${Caffe2_DIR}/src/Caffe2/third_party/nccl/build/lib/) - -FOREACH(POSTFIX _CPU;_GPU) - -# Find all libraries, store debug and release separately - # Find Release libraries - find_library(Caffe2_LIBRARY_RELEASE${POSTFIX} - Caffe2${POSTFIX} - PATHS - ${Caffe2_DIR}/lib - ${Caffe2_DIR}/lib/Release - ${Caffe2_DIR}/lib/RelWithDebInfo - ${Caffe2_DIR}/bin - ${Caffe2_DIR}/bin/Release - ${Caffe2_DIR}/bin/RelWithDebInfo - NO_DEFAULT_PATH - ) - - # Find Debug libraries - find_library(Caffe2_LIBRARY_DEBUG${POSTFIX} - Caffe2${POSTFIX}${Caffe2_CMAKE_DEBUG_POSTFIX} - PATHS - ${Caffe2_DIR}/lib - ${Caffe2_DIR}/lib/Debug - ${Caffe2_DIR}/bin - ${Caffe2_DIR}/bin/Debug - NO_DEFAULT_PATH - ) - - # Add libraries to variable according to build type - - if(Caffe2_LIBRARY_RELEASE${POSTFIX}) - list(APPEND Caffe2_LIBRARIES optimized ${Caffe2_LIBRARY_RELEASE${POSTFIX}}) - list(APPEND Caffe2_LIBRARIES optimized ${PROTOBUF_LIB}) - - if(${POSTFIX} MATCHES "_GPU") - find_library(NCCL_LIB_RELEASE nccl PATHS ${NCCL_LIB_DIR}) - list(APPEND Caffe2_LIBRARIES optimized ${NCCL_LIB_RELEASE}) - list(APPEND Caffe2_LIBRARIES optimized ${CUDART_LIB}) - list(APPEND Caffe2_LIBRARIES optimized ${CUDNN_LIB}) - list(APPEND Caffe2_LIBRARIES optimized ${CUBLAS_LIB}) - list(APPEND Caffe2_LIBRARIES optimized ${CURAND_LIB}) - list(APPEND Caffe2_LIBRARIES optimized ${CUDA_LIB}) - endif() - - endif() - - if(Caffe2_LIBRARY_DEBUG${POSTFIX}) - list(APPEND Caffe2_LIBRARIES debug ${Caffe2_LIBRARY_DEBUG${POSTFIX}}) - list(APPEND Caffe2_LIBRARIES debug ${PROTOBUF_LIB}) - - if(${POSTFIX} MATCHES "_GPU") - find_library(NCCL_LIB_DEBUG nccl PATHS ${NCCL_LIB_DIR}) - list(APPEND Caffe2_LIBRARIES debug ${NCCL_LIB_DEBUG}) - list(APPEND Caffe2_LIBRARIES debug ${CUDART_LIB}) - list(APPEND Caffe2_LIBRARIES debug ${CUDNN_LIB}) - list(APPEND Caffe2_LIBRARIES debug ${CUBLAS_LIB}) - list(APPEND Caffe2_LIBRARIES debug ${CURAND_LIB}) - list(APPEND Caffe2_LIBRARIES debug ${CUDA_LIB}) - endif() - - endif() - -ENDFOREACH() - -find_package_handle_standard_args(Caffe2 - FOUND_VAR Caffe2_FOUND - REQUIRED_VARS Caffe2_INCLUDE_DIR Caffe2_LIBRARIES PROTOBUF_LIB CUDA_DIR -) diff --git a/CMake/PackageDepends/MITK_Caffe2_Config.cmake b/CMake/PackageDepends/MITK_Caffe2_Config.cmake deleted file mode 100644 index c5b5b8c94c..0000000000 --- a/CMake/PackageDepends/MITK_Caffe2_Config.cmake +++ /dev/null @@ -1,4 +0,0 @@ -list(APPEND ALL_LIBRARIES ${Caffe2_LIBRARIES}) - -list(APPEND ALL_INCLUDE_DIRECTORIES ${CUDA_DIR}/include) -list(APPEND ALL_INCLUDE_DIRECTORIES ${Caffe2_INCLUDE_DIR}) diff --git a/CMake/PackageDepends/MITK_Caffe_Config.cmake b/CMake/PackageDepends/MITK_Caffe_Config.cmake deleted file mode 100644 index f95bba99b5..0000000000 --- a/CMake/PackageDepends/MITK_Caffe_Config.cmake +++ /dev/null @@ -1,4 +0,0 @@ -find_package(Caffe REQUIRED) - -list(APPEND ALL_LIBRARIES ${Caffe_LIBRARIES}) -list(APPEND ALL_INCLUDE_DIRECTORIES ${Caffe_INCLUDE_DIRS}) diff --git a/CMakeExternals/Caffe.cmake b/CMakeExternals/Caffe.cmake deleted file mode 100644 index fb10543cf3..0000000000 --- a/CMakeExternals/Caffe.cmake +++ /dev/null @@ -1,62 +0,0 @@ -#----------------------------------------------------------------------------- -# Caffe -#----------------------------------------------------------------------------- - -if(MITK_USE_Caffe) - - # Sanity checks - if(DEFINED Caffe_DIR AND NOT EXISTS ${Caffe_DIR}) - message(FATAL_ERROR "Caffe_DIR variable is defined but corresponds to non-existing directory") - endif() - - set(proj Caffe) - set(proj_DEPENDENCIES ) - set(Caffe_DEPENDS ${proj}) - - if(WIN32) - set(COPY_COMMAND copy) - else() - set(COPY_COMMAND cp) - endif() - - if(NOT DEFINED Caffe_DIR) - - find_path(Boost_INCLUDE_DIR boost) - find_library(Boost_LIBRARY boost_system) - get_filename_component(Boost_LIBRARY_DIR ${Boost_LIBRARY} DIRECTORY) - - if(${CMAKE_BUILD_TYPE} MATCHES "Debug") - find_library(GFLAGS_LIBRARY gflagsd PATHS ${ep_prefix}/lib NO_DEFAULT_PATH) - else() - find_library(GFLAGS_LIBRARY gflags PATHS ${ep_prefix}/lib NO_DEFAULT_PATH) - endif() - - #set(revision_tag 63cad96) - ExternalProject_Add(${proj} - GIT_REPOSITORY https://github.com/BVLC/caffe.git - #GIT_TAG ${revision_tag} - CMAKE_GENERATOR ${gen} - CMAKE_ARGS - ${ep_common_args} - ${additional_args} - -DUSE_OPENMP:BOOL=ON - -DBoost_INCLUDE_DIR:PATH=${Boost_INCLUDE_DIR} - -DBoost_LIBRARY_DIR_RELEASE:PATH=${Boost_LIBRARY_DIR} - -DBoost_LIBRARY_DIR_DEBUG:PATH=${Boost_LIBRARY_DIR} - -DGFLAGS_LIBRARY:FILEPATH=${GFLAGS_LIBRARY} - CMAKE_CACHE_ARGS - ${ep_common_cache_args} - CMAKE_CACHE_DEFAULT_ARGS - ${ep_common_cache_default_args} - DEPENDS ${proj_DEPENDENCIES} - ) - - set(Caffe_DIR ${ep_prefix}) - mitkFunctionInstallExternalCMakeProject(${proj}) - - else() - - mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}") - - endif() -endif(MITK_USE_Caffe) diff --git a/CMakeExternals/Caffe2.cmake b/CMakeExternals/Caffe2.cmake deleted file mode 100644 index 0cddc3c0f9..0000000000 --- a/CMakeExternals/Caffe2.cmake +++ /dev/null @@ -1,55 +0,0 @@ -#----------------------------------------------------------------------------- -# Caffe2 -#----------------------------------------------------------------------------- - -if(MITK_USE_Caffe2) - - # Sanity checks - if(DEFINED Caffe2_DIR AND NOT EXISTS ${Caffe2_DIR}) - message(FATAL_ERROR "Caffe2_DIR variable is defined but corresponds to non-existing directory") - endif() - - set(proj Caffe2) - set(proj_DEPENDENCIES ) - set(Caffe2_DEPENDS ${proj}) - - if(WIN32) - set(COPY_COMMAND copy) - else() - set(COPY_COMMAND cp) - endif() - - if(NOT DEFINED Caffe2_DIR) - - set(revision_tag 63cad96) - - ExternalProject_Add(${proj} - GIT_REPOSITORY https://github.com/caffe2/caffe2.git - #GIT_TAG ${revision_tag} - CMAKE_GENERATOR ${gen} - CMAKE_ARGS - ${ep_common_args} - ${additional_args} - -DBUILD_TEST:BOOL=OFF - -DBUILD_PYTHON:BOOL=OFF - -DBUILD_BINARY:BOOL=OFF - -DUSE_GFLAGS:BOOL=OFF - -DUSE_GLOG:BOOL=OFF - -DUSE_ROCKSDB:BOOL=OFF - -DUSE_NNPACK:BOOL=OFF - CMAKE_CACHE_ARGS - ${ep_common_cache_args} - CMAKE_CACHE_DEFAULT_ARGS - ${ep_common_cache_default_args} - DEPENDS ${proj_DEPENDENCIES} - ) - - set(Caffe2_DIR ${ep_prefix}) - mitkFunctionInstallExternalCMakeProject(${proj}) - - else() - - mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}") - - endif() -endif(MITK_USE_Caffe2) diff --git a/CMakeExternals/Gflags.cmake b/CMakeExternals/Gflags.cmake deleted file mode 100644 index 0222a3a27d..0000000000 --- a/CMakeExternals/Gflags.cmake +++ /dev/null @@ -1,47 +0,0 @@ -#----------------------------------------------------------------------------- -# Gflags -#----------------------------------------------------------------------------- - -if(MITK_USE_Gflags) - - # Sanity checks - if(DEFINED Gflags_DIR AND NOT EXISTS ${Gflags_DIR}) - message(FATAL_ERROR "Gflags_DIR variable is defined but corresponds to non-existing directory") - endif() - - set(proj Gflags) - set(proj_DEPENDENCIES ) - set(Gflags_DEPENDS ${proj}) - - if(WIN32) - set(COPY_COMMAND copy) - else() - set(COPY_COMMAND cp) - endif() - - if(NOT DEFINED Gflags_DIR) - - set(revision_tag v2.2.0) - ExternalProject_Add(${proj} - GIT_REPOSITORY https://github.com/gflags/gflags.git - GIT_TAG ${revision_tag} - CMAKE_GENERATOR ${gen} - CMAKE_ARGS - ${ep_common_args} - ${additional_args} - CMAKE_CACHE_ARGS - ${ep_common_cache_args} - CMAKE_CACHE_DEFAULT_ARGS - ${ep_common_cache_default_args} - DEPENDS ${proj_DEPENDENCIES} - ) - - set(Gflags_DIR ${ep_prefix}) - mitkFunctionInstallExternalCMakeProject(${proj}) - - else() - - mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}") - - endif() -endif(MITK_USE_Gflags) diff --git a/CMakeLists.txt b/CMakeLists.txt index 0d13b06d8e..6bd4b5d191 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,1356 +1,1350 @@ set(MITK_CMAKE_MINIMUM_REQUIRED_VERSION 3.5) cmake_minimum_required(VERSION ${MITK_CMAKE_MINIMUM_REQUIRED_VERSION}) #----------------------------------------------------------------------------- # See http://www.cmake.org/cmake/help/v3.5/manual/cmake-policies.7.html for details #----------------------------------------------------------------------------- set(project_policies ) foreach(policy ${project_policies}) if(POLICY ${policy}) cmake_policy(SET ${policy} NEW) endif() endforeach() #----------------------------------------------------------------------------- # Superbuild Option - Enabled by default #----------------------------------------------------------------------------- option(MITK_USE_SUPERBUILD "Build MITK and the projects it depends on via SuperBuild.cmake." ON) if(MITK_USE_SUPERBUILD) project(MITK-superbuild) set(MITK_SOURCE_DIR ${PROJECT_SOURCE_DIR}) set(MITK_BINARY_DIR ${PROJECT_BINARY_DIR}) else() project(MITK VERSION 2016.11.99) endif() #----------------------------------------------------------------------------- # Update CMake module path #------------------------------------------------------------------------------ set(MITK_CMAKE_DIR ${MITK_SOURCE_DIR}/CMake) set(CMAKE_MODULE_PATH ${MITK_CMAKE_DIR} ${CMAKE_MODULE_PATH} ) #----------------------------------------------------------------------------- # CMake function(s) and macro(s) #----------------------------------------------------------------------------- # Standard CMake macros include(FeatureSummary) include(CTestUseLaunchers) include(CMakeParseArguments) include(FindPackageHandleStandardArgs) # MITK macros include(mitkFunctionGetGccVersion) include(mitkFunctionCheckCompilerFlags) include(mitkFunctionSuppressWarnings) # includes several functions include(mitkMacroEmptyExternalProject) include(mitkFunctionGenerateProjectXml) include(mitkFunctionEnableBuildConfiguration) include(mitkFunctionWhitelists) include(mitkFunctionAddExternalProject) SUPPRESS_VC_DEPRECATED_WARNINGS() #----------------------------------------------------------------------------- # Set a default build type if none was specified #----------------------------------------------------------------------------- if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) message(STATUS "Setting build type to 'Debug' as none was specified.") set(CMAKE_BUILD_TYPE Debug CACHE STRING "Choose the type of build." FORCE) # Set the possible values of build type for cmake-gui set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release" "MinSizeRel" "RelWithDebInfo") endif() #----------------------------------------------------------------------------- # Check miminum Mac OS X version #----------------------------------------------------------------------------- # The minimum supported Mac OS X version is 10.9. If you use a version less than 10.9, there is no guarantee that the build still works. if(APPLE) exec_program(sw_vers ARGS -productVersion OUTPUT_VARIABLE osx_version) if (osx_version VERSION_LESS "10.9") message(WARNING "Detected OS X version \"${osx_version}\" is not supported anymore. Minimum required OS X version is 10.9 or greater.") endif() if (CMAKE_OSX_DEPLOYMENT_TARGET AND CMAKE_OSX_DEPLOYMENT_TARGET VERSION_LESS 10.9) message(WARNING "Detected OS X deployment target \"${CMAKE_OSX_DEPLOYMENT_TARGET}\" is not supported anymore. Minimum required OS X version is 10.9 or greater.") endif() endif() #----------------------------------------------------------------------------- # Check miminum compiler versions #----------------------------------------------------------------------------- if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") # require at least gcc 4.9 as provided by ppa:ubuntu-toolchain-r/test for Ubuntu 14.04 if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.9) message(FATAL_ERROR "GCC version must be at least 4.9 If you are using Ubuntu 14.04, you can easily install gcc and g++ 4.9 (or any later version available) in addition to your version ${CMAKE_CXX_COMPILER_VERSION}: sudo add-apt-repository ppa:ubuntu-toolchain-r/test sudo apt-get update sudo apt-get install gcc-4.9 g++-4.9 Make sure to explicitly specify these compilers when configuring MITK: CMAKE_C_COMPILER:FILEPATH=/usr/bin/gcc-4.9 CMAKE_CXX_COMPILER:FILEPATH=/usr/bin/g++-4.9 For more information on the proposed PPA see the Toolchain Updates section of https://wiki.ubuntu.com/ToolChain.") endif() elseif("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") # require at least clang 3.4 if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.4) message(FATAL_ERROR "Clang version must be at least 3.4") endif() elseif("${CMAKE_CXX_COMPILER_ID}" STREQUAL "AppleClang") # require at least clang 5.0 if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.0) message(FATAL_ERROR "Apple Clang version must be at least 5.0") endif() elseif("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") # require at least Visual Studio 2013 if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 18.0.40629.0) message(FATAL_ERROR "Microsoft Visual Studio 2013 Update 5 or newer required (MSVC 18.0.40629.0)") endif() else() message(WARNING "You are using an unsupported compiler! Compilation has only been tested with Clang (Linux or Apple), GCC and MSVC.") endif() if(CMAKE_COMPILER_IS_GNUCXX) mitkFunctionGetGccVersion(${CMAKE_CXX_COMPILER} GCC_VERSION) else() set(GCC_VERSION 0) endif() set(MITK_CXX_STANDARD 14) set(CMAKE_CXX_EXTENSIONS 0) set(CMAKE_CXX_STANDARD ${MITK_CXX_STANDARD}) set(CMAKE_CXX_STANDARD_REQUIRED 1) # This is necessary to avoid problems with compile feature checks. # CMAKE_CXX_STANDARD seems to only set the -std=c++14 flag for targets. # However, compile flag checks also need to be done with -std=c++14. # The MITK_CXX14_FLAG variable is also used for external projects # build during the MITK super-build. mitkFunctionCheckCompilerFlags("-std=c++14" MITK_CXX14_FLAG) #----------------------------------------------------------------------------- # Warn if source or build path is too long #----------------------------------------------------------------------------- if(WIN32) set(_src_dir_length_max 50) set(_bin_dir_length_max 50) if(MITK_USE_SUPERBUILD) set(_src_dir_length_max 34) # _src_dir_length_max - strlen(ep/src/ITK-build) set(_bin_dir_length_max 40) # _bin_dir_length_max - strlen(MITK-build) endif() string(LENGTH "${MITK_SOURCE_DIR}" _src_n) string(LENGTH "${MITK_BINARY_DIR}" _bin_n) # The warnings should be converted to errors if(_src_n GREATER _src_dir_length_max) message(WARNING "MITK source code directory path length is too long (${_src_n} > ${_src_dir_length_max})." "Please move the MITK source code directory to a directory with a shorter path." ) endif() if(_bin_n GREATER _bin_dir_length_max) message(WARNING "MITK build directory path length is too long (${_bin_n} > ${_bin_dir_length_max})." "Please move the MITK build directory to a directory with a shorter path." ) endif() endif() #----------------------------------------------------------------------------- # Additional MITK Options (also shown during superbuild) #----------------------------------------------------------------------------- macro(env_option name doc value) set(_value $ENV{${name}}) if("${_value}" STREQUAL "") set(_value ${value}) endif() option(${name} "${doc}" ${_value}) endmacro() # ----------------------------------------- # General build options option(BUILD_SHARED_LIBS "Build MITK with shared libraries" ON) option(WITH_COVERAGE "Enable/Disable coverage" OFF) option(BUILD_TESTING "Test the project" ON) env_option(MITK_BUILD_ALL_APPS "Build all MITK applications" OFF) env_option(MITK_BUILD_EXAMPLES "Build the MITK Examples" OFF) option(MITK_ENABLE_PIC_READER "Enable support for reading the DKFZ pic file format." ON) mark_as_advanced(MITK_BUILD_ALL_APPS MITK_ENABLE_PIC_READER ) # ----------------------------------------- # Qt version related variables env_option(MITK_USE_Qt5 "Use Qt 5 library" ON) env_option(MITK_USE_Qt5_WebEngine "Use Qt 5 WebEngine library" ON) if(MITK_USE_Qt5) set(MITK_QT5_MINIMUM_VERSION 5.6.0) set(MITK_QT5_COMPONENTS Concurrent OpenGL PrintSupport Script Sql Svg Widgets Xml XmlPatterns UiTools Help LinguistTools) if(MITK_USE_Qt5_WebEngine) set(MITK_QT5_COMPONENTS ${MITK_QT5_COMPONENTS} WebEngineWidgets) endif() if(APPLE) set(MITK_QT5_COMPONENTS ${MITK_QT5_COMPONENTS} DBus) endif() find_package(Qt5 ${MITK_QT5_MINIMUM_VERSION} COMPONENTS ${MITK_QT5_COMPONENTS} REQUIRED) if(Qt5_DIR) get_filename_component(_Qt5_DIR "${Qt5_DIR}/../../../" ABSOLUTE) list(FIND CMAKE_PREFIX_PATH "${_Qt5_DIR}" _result) if(_result LESS 0) set(CMAKE_PREFIX_PATH "${_Qt5_DIR};${CMAKE_PREFIX_PATH}" CACHE PATH "" FORCE) endif() endif() elseif(MITK_USE_Qt5_WebEngine) set(MITK_USE_Qt5_WebEngine OFF) endif() # ------------------------------------------------------------------------ # Register external projects which can be build with the MITK superbuild # system. Each mitkFunctionAddExternalProject() call registers an external # project for which a CMakeExternals/.cmake file must exist. The # call also creates a MITK_USE_ variable (appearing in the CMake # UI if the NO_CACHE option is *not* given). # ----------------------------------------- # Optional external projects with no # inter-dependencies set_property(GLOBAL PROPERTY MITK_EXTERNAL_PROJECTS "") mitkFunctionAddExternalProject(NAME Poco ON COMPONENTS Foundation Net Util XML Zip) mitkFunctionAddExternalProject(NAME DCMTK ON DOC "EXPERIMENTAL, superbuild only: Use DCMTK in MITK") mitkFunctionAddExternalProject(NAME OpenIGTLink OFF) mitkFunctionAddExternalProject(NAME tinyxml ON ADVANCED) mitkFunctionAddExternalProject(NAME GDCM ON ADVANCED) mitkFunctionAddExternalProject(NAME GLUT OFF ADVANCED) mitkFunctionAddExternalProject(NAME Raptor2 OFF ADVANCED) mitkFunctionAddExternalProject(NAME Eigen ON ADVANCED DOC "Use the Eigen library") mitkFunctionAddExternalProject(NAME ANN ON ADVANCED DOC "Use Approximate Nearest Neighbor Library") mitkFunctionAddExternalProject(NAME CppUnit ON ADVANCED DOC "Use CppUnit for unit tests") mitkFunctionAddExternalProject(NAME PCRE OFF ADVANCED NO_PACKAGE) mitkFunctionAddExternalProject(NAME ZLIB OFF ADVANCED NO_PACKAGE NO_CACHE) mitkFunctionAddExternalProject(NAME HDF5 ON ADVANCED) # ----------------------------------------- # The following external projects must be # ordered according to their # inter-dependencies mitkFunctionAddExternalProject(NAME SWIG OFF ADVANCED NO_PACKAGE DEPENDS PCRE) mitkFunctionAddExternalProject(NAME Python OFF NO_PACKAGE DEPENDS SWIG DOC "Use Python wrapping in MITK") mitkFunctionAddExternalProject(NAME Numpy OFF ADVANCED NO_PACKAGE) mitkFunctionAddExternalProject(NAME OpenCV OFF) mitkFunctionAddExternalProject(NAME Vigra OFF DEPENDS HDF5) # These are "hard" dependencies and always set to ON mitkFunctionAddExternalProject(NAME ITK ON NO_CACHE DEPENDS HDF5) mitkFunctionAddExternalProject(NAME VTK ON NO_CACHE) mitkFunctionAddExternalProject(NAME Boost ON NO_CACHE) mitkFunctionAddExternalProject(NAME SimpleITK OFF DEPENDS ITK GDCM SWIG) mitkFunctionAddExternalProject(NAME ACVD OFF DOC "Use Approximated Centroidal Voronoi Diagrams") mitkFunctionAddExternalProject(NAME CTK ON DEPENDS Qt5 DCMTK DOC "Use CTK in MITK") mitkFunctionAddExternalProject(NAME Rasqal OFF DEPENDS Raptor2 PCRE ADVANCED) mitkFunctionAddExternalProject(NAME Redland OFF DEPENDS Rasqal DOC "Use the Redland RDF library") mitkFunctionAddExternalProject(NAME DCMQI OFF DEPENDS DCMTK ITK DOC "Use dcmqi in MITK") mitkFunctionAddExternalProject(NAME MatchPoint OFF ADVANCED DEPENDS ITK DOC "Use the MatchPoint translation image registration library") if(MITK_USE_Qt5) mitkFunctionAddExternalProject(NAME Qwt ON ADVANCED DEPENDS Qt5) endif() -if(${CMAKE_SYSTEM_NAME} MATCHES "Linux") - mitkFunctionAddExternalProject(NAME Gflags OFF ADVANCED DOC "Experimental. Only available on Linux systems. Needed for Caffe.") - mitkFunctionAddExternalProject(NAME Caffe OFF ADVANCED DEPENDS HDF5 OpenCV Gflags DOC "Experimental. Only available on Linux systems.") - mitkFunctionAddExternalProject(NAME Caffe2 OFF ADVANCED DOC "Experimental. Only available on Linux systems.") -endif() - # ----------------------------------------- # Other MITK_USE_* options not related to # external projects build via the # MITK superbuild env_option(MITK_USE_BLUEBERRY "Build the BlueBerry platform" ON) env_option(MITK_USE_OpenCL "Use OpenCL GPU-Computing library" OFF) #----------------------------------------------------------------------------- # Build configurations #----------------------------------------------------------------------------- set(_buildConfigs "Custom") file(GLOB _buildConfigFiles CMake/BuildConfigurations/*.cmake) foreach(_buildConfigFile ${_buildConfigFiles}) get_filename_component(_buildConfigFile ${_buildConfigFile} NAME_WE) list(APPEND _buildConfigs ${_buildConfigFile}) endforeach() set(MITK_BUILD_CONFIGURATION "Custom" CACHE STRING "Use pre-defined MITK configurations") set_property(CACHE MITK_BUILD_CONFIGURATION PROPERTY STRINGS ${_buildConfigs}) mitkFunctionEnableBuildConfiguration() mitkFunctionCreateWhitelistPaths(MITK) mitkFunctionFindWhitelists(MITK) # ----------------------------------------- # Custom dependency logic option(MITK_USE_SYSTEM_Boost "Use the system Boost" OFF) set(MITK_USE_Boost_LIBRARIES "" CACHE STRING "A semi-colon separated list of required Boost libraries") # only windows can't build python in debug mode if(MITK_USE_Python AND "${CMAKE_BUILD_TYPE}" STREQUAL "Debug" AND WIN32) message(WARNING "Disabling Python support. Building MITK Python in debug mode on Windowsis not supported!") set(MITK_USE_Python OFF CACHE BOOL "Use python wrapping in MITK" FORCE) set(MITK_USE_Numpy OFF CACHE BOOL "Use Numpy" FORCE) set(MITK_USE_SimpleITK OFF CACHE BOOL "Use SimpleITK" FORCE) elseif(MITK_USE_Python) set(MITK_USE_ZLIB ON) if(NOT MITK_USE_Numpy) message("> Forcing MITK_USE_Numpy to ON because of MITK_USE_Python") set(MITK_USE_Numpy ON CACHE BOOL "Use Numpy" FORCE) endif() if(NOT MITK_USE_SimpleITK) message("> Forcing MITK_USE_SimpleITK to ON because of MITK_USE_Python") set(MITK_USE_SimpleITK ON CACHE BOOL "Use SimpleITK" FORCE) endif() option(MITK_USE_SYSTEM_PYTHON "Use the system python runtime" OFF) if(MITK_USE_SYSTEM_PYTHON) find_package(PythonLibs REQUIRED) find_package(PythonInterp REQUIRED) endif() elseif(MITK_USE_Python AND "${CMAKE_BUILD_TYPE}" STREQUAL "Debug" AND WIN32) message(WARNING "Disabling Python support. Building MITK Python in debug mode on Windowsis not supported!") set(MITK_USE_Python OFF CACHE BOOL "Use python wrapping in MITK" FORCE) endif() if(BUILD_TESTING AND NOT MITK_USE_CppUnit) message("> Forcing MITK_USE_CppUnit to ON because BUILD_TESTING=ON") set(MITK_USE_CppUnit ON CACHE BOOL "Use CppUnit for unit tests" FORCE) endif() if(MITK_USE_BLUEBERRY) option(MITK_BUILD_ALL_PLUGINS "Build all MITK plugins" OFF) mark_as_advanced(MITK_BUILD_ALL_PLUGINS) if(NOT MITK_USE_CTK) message("> Forcing MITK_USE_CTK to ON because of MITK_USE_BLUEBERRY") set(MITK_USE_CTK ON CACHE BOOL "Use CTK in MITK" FORCE) endif() endif() #----------------------------------------------------------------------------- # Pixel type multiplexing #----------------------------------------------------------------------------- # Customize the default pixel types for multiplex macros set(MITK_ACCESSBYITK_INTEGRAL_PIXEL_TYPES "int, unsigned int, short, unsigned short, char, unsigned char" CACHE STRING "List of integral pixel types used in AccessByItk and InstantiateAccessFunction macros") set(MITK_ACCESSBYITK_FLOATING_PIXEL_TYPES "double, float" CACHE STRING "List of floating pixel types used in AccessByItk and InstantiateAccessFunction macros") set(MITK_ACCESSBYITK_COMPOSITE_PIXEL_TYPES "itk::RGBPixel, itk::RGBAPixel" CACHE STRING "List of composite pixel types used in AccessByItk and InstantiateAccessFunction macros") set(MITK_ACCESSBYITK_DIMENSIONS "2,3" CACHE STRING "List of dimensions used in AccessByItk and InstantiateAccessFunction macros") mark_as_advanced(MITK_ACCESSBYITK_INTEGRAL_PIXEL_TYPES MITK_ACCESSBYITK_FLOATING_PIXEL_TYPES MITK_ACCESSBYITK_COMPOSITE_PIXEL_TYPES MITK_ACCESSBYITK_DIMENSIONS ) # consistency checks if(NOT MITK_ACCESSBYITK_INTEGRAL_PIXEL_TYPES) set(MITK_ACCESSBYITK_INTEGRAL_PIXEL_TYPES "int, unsigned int, short, unsigned short, char, unsigned char" CACHE STRING "List of integral pixel types used in AccessByItk and InstantiateAccessFunction macros" FORCE) endif() if(NOT MITK_ACCESSBYITK_FLOATING_PIXEL_TYPES) set(MITK_ACCESSBYITK_FLOATING_PIXEL_TYPES "double, float" CACHE STRING "List of floating pixel types used in AccessByItk and InstantiateAccessFunction macros" FORCE) endif() if(NOT MITK_ACCESSBYITK_COMPOSITE_PIXEL_TYPES) set(MITK_ACCESSBYITK_COMPOSITE_PIXEL_TYPES "itk::RGBPixel, itk::RGBAPixel" CACHE STRING "List of composite pixel types used in AccessByItk and InstantiateAccessFunction macros" FORCE) endif() if(NOT MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES) string(REPLACE "," ";" _integral_types ${MITK_ACCESSBYITK_INTEGRAL_PIXEL_TYPES}) string(REPLACE "," ";" _floating_types ${MITK_ACCESSBYITK_FLOATING_PIXEL_TYPES}) foreach(_scalar_type ${_integral_types} ${_floating_types}) set(MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES "${MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES}itk::VariableLengthVector<${_scalar_type}>,") endforeach() string(LENGTH "${MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES}" _length) math(EXPR _length "${_length} - 1") string(SUBSTRING "${MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES}" 0 ${_length} MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES) set(MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES ${MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES} CACHE STRING "List of vector pixel types used in AccessByItk and InstantiateAccessFunction macros for itk::VectorImage types" FORCE) endif() if(NOT MITK_ACCESSBYITK_DIMENSIONS) set(MITK_ACCESSBYITK_DIMENSIONS "2,3" CACHE STRING "List of dimensions used in AccessByItk and InstantiateAccessFunction macros") endif() #----------------------------------------------------------------------------- # Project.xml #----------------------------------------------------------------------------- # A list of topologically ordered targets set(CTEST_PROJECT_SUBPROJECTS) list(APPEND CTEST_PROJECT_SUBPROJECTS MITK-Core MITK-CoreUI MITK-IGT MITK-ToF MITK-DTI MITK-Modules # all modules not contained in a specific subproject MITK-Plugins # all plugins not contained in a specific subproject MITK-Examples Unlabeled # special "subproject" catching all unlabeled targets and tests ) # Configure CTestConfigSubProject.cmake that could be used by CTest scripts configure_file(${MITK_SOURCE_DIR}/CTestConfigSubProject.cmake.in ${MITK_BINARY_DIR}/CTestConfigSubProject.cmake) if(CTEST_PROJECT_ADDITIONAL_TARGETS) # those targets will be executed at the end of the ctest driver script # and they also get their own subproject label set(subproject_list "${CTEST_PROJECT_SUBPROJECTS};${CTEST_PROJECT_ADDITIONAL_TARGETS}") else() set(subproject_list "${CTEST_PROJECT_SUBPROJECTS}") endif() # Generate Project.xml file expected by the CTest driver script mitkFunctionGenerateProjectXml(${MITK_BINARY_DIR} MITK "${subproject_list}" ${MITK_USE_SUPERBUILD}) #----------------------------------------------------------------------------- # Superbuild script #----------------------------------------------------------------------------- if(MITK_USE_SUPERBUILD) include("${CMAKE_CURRENT_SOURCE_DIR}/SuperBuild.cmake") # Print configuration summary message("\n\n") feature_summary( DESCRIPTION "------- FEATURE SUMMARY FOR ${PROJECT_NAME} -------" WHAT ALL) return() endif() #***************************************************************************** #**************************** END OF SUPERBUILD **************************** #***************************************************************************** #----------------------------------------------------------------------------- # CMake function(s) and macro(s) #----------------------------------------------------------------------------- include(WriteBasicConfigVersionFile) include(CheckCXXSourceCompiles) include(GenerateExportHeader) include(mitkFunctionAddCustomModuleTest) include(mitkFunctionCheckModuleDependencies) include(mitkFunctionCompileSnippets) include(mitkFunctionConfigureVisualStudioUserProjectFile) include(mitkFunctionConvertXPSchema) include(mitkFunctionCreateBlueBerryApplication) include(mitkFunctionCreateCommandLineApp) include(mitkFunctionCreateModule) include(mitkFunctionCreatePlugin) include(mitkFunctionCreateProvisioningFile) include(mitkFunctionGetLibrarySearchPaths) include(mitkFunctionGetVersion) include(mitkFunctionGetVersionDescription) include(mitkFunctionInstallAutoLoadModules) include(mitkFunctionInstallCTKPlugin) include(mitkFunctionInstallProvisioningFiles) include(mitkFunctionInstallThirdPartyCTKPlugins) include(mitkFunctionOrganizeSources) include(mitkFunctionTestPlugin) include(mitkFunctionUseModules) if( ${MITK_USE_MatchPoint} ) include(mitkFunctionCreateMatchPointDeployedAlgorithm) endif() include(mitkMacroConfigureItkPixelTypes) include(mitkMacroCreateExecutable) include(mitkMacroCreateModuleTests) include(mitkMacroGenerateToolsLibrary) include(mitkMacroGetLinuxDistribution) include(mitkMacroGetPMDPlatformString) include(mitkMacroInstall) include(mitkMacroInstallHelperApp) include(mitkMacroInstallTargets) include(mitkMacroMultiplexPicType) # Deprecated include(mitkMacroCreateCTKPlugin) #----------------------------------------------------------------------------- # Global CMake variables #----------------------------------------------------------------------------- # Required and enabled C++14 features for all MITK code. # These are added as PUBLIC compile features to all MITK modules. set(MITK_CXX_FEATURES cxx_auto_type cxx_decltype cxx_enum_forward_declarations cxx_extended_friend_declarations cxx_extern_templates cxx_final cxx_lambdas cxx_local_type_template_args cxx_long_long_type cxx_nullptr cxx_override cxx_range_for cxx_right_angle_brackets cxx_rvalue_references cxx_static_assert cxx_strong_enums cxx_template_template_parameters cxx_trailing_return_types cxx_variadic_macros ) if(NOT DEFINED CMAKE_DEBUG_POSTFIX) # We can't do this yet because the CTK Plugin Framework # cannot cope with a postfix yet. #set(CMAKE_DEBUG_POSTFIX d) endif() #----------------------------------------------------------------------------- # Output directories. #----------------------------------------------------------------------------- set(_default_LIBRARY_output_dir lib) set(_default_RUNTIME_output_dir bin) set(_default_ARCHIVE_output_dir lib) foreach(type LIBRARY RUNTIME ARCHIVE) # Make sure the directory exists if(MITK_CMAKE_${type}_OUTPUT_DIRECTORY AND NOT EXISTS ${MITK_CMAKE_${type}_OUTPUT_DIRECTORY}) message("Creating directory MITK_CMAKE_${type}_OUTPUT_DIRECTORY: ${MITK_CMAKE_${type}_OUTPUT_DIRECTORY}") file(MAKE_DIRECTORY "${MITK_CMAKE_${type}_OUTPUT_DIRECTORY}") endif() if(MITK_CMAKE_${type}_OUTPUT_DIRECTORY) set(CMAKE_${type}_OUTPUT_DIRECTORY ${MITK_CMAKE_${type}_OUTPUT_DIRECTORY}) else() set(CMAKE_${type}_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/${_default_${type}_output_dir}) set(MITK_CMAKE_${type}_OUTPUT_DIRECTORY ${CMAKE_${type}_OUTPUT_DIRECTORY}) endif() set(CMAKE_${type}_OUTPUT_DIRECTORY ${CMAKE_${type}_OUTPUT_DIRECTORY} CACHE INTERNAL "Output directory for ${type} files.") mark_as_advanced(CMAKE_${type}_OUTPUT_DIRECTORY) endforeach() #----------------------------------------------------------------------------- # Set MITK specific options and variables (NOT available during superbuild) #----------------------------------------------------------------------------- # Look for optional Doxygen package find_package(Doxygen) option(BLUEBERRY_DEBUG_SMARTPOINTER "Enable code for debugging smart pointers" OFF) mark_as_advanced(BLUEBERRY_DEBUG_SMARTPOINTER) # ASK THE USER TO SHOW THE CONSOLE WINDOW FOR CoreApp and mitkWorkbench option(MITK_SHOW_CONSOLE_WINDOW "Use this to enable or disable the console window when starting MITK GUI Applications" ON) mark_as_advanced(MITK_SHOW_CONSOLE_WINDOW) # TODO: check if necessary option(USE_ITKZLIB "Use the ITK zlib for pic compression." ON) mark_as_advanced(USE_ITKZLIB) if(NOT MITK_FAST_TESTING) if(DEFINED MITK_CTEST_SCRIPT_MODE AND (MITK_CTEST_SCRIPT_MODE STREQUAL "continuous" OR MITK_CTEST_SCRIPT_MODE STREQUAL "experimental") ) set(MITK_FAST_TESTING 1) endif() endif() if(NOT UNIX AND NOT MINGW) set(MITK_WIN32_FORCE_STATIC "STATIC" CACHE INTERNAL "Use this variable to always build static libraries on non-unix platforms") endif() if(MITK_BUILD_ALL_PLUGINS) set(MITK_BUILD_ALL_PLUGINS_OPTION "FORCE_BUILD_ALL") endif() # Configure pixel types used for ITK image access multiplexing mitkMacroConfigureItkPixelTypes() # Configure module naming conventions set(MITK_MODULE_NAME_REGEX_MATCH "^[A-Z].*$") set(MITK_MODULE_NAME_REGEX_NOT_MATCH "^[Mm][Ii][Tt][Kk].*$") set(MITK_MODULE_NAME_PREFIX "Mitk") set(MITK_MODULE_NAME_DEFAULTS_TO_DIRECTORY_NAME 1) #----------------------------------------------------------------------------- # Get MITK version info #----------------------------------------------------------------------------- mitkFunctionGetVersion(${MITK_SOURCE_DIR} MITK) mitkFunctionGetVersionDescription(${MITK_SOURCE_DIR} MITK) # MITK_VERSION set(MITK_VERSION_STRING "${MITK_VERSION_MAJOR}.${MITK_VERSION_MINOR}.${MITK_VERSION_PATCH}") if(MITK_VERSION_PATCH STREQUAL "99") set(MITK_VERSION_STRING "${MITK_VERSION_STRING}-${MITK_REVISION_SHORTID}") endif() #----------------------------------------------------------------------------- # Installation preparation # # These should be set before any MITK install macros are used #----------------------------------------------------------------------------- # on Mac OSX all BlueBerry plugins get copied into every # application bundle (.app directory) specified here if(MITK_USE_BLUEBERRY AND APPLE) include("${CMAKE_CURRENT_SOURCE_DIR}/Applications/AppList.cmake") foreach(mitk_app ${MITK_APPS}) # extract option_name string(REPLACE "^^" "\\;" target_info ${mitk_app}) set(target_info_list ${target_info}) list(GET target_info_list 1 option_name) list(GET target_info_list 0 app_name) # check if the application is enabled if(${option_name} OR MITK_BUILD_ALL_APPS) set(MACOSX_BUNDLE_NAMES ${MACOSX_BUNDLE_NAMES} Mitk${app_name}) endif() endforeach() endif() #----------------------------------------------------------------------------- # Set coverage Flags #----------------------------------------------------------------------------- if(WITH_COVERAGE) if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") set(coverage_flags "-g -fprofile-arcs -ftest-coverage -O0 -DNDEBUG") set(COVERAGE_CXX_FLAGS ${coverage_flags}) set(COVERAGE_C_FLAGS ${coverage_flags}) endif() endif() #----------------------------------------------------------------------------- # MITK C/CXX Flags #----------------------------------------------------------------------------- set(MITK_C_FLAGS "${COVERAGE_C_FLAGS}") set(MITK_C_FLAGS_DEBUG ) set(MITK_C_FLAGS_RELEASE ) set(MITK_CXX_FLAGS "${COVERAGE_CXX_FLAGS} ${MITK_CXX14_FLAG}") set(MITK_CXX_FLAGS_DEBUG ) set(MITK_CXX_FLAGS_RELEASE ) set(MITK_EXE_LINKER_FLAGS ) set(MITK_SHARED_LINKER_FLAGS ) find_package(OpenMP) if (OPENMP_FOUND) set(MITK_C_FLAGS "${MITK_C_FLAGS} ${OpenMP_C_FLAGS}") set(MITK_CXX_FLAGS "${MITK_CXX_FLAGS} ${OpenMP_CXX_FLAGS}") endif() if(WIN32) set(MITK_CXX_FLAGS "${MITK_CXX_FLAGS} -D_WIN32_WINNT=0x0501 -DPOCO_NO_UNWINDOWS -DWIN32_LEAN_AND_MEAN -DNOMINMAX") mitkFunctionCheckCompilerFlags("/wd4005" MITK_CXX_FLAGS) # warning C4005: macro redefinition mitkFunctionCheckCompilerFlags("/wd4231" MITK_CXX_FLAGS) # warning C4231: nonstandard extension used : 'extern' before template explicit instantiation # the following line should be removed after fixing bug 17637 mitkFunctionCheckCompilerFlags("/wd4316" MITK_CXX_FLAGS) # warning C4316: object alignment on heap mitkFunctionCheckCompilerFlags("/wd4180" MITK_CXX_FLAGS) # warning C4180: qualifier applied to function type has no meaning endif() if(NOT MSVC_VERSION) foreach(_flag -Wall -Wextra -Wpointer-arith -Winvalid-pch -Wcast-align -Wwrite-strings -Wno-error=gnu -Wno-error=unknown-pragmas # The strict-overflow warning is generated by ITK template code -Wno-error=strict-overflow -Woverloaded-virtual -Wstrict-null-sentinel #-Wold-style-cast #-Wsign-promo -Wno-array-bounds -fdiagnostics-show-option ) mitkFunctionCheckCAndCXXCompilerFlags(${_flag} MITK_C_FLAGS MITK_CXX_FLAGS) endforeach() endif() if(CMAKE_COMPILER_IS_GNUCXX AND NOT APPLE) mitkFunctionCheckCompilerFlags("-Wl,--no-undefined" MITK_SHARED_LINKER_FLAGS) mitkFunctionCheckCompilerFlags("-Wl,--as-needed" MITK_SHARED_LINKER_FLAGS) endif() if(CMAKE_COMPILER_IS_GNUCXX) mitkFunctionCheckCAndCXXCompilerFlags("-fstack-protector-all" MITK_C_FLAGS MITK_CXX_FLAGS) if(MINGW) # suppress warnings about auto imported symbols set(MITK_SHARED_LINKER_FLAGS "-Wl,--enable-auto-import ${MITK_SHARED_LINKER_FLAGS}") endif() set(MITK_CXX_FLAGS_RELEASE "-U_FORTIFY_SOURCES -D_FORTIFY_SOURCE=2 ${MITK_CXX_FLAGS_RELEASE}") endif() set(MITK_MODULE_LINKER_FLAGS ${MITK_SHARED_LINKER_FLAGS}) set(MITK_EXE_LINKER_FLAGS ${MITK_SHARED_LINKER_FLAGS}) #----------------------------------------------------------------------------- # MITK Packages #----------------------------------------------------------------------------- set(MITK_MODULES_PACKAGE_DEPENDS_DIR ${MITK_SOURCE_DIR}/CMake/PackageDepends) set(MODULES_PACKAGE_DEPENDS_DIRS ${MITK_MODULES_PACKAGE_DEPENDS_DIR}) if(NOT MITK_USE_SYSTEM_Boost) set(Boost_NO_SYSTEM_PATHS 1) endif() set(Boost_USE_MULTITHREADED 1) set(Boost_USE_STATIC_LIBS 0) set(Boost_USE_STATIC_RUNTIME 0) set(Boost_ADDITIONAL_VERSIONS "1.64" "1.64.0") # We need this later for a DCMTK workaround set(_dcmtk_dir_orig ${DCMTK_DIR}) # This property is populated at the top half of this file get_property(MITK_EXTERNAL_PROJECTS GLOBAL PROPERTY MITK_EXTERNAL_PROJECTS) foreach(ep ${MITK_EXTERNAL_PROJECTS}) get_property(_package GLOBAL PROPERTY MITK_${ep}_PACKAGE) get_property(_components GLOBAL PROPERTY MITK_${ep}_COMPONENTS) if(MITK_USE_${ep} AND _package) if(_components) find_package(${_package} COMPONENTS ${_components} REQUIRED CONFIG) else() # Prefer config mode first because it finds external # Config.cmake files pointed at by _DIR variables. # Otherwise, existing Find.cmake files could fail. find_package(${_package} QUIET CONFIG) string(TOUPPER "${_package}" _package_uc) if(NOT (${_package}_FOUND OR ${_package_uc}_FOUND)) find_package(${_package} REQUIRED) endif() endif() endif() endforeach() # Ensure that the MITK CMake module path comes first set(CMAKE_MODULE_PATH ${MITK_CMAKE_DIR} ${CMAKE_MODULE_PATH} ) if(MITK_USE_DCMTK) # Due to the preferred CONFIG mode in find_package calls above, # the DCMTKConfig.cmake file is read, which does not provide useful # package information. We explictly need MODULE mode to find DCMTK. if(${_dcmtk_dir_orig} MATCHES "${MITK_EXTERNAL_PROJECT_PREFIX}.*") # Help our FindDCMTK.cmake script find our super-build DCMTK set(DCMTK_DIR ${MITK_EXTERNAL_PROJECT_PREFIX}) else() # Use the original value set(DCMTK_DIR ${_dcmtk_dir_orig}) endif() find_package(DCMTK REQUIRED MODULE) endif() if(MITK_USE_DCMQI) # Due to the preferred CONFIG mode in find_package calls above, # the DCMQIConfig.cmake file is read, which does not provide useful # package information. We explictly need MODULE mode to find DCMQI. # Help our FindDCMQI.cmake script find our super-build DCMQI set(DCMQI_DIR ${MITK_EXTERNAL_PROJECT_PREFIX}) find_package(DCMQI REQUIRED) endif() if(MITK_USE_Python) find_package(PythonLibs REQUIRED) find_package(PythonInterp REQUIRED) if(MITK_USE_Numpy) find_package(Numpy REQUIRED) endif() endif() link_directories(${Boost_LIBRARY_DIRS}) if(MITK_USE_OpenIGTLink) link_directories(${OpenIGTLink_LIBRARY_DIRS}) endif() if(MITK_USE_SimpleITK) link_directories(${SimpleITK_LIBRARY_DIRS}) endif() if(MITK_USE_OpenCL) find_package(OpenCL REQUIRED) endif() # Qt support if(MITK_USE_Qt5) find_package(Qt5Core ${MITK_QT5_MINIMUM_VERSION} REQUIRED) # at least Core required get_target_property(_qmake_exec Qt5::qmake LOCATION) execute_process(COMMAND ${_qmake_exec} -query QT_INSTALL_BINS RESULT_VARIABLE _result OUTPUT_VARIABLE QT_BINARY_DIR ERROR_VARIABLE _error ) string(STRIP "${QT_BINARY_DIR}" QT_BINARY_DIR) if(_result OR NOT EXISTS "${QT_BINARY_DIR}") message(FATAL_ERROR "Could not determine Qt binary directory: ${_result} ${QT_BINARY_DIR} ${_error}") endif() find_program(QT_HELPGENERATOR_EXECUTABLE NAMES qhelpgenerator qhelpgenerator-qt5 qhelpgenerator5 PATHS ${QT_BINARY_DIR} NO_DEFAULT_PATH ) find_program(QT_COLLECTIONGENERATOR_EXECUTABLE NAMES qcollectiongenerator qcollectiongenerator-qt5 qcollectiongenerator5 PATHS ${QT_BINARY_DIR} NO_DEFAULT_PATH ) find_program(QT_ASSISTANT_EXECUTABLE NAMES assistant assistant-qt5 assistant5 PATHS ${QT_BINARY_DIR} NO_DEFAULT_PATH ) find_program(QT_XMLPATTERNS_EXECUTABLE NAMES xmlpatterns PATHS ${QT_BINARY_DIR} NO_DEFAULT_PATH ) mark_as_advanced(QT_HELPGENERATOR_EXECUTABLE QT_COLLECTIONGENERATOR_EXECUTABLE QT_ASSISTANT_EXECUTABLE QT_XMLPATTERNS_EXECUTABLE ) if(MITK_USE_BLUEBERRY) option(BLUEBERRY_USE_QT_HELP "Enable support for integrating plugin documentation into Qt Help" ${DOXYGEN_FOUND}) mark_as_advanced(BLUEBERRY_USE_QT_HELP) # Sanity checks for in-application BlueBerry plug-in help generation if(BLUEBERRY_USE_QT_HELP) set(_force_blueberry_use_qt_help_to_off 0) if(NOT DOXYGEN_FOUND) message("> Forcing BLUEBERRY_USE_QT_HELP to OFF because Doxygen was not found.") set(_force_blueberry_use_qt_help_to_off 1) endif() if(DOXYGEN_FOUND AND DOXYGEN_VERSION VERSION_LESS 1.8.7) message("> Forcing BLUEBERRY_USE_QT_HELP to OFF because Doxygen version 1.8.7 or newer not found.") set(_force_blueberry_use_qt_help_to_off 1) endif() if(NOT QT_HELPGENERATOR_EXECUTABLE) message("> Forcing BLUEBERRY_USE_QT_HELP to OFF because QT_HELPGENERATOR_EXECUTABLE is empty.") set(_force_blueberry_use_qt_help_to_off 1) endif() if(NOT MITK_USE_Qt5_WebEngine) message("> Forcing BLUEBERRY_USE_QT_HELP to OFF because MITK_USE_Qt5_WebEngine is OFF.") set(_force_blueberry_use_qt_help_to_off 1) endif() if(NOT QT_XMLPATTERNS_EXECUTABLE) message("You have enabled Qt Help support, but QT_XMLPATTERNS_EXECUTABLE is empty") set(_force_blueberry_use_qt_help_to_off 1) endif() if(_force_blueberry_use_qt_help_to_off) set(BLUEBERRY_USE_QT_HELP OFF CACHE BOOL "Enable support for integrating plugin documentation into Qt Help" FORCE) endif() endif() if(BLUEBERRY_QT_HELP_REQUIRED AND NOT BLUEBERRY_USE_QT_HELP) message(FATAL_ERROR "BLUEBERRY_USE_QT_HELP is required to be set to ON") endif() endif() endif() #----------------------------------------------------------------------------- # Testing #----------------------------------------------------------------------------- if(BUILD_TESTING) enable_testing() include(CTest) mark_as_advanced(TCL_TCLSH DART_ROOT) option(MITK_ENABLE_RENDERING_TESTING OFF "Enable the MITK rendering tests. Requires x-server in Linux.") #Rendering testing does not work for Linux nightlies, thus it is disabled per default #and activated for Mac and Windows. if(WIN32 OR APPLE) set(MITK_ENABLE_RENDERING_TESTING ON) endif() mark_as_advanced( MITK_ENABLE_RENDERING_TESTING ) # Setup file for setting custom ctest vars configure_file( CMake/CTestCustom.cmake.in ${MITK_BINARY_DIR}/CTestCustom.cmake @ONLY ) # Initial cache for ProjectTemplate and PluginGenerator tests configure_file( CMake/mitkTestInitialCache.txt.in ${MITK_BINARY_DIR}/mitkTestInitialCache.txt @ONLY ) # Configuration for the CMake-generated test driver set(CMAKE_TESTDRIVER_EXTRA_INCLUDES "#include ") set(CMAKE_TESTDRIVER_BEFORE_TESTMAIN " try {") set(CMAKE_TESTDRIVER_AFTER_TESTMAIN " } catch( std::exception & excp ) { fprintf(stderr,\"%s\\n\",excp.what()); return EXIT_FAILURE; } catch( ... ) { printf(\"Exception caught in the test driver\\n\"); return EXIT_FAILURE; } ") set(MITK_TEST_OUTPUT_DIR "${MITK_BINARY_DIR}/test_output") if(NOT EXISTS ${MITK_TEST_OUTPUT_DIR}) file(MAKE_DIRECTORY ${MITK_TEST_OUTPUT_DIR}) endif() # Test the external project template if(MITK_USE_BLUEBERRY) include(mitkTestProjectTemplate) endif() # Test the package target include(mitkPackageTest) endif() configure_file(mitkTestingConfig.h.in ${MITK_BINARY_DIR}/mitkTestingConfig.h) #----------------------------------------------------------------------------- # MITK_SUPERBUILD_BINARY_DIR #----------------------------------------------------------------------------- # If MITK_SUPERBUILD_BINARY_DIR isn't defined, it means MITK is *NOT* build using Superbuild. # In that specific case, MITK_SUPERBUILD_BINARY_DIR should default to MITK_BINARY_DIR if(NOT DEFINED MITK_SUPERBUILD_BINARY_DIR) set(MITK_SUPERBUILD_BINARY_DIR ${MITK_BINARY_DIR}) endif() #----------------------------------------------------------------------------- # Set C/CXX and linker flags for MITK code #----------------------------------------------------------------------------- set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${MITK_CXX_FLAGS}") set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} ${MITK_CXX_FLAGS_DEBUG}") set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} ${MITK_CXX_FLAGS_RELEASE}") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${MITK_C_FLAGS}") set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} ${MITK_C_FLAGS_DEBUG}") set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} ${MITK_C_FLAGS_RELEASE}") set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${MITK_EXE_LINKER_FLAGS}") set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} ${MITK_SHARED_LINKER_FLAGS}") set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} ${MITK_MODULE_LINKER_FLAGS}") #----------------------------------------------------------------------------- # Add custom targets representing CDash subprojects #----------------------------------------------------------------------------- foreach(subproject ${CTEST_PROJECT_SUBPROJECTS}) if(NOT TARGET ${subproject} AND NOT subproject MATCHES "Unlabeled") add_custom_target(${subproject}) endif() endforeach() #----------------------------------------------------------------------------- # Add subdirectories #----------------------------------------------------------------------------- add_subdirectory(Utilities) add_subdirectory(Modules) if(MITK_USE_BLUEBERRY) set(BLUEBERRY_XPDOC_OUTPUT_DIR ${MITK_DOXYGEN_OUTPUT_DIR}/html/extension-points/html/) set(MITK_DEFAULT_SUBPROJECTS MITK-Plugins) # Plug-in testing (needs some work to be enabled again) if(BUILD_TESTING) set(BLUEBERRY_UI_TEST_APP "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/CoreApp") if(TARGET CoreApp) get_target_property(_is_macosx_bundle CoreApp MACOSX_BUNDLE) if(APPLE AND _is_macosx_bundle) set(BLUEBERRY_UI_TEST_APP "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/CoreApp.app/Contents/MacOS/CoreApp") endif() endif() set(BLUEBERRY_TEST_APP_ID "org.mitk.qt.coreapplication") endif() include("${CMAKE_CURRENT_SOURCE_DIR}/Plugins/PluginList.cmake") mitkFunctionWhitelistPlugins(MITK MITK_PLUGINS) set(mitk_plugins_fullpath "") foreach(mitk_plugin ${MITK_PLUGINS}) list(APPEND mitk_plugins_fullpath Plugins/${mitk_plugin}) endforeach() if(EXISTS ${MITK_PRIVATE_MODULES}/PluginList.cmake) include(${MITK_PRIVATE_MODULES}/PluginList.cmake) foreach(mitk_plugin ${MITK_PRIVATE_PLUGINS}) list(APPEND mitk_plugins_fullpath ${MITK_PRIVATE_MODULES}/${mitk_plugin}) endforeach() endif() if(MITK_BUILD_EXAMPLES) include("${CMAKE_CURRENT_SOURCE_DIR}/Examples/Plugins/PluginList.cmake") set(mitk_example_plugins_fullpath ) foreach(mitk_example_plugin ${MITK_EXAMPLE_PLUGINS}) list(APPEND mitk_example_plugins_fullpath Examples/Plugins/${mitk_example_plugin}) list(APPEND mitk_plugins_fullpath Examples/Plugins/${mitk_example_plugin}) endforeach() endif() # Specify which plug-ins belong to this project macro(GetMyTargetLibraries all_target_libraries varname) set(re_ctkplugin_mitk "^org_mitk_[a-zA-Z0-9_]+$") set(re_ctkplugin_bb "^org_blueberry_[a-zA-Z0-9_]+$") set(_tmp_list) list(APPEND _tmp_list ${all_target_libraries}) ctkMacroListFilter(_tmp_list re_ctkplugin_mitk re_ctkplugin_bb OUTPUT_VARIABLE ${varname}) endmacro() # Get infos about application directories and build options include("${CMAKE_CURRENT_SOURCE_DIR}/Applications/AppList.cmake") set(mitk_apps_fullpath ) foreach(mitk_app ${MITK_APPS}) # extract option_name string(REPLACE "^^" "\\;" target_info ${mitk_app}) set(target_info_list ${target_info}) list(GET target_info_list 0 directory_name) list(GET target_info_list 1 option_name) if(${option_name}) list(APPEND mitk_apps_fullpath "${CMAKE_CURRENT_SOURCE_DIR}/Applications/${directory_name}^^${option_name}") endif() endforeach() if (mitk_plugins_fullpath) ctkMacroSetupPlugins(${mitk_plugins_fullpath} BUILD_OPTION_PREFIX MITK_BUILD_ APPS ${mitk_apps_fullpath} BUILD_ALL ${MITK_BUILD_ALL_PLUGINS} COMPACT_OPTIONS) endif() set(MITK_PLUGIN_USE_FILE "${MITK_BINARY_DIR}/MitkPluginUseFile.cmake") if(${PROJECT_NAME}_PLUGIN_LIBRARIES) ctkFunctionGeneratePluginUseFile(${MITK_PLUGIN_USE_FILE}) else() file(REMOVE ${MITK_PLUGIN_USE_FILE}) set(MITK_PLUGIN_USE_FILE ) endif() endif() #----------------------------------------------------------------------------- # Documentation #----------------------------------------------------------------------------- if(DOXYGEN_FOUND) add_subdirectory(Documentation) endif() #----------------------------------------------------------------------------- # Installation #----------------------------------------------------------------------------- # set MITK cpack variables # These are the default variables, which can be overwritten ( see below ) include(mitkSetupCPack) set(use_default_config ON) # MITK_APPS is set in Applications/AppList.cmake (included somewhere above # if MITK_USE_BLUEBERRY is set to ON). if(MITK_APPS) set(activated_apps_no 0) list(LENGTH MITK_APPS app_count) # Check how many apps have been enabled # If more than one app has been activated, the we use the # default CPack configuration. Otherwise that apps configuration # will be used, if present. foreach(mitk_app ${MITK_APPS}) # extract option_name string(REPLACE "^^" "\\;" target_info ${mitk_app}) set(target_info_list ${target_info}) list(GET target_info_list 1 option_name) # check if the application is enabled if(${option_name} OR MITK_BUILD_ALL_APPS) MATH(EXPR activated_apps_no "${activated_apps_no} + 1") endif() endforeach() if(app_count EQUAL 1 AND (activated_apps_no EQUAL 1 OR MITK_BUILD_ALL_APPS)) # Corner case if there is only one app in total set(use_project_cpack ON) elseif(activated_apps_no EQUAL 1 AND NOT MITK_BUILD_ALL_APPS) # Only one app is enabled (no "build all" flag set) set(use_project_cpack ON) else() # Less or more then one app is enabled set(use_project_cpack OFF) endif() foreach(mitk_app ${MITK_APPS}) # extract target_dir and option_name string(REPLACE "^^" "\\;" target_info ${mitk_app}) set(target_info_list ${target_info}) list(GET target_info_list 0 target_dir) list(GET target_info_list 1 option_name) list(GET target_info_list 2 executable_name) # check if the application is enabled if(${option_name} OR MITK_BUILD_ALL_APPS) # check whether application specific configuration files will be used if(use_project_cpack) # use files if they exist if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/Applications/${target_dir}/CPackOptions.cmake") include("${CMAKE_CURRENT_SOURCE_DIR}/Applications/${target_dir}/CPackOptions.cmake") endif() if(EXISTS "${PROJECT_SOURCE_DIR}/Applications/${target_dir}/CPackConfig.cmake.in") set(CPACK_PROJECT_CONFIG_FILE "${PROJECT_BINARY_DIR}/Applications/${target_dir}/CPackConfig.cmake") configure_file(${PROJECT_SOURCE_DIR}/Applications/${target_dir}/CPackConfig.cmake.in ${CPACK_PROJECT_CONFIG_FILE} @ONLY) set(use_default_config OFF) endif() endif() # add link to the list list(APPEND CPACK_CREATE_DESKTOP_LINKS "${executable_name}") endif() endforeach() endif() # if no application specific configuration file was used, use default if(use_default_config) configure_file(${MITK_SOURCE_DIR}/MITKCPackOptions.cmake.in ${MITK_BINARY_DIR}/MITKCPackOptions.cmake @ONLY) set(CPACK_PROJECT_CONFIG_FILE "${MITK_BINARY_DIR}/MITKCPackOptions.cmake") endif() # include CPack model once all variables are set include(CPack) # Additional installation rules include(mitkInstallRules) #----------------------------------------------------------------------------- # Last configuration steps #----------------------------------------------------------------------------- # ---------------- Export targets ----------------- set(MITK_EXPORTS_FILE "${MITK_BINARY_DIR}/MitkExports.cmake") file(REMOVE ${MITK_EXPORTS_FILE}) set(targets_to_export) get_property(module_targets GLOBAL PROPERTY MITK_MODULE_TARGETS) if(module_targets) list(APPEND targets_to_export ${module_targets}) endif() if(MITK_USE_BLUEBERRY) if(MITK_PLUGIN_LIBRARIES) list(APPEND targets_to_export ${MITK_PLUGIN_LIBRARIES}) endif() endif() export(TARGETS ${targets_to_export} APPEND FILE ${MITK_EXPORTS_FILE}) set(MITK_EXPORTED_TARGET_PROPERTIES ) foreach(target_to_export ${targets_to_export}) get_target_property(autoload_targets ${target_to_export} MITK_AUTOLOAD_TARGETS) if(autoload_targets) set(MITK_EXPORTED_TARGET_PROPERTIES "${MITK_EXPORTED_TARGET_PROPERTIES} set_target_properties(${target_to_export} PROPERTIES MITK_AUTOLOAD_TARGETS \"${autoload_targets}\")") endif() get_target_property(autoload_dir ${target_to_export} MITK_AUTOLOAD_DIRECTORY) if(autoload_dir) set(MITK_EXPORTED_TARGET_PROPERTIES "${MITK_EXPORTED_TARGET_PROPERTIES} set_target_properties(${target_to_export} PROPERTIES MITK_AUTOLOAD_DIRECTORY \"${autoload_dir}\")") endif() get_target_property(deprecated_module ${target_to_export} MITK_MODULE_DEPRECATED_SINCE) if(deprecated_module) set(MITK_EXPORTED_TARGET_PROPERTIES "${MITK_EXPORTED_TARGET_PROPERTIES} set_target_properties(${target_to_export} PROPERTIES MITK_MODULE_DEPRECATED_SINCE \"${deprecated_module}\")") endif() endforeach() # ---------------- External projects ----------------- get_property(MITK_ADDITIONAL_LIBRARY_SEARCH_PATHS_CONFIG GLOBAL PROPERTY MITK_ADDITIONAL_LIBRARY_SEARCH_PATHS) set(MITK_CONFIG_EXTERNAL_PROJECTS ) #string(REPLACE "^^" ";" _mitk_external_projects ${MITK_EXTERNAL_PROJECTS}) foreach(ep ${MITK_EXTERNAL_PROJECTS}) get_property(_components GLOBAL PROPERTY MITK_${ep}_COMPONENTS) set(MITK_CONFIG_EXTERNAL_PROJECTS "${MITK_CONFIG_EXTERNAL_PROJECTS} set(MITK_USE_${ep} ${MITK_USE_${ep}}) set(MITK_${ep}_DIR \"${${ep}_DIR}\") set(MITK_${ep}_COMPONENTS ${_components}) ") endforeach() foreach(ep ${MITK_EXTERNAL_PROJECTS}) get_property(_package GLOBAL PROPERTY MITK_${ep}_PACKAGE) get_property(_components GLOBAL PROPERTY MITK_${ep}_COMPONENTS) if(_components) set(_components_arg COMPONENTS \${_components}) else() set(_components_arg) endif() if(_package) set(MITK_CONFIG_EXTERNAL_PROJECTS "${MITK_CONFIG_EXTERNAL_PROJECTS} if(MITK_USE_${ep}) set(${ep}_DIR \${MITK_${ep}_DIR}) if(MITK_${ep}_COMPONENTS) mitkMacroFindDependency(${_package} COMPONENTS \${MITK_${ep}_COMPONENTS}) else() mitkMacroFindDependency(${_package}) endif() endif()") endif() endforeach() # ---------------- Tools ----------------- configure_file(${MITK_SOURCE_DIR}/CMake/ToolExtensionITKFactory.cpp.in ${MITK_BINARY_DIR}/ToolExtensionITKFactory.cpp.in COPYONLY) configure_file(${MITK_SOURCE_DIR}/CMake/ToolExtensionITKFactoryLoader.cpp.in ${MITK_BINARY_DIR}/ToolExtensionITKFactoryLoader.cpp.in COPYONLY) configure_file(${MITK_SOURCE_DIR}/CMake/ToolGUIExtensionITKFactory.cpp.in ${MITK_BINARY_DIR}/ToolGUIExtensionITKFactory.cpp.in COPYONLY) # ---------------- Configure files ----------------- configure_file(mitkVersion.h.in ${MITK_BINARY_DIR}/mitkVersion.h) configure_file(mitkConfig.h.in ${MITK_BINARY_DIR}/mitkConfig.h) set(IPFUNC_INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/Utilities/ipFunc) set(UTILITIES_DIR ${CMAKE_CURRENT_SOURCE_DIR}/Utilities) configure_file(mitkConfig.h.in ${MITK_BINARY_DIR}/mitkConfig.h) configure_file(MITKConfig.cmake.in ${MITK_BINARY_DIR}/MITKConfig.cmake @ONLY) write_basic_config_version_file(${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake VERSION ${MITK_VERSION_STRING} COMPATIBILITY AnyNewerVersion) #----------------------------------------------------------------------------- # MITK Applications #----------------------------------------------------------------------------- # This must come after MITKConfig.h was generated, since applications # might do a find_package(MITK REQUIRED). add_subdirectory(Applications) #----------------------------------------------------------------------------- # MITK Examples #----------------------------------------------------------------------------- if(MITK_BUILD_EXAMPLES) # This must come after MITKConfig.h was generated, since applications # might do a find_package(MITK REQUIRED). add_subdirectory(Examples) endif() #----------------------------------------------------------------------------- # Print configuration summary #----------------------------------------------------------------------------- message("\n\n") feature_summary( DESCRIPTION "------- FEATURE SUMMARY FOR ${PROJECT_NAME} -------" WHAT ALL ) diff --git a/Modules/DiffusionImaging/CMakeLists.txt b/Modules/DiffusionImaging/CMakeLists.txt index c649ff334d..bcd76551e5 100644 --- a/Modules/DiffusionImaging/CMakeLists.txt +++ b/Modules/DiffusionImaging/CMakeLists.txt @@ -1,14 +1,13 @@ set( diffusion_module_dirs DiffusionCore FiberTracking Connectomics Quantification DiffusionIO - DeepDiffusion ) foreach(diffusion_module_dir ${diffusion_module_dirs}) add_subdirectory(${diffusion_module_dir}) endforeach() configure_file(${CMAKE_CURRENT_SOURCE_DIR}/mitkDiffusionImagingConfigure.h.in ${CMAKE_CURRENT_BINARY_DIR}/DiffusionCore/mitkDiffusionImagingConfigure.h) diff --git a/Modules/DiffusionImaging/DeepDiffusion/CMakeLists.txt b/Modules/DiffusionImaging/DeepDiffusion/CMakeLists.txt deleted file mode 100644 index 1aec51a519..0000000000 --- a/Modules/DiffusionImaging/DeepDiffusion/CMakeLists.txt +++ /dev/null @@ -1,17 +0,0 @@ -if(MITK_USE_Caffe2 AND MITK_USE_Caffe) - - set(_module_deps MitkFiberTracking ) - - MITK_CREATE_MODULE( - SUBPROJECTS MITK-DTI - INCLUDE_DIRS include/ src/ - DEPENDS ${_module_deps} - PACKAGE_DEPENDS PUBLIC OpenCV Caffe Caffe2 - ) - - if(MODULE_IS_ENABLED) - add_subdirectory(cmdapps) - add_subdirectory(Testing) - endif() - -endif() diff --git a/Modules/DiffusionImaging/DeepDiffusion/Testing/CMakeLists.txt b/Modules/DiffusionImaging/DeepDiffusion/Testing/CMakeLists.txt deleted file mode 100644 index 83f17ad300..0000000000 --- a/Modules/DiffusionImaging/DeepDiffusion/Testing/CMakeLists.txt +++ /dev/null @@ -1,4 +0,0 @@ -MITK_CREATE_MODULE_TESTS() - -mitkAddCustomModuleTest(mitkCaffe2PredictionTest mitkCaffe2PredictionTest) -mitkAddCustomModuleTest(mitkCaffePredictionTest mitkCaffePredictionTest) diff --git a/Modules/DiffusionImaging/DeepDiffusion/Testing/files.cmake b/Modules/DiffusionImaging/DeepDiffusion/Testing/files.cmake deleted file mode 100644 index acf3ce0cbb..0000000000 --- a/Modules/DiffusionImaging/DeepDiffusion/Testing/files.cmake +++ /dev/null @@ -1,6 +0,0 @@ -SET(MODULE_CUSTOM_TESTS - mitkCaffe2PredictionTest.cpp - mitkCaffePredictionTest.cpp -) - - diff --git a/Modules/DiffusionImaging/DeepDiffusion/Testing/mitkCaffe2PredictionTest.cpp b/Modules/DiffusionImaging/DeepDiffusion/Testing/mitkCaffe2PredictionTest.cpp deleted file mode 100644 index 6a4397dc18..0000000000 --- a/Modules/DiffusionImaging/DeepDiffusion/Testing/mitkCaffe2PredictionTest.cpp +++ /dev/null @@ -1,144 +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 -#include -#include - -#include -#include - -#include -#include -#include - -class mitkCaffe2PredictionTestSuite : public mitk::TestFixture -{ - - CPPUNIT_TEST_SUITE(mitkCaffe2PredictionTestSuite); - MITK_TEST(Test1); - CPPUNIT_TEST_SUITE_END(); - -private: - - /** Members used inside the different (sub-)tests. All members are initialized via setUp().*/ - -public: - - void setUp() override - { - } - - void tearDown() override - { - } - - // converts cv::Mat to a Caffe2 Tensor object that serves as input for the network - void to_tensorcpu(cv::Mat &img, caffe2::TensorCPU &tensor) - { - const int num_channel = tensor.dim(1); - const int height = tensor.dim(2); - const int width = tensor.dim(3); - - assert(img.channels() == num_channel); - assert(img.cols == width); - assert(img.rows == height); - - // convert to float - if (num_channel==3 && img.type()!=CV_32FC3) - img.convertTo(img, CV_32FC3); - else if(num_channel==1 && img.type()!=CV_32FC1) - img.convertTo(img, CV_32FC1); - - // subtract mean - img -= 128; // necessary? - - float* tensor_data = tensor.mutable_data(); - - // create array of cv::Mat where each matrix points to the tensor data - std::vector bgr; - for (int i = 0; i < num_channel; ++i) - { - bgr.push_back(cv::Mat(height, width, CV_32FC1, tensor_data)); - tensor_data += width * height; - } - - // HWC to CHW - // splits 3 channel matrix into three single channel matrices - cv::split(img, bgr); - } - - void Test1() - { - std::cout << "loading test image" << std::endl; - cv::Mat img = cv::imread(GetTestDataFilePath("DiffusionImaging/DeepDiffusion/Caffe2_Prediction_Test/flower.jpg"), CV_LOAD_IMAGE_COLOR); - - std::cout << "loading network definition and weights (predict_net and init_net)" << std::endl; - // use pretrained squeezenet in this case (https://github.com/caffe2/models) - caffe2::NetDef init_net, predict_net; - ReadProtoFromFile(GetTestDataFilePath("DiffusionImaging/DeepDiffusion/Caffe2_Prediction_Test/squeezenet/init_net.pb"), &init_net); - ReadProtoFromFile(GetTestDataFilePath("DiffusionImaging/DeepDiffusion/Caffe2_Prediction_Test/squeezenet/predict_net.pb"), &predict_net); - std::cout << "Predict net: " << ProtoDebugString(predict_net) << std::endl; - - std::cout << "creating predictor object" << std::endl; - auto predictor = caffe2::make_unique(init_net, predict_net); - - // input image specifications - int width = 227; - int height = 227; - int channels = 3; - - std::cout << "creating tensor object (Caffe2 network input)" << std::endl; - caffe2::TensorCPU input(std::vector({1, channels, height, width})); - - std::cout << "converting opencv image to tensor object" << std::endl; - to_tensorcpu(img, input); - - // the predictor takes a vector of tensors as input - caffe2::Predictor::TensorVector inputVec{&input}; - - // the netork output is also stored in a vector of tensors - caffe2::Predictor::TensorVector outputVec; - - std::cout << "running prediction" << std::endl; - predictor->run(inputVec, &outputVec); - - // since we only had one input tensor, we also have one output tensor in the vector - caffe2::TensorCPU* output = outputVec[0]; - - // the output tensor is of size 1x1000 (batch size 1 and 1000 classes from imagenet) - const float* output_data = output->data(); - - std::cout << "looking for max. probability class" << std::endl; - int max_class = -1; - float max_prob = 0; - for (int i=0; isize(); i++) - if(output_data[i]>max_prob) - { - max_prob = output_data[i]; - max_class = i; - } - std::cout << "Class: " << max_class << std::endl; - std::cout << "Probability: " << max_prob << std::endl; - - // should be 985 (daisy) - CPPUNIT_ASSERT_MESSAGE("Class probability should be ~0.995", fabs(max_prob-0.995)<0.001); - CPPUNIT_ASSERT_MESSAGE("Class should be 985", max_class==985); - } - -}; - -MITK_TEST_SUITE_REGISTRATION(mitkCaffe2Prediction) diff --git a/Modules/DiffusionImaging/DeepDiffusion/Testing/mitkCaffePredictionTest.cpp b/Modules/DiffusionImaging/DeepDiffusion/Testing/mitkCaffePredictionTest.cpp deleted file mode 100644 index 93444578a4..0000000000 --- a/Modules/DiffusionImaging/DeepDiffusion/Testing/mitkCaffePredictionTest.cpp +++ /dev/null @@ -1,109 +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 -#include -#include -#include - -#include -#include - -#include -#include - -class mitkCaffePredictionTestSuite : public mitk::TestFixture -{ - - CPPUNIT_TEST_SUITE(mitkCaffePredictionTestSuite); - MITK_TEST(Test1); - CPPUNIT_TEST_SUITE_END(); - -private: - - /** Members used inside the different (sub-)tests. All members are initialized via setUp().*/ - -public: - - std::default_random_engine generator; - - void setUp() override - { - } - - void tearDown() override - { - } - - void Test1() - { - generator.seed(0); - std::normal_distribution distribution(0.0,0.1); - - std::string network_file = GetTestDataFilePath("DiffusionImaging/DeepDiffusion/Caffe_Prediction_Test/unet_structure.prototxt"); - std::string weights_file = GetTestDataFilePath("DiffusionImaging/DeepDiffusion/Caffe_Prediction_Test/unet_weights.caffemodel"); - - MITK_INFO << "1"; - caffe::shared_ptr> network; - const std::vector stages = {"deploy"}; - network.reset(new caffe::Net(network_file, caffe::TEST, 0, &stages)); - network->CopyTrainedLayersFrom(weights_file); - MITK_INFO << "2"; - - caffe::Blob* input_layer = network->input_blobs()[0]; - float* input_data = input_layer->mutable_cpu_data(); - - cv::Mat ground_truth(input_layer->height(), input_layer->width(), CV_8UC1); - int counter = 0; - for (int x = 0; x < input_layer->height(); x++) - for (int y = 0; y < input_layer->width(); y++) - for (int j = 0; j < input_layer->channels(); j++) - { - input_data[counter] = 0; - if (x>20 && x<40 && y>20 && y<40) - input_data[counter] = 1; - if (x>35 && x<55 && y>25 && y<45) - input_data[counter] = 2; - - if (x>2 && x<12 && y>45 && y<55) - input_data[counter] = 1; - - if (x>50 && x<60 && y>50 && y<60) - input_data[counter] = 1; - - ground_truth.data[counter] = input_data[counter] * 100; - input_data[counter] += distribution(generator); - - counter++; - } - - network->Forward(); - - cv::Mat input_img = cv::Mat(input_layer->height(), input_layer->width(), CV_32FC1, input_data) * 100; - input_img.convertTo(input_img, CV_8UC1); - - boost::shared_ptr > output_layer = network->blob_by_name("argmax"); - cv::Mat out_img = cv::Mat(input_layer->height(), input_layer->width(), CV_32FC1, output_layer->mutable_cpu_data()) * 100; - out_img.convertTo(out_img, CV_8UC1); - -// cv::imwrite(MITK_DATA_DIR + "DiffusionImaging/DeepDiffusion/Caffe_Prediction_Test/input.png", input_img); -// cv::imwrite(MITK_DATA_DIR + "DiffusionImaging/DeepDiffusion/Caffe_Prediction_Test/output.png", out_img); -// cv::imwrite(MITK_DATA_DIR + "DiffusionImaging/DeepDiffusion/Caffe_Prediction_Test/ground_truth.png", ground_truth); - } - -}; - -MITK_TEST_SUITE_REGISTRATION(mitkCaffePrediction) diff --git a/Modules/DiffusionImaging/DeepDiffusion/cmdapps/BrainMaskSegmentation.cpp b/Modules/DiffusionImaging/DeepDiffusion/cmdapps/BrainMaskSegmentation.cpp deleted file mode 100755 index 143ed74af8..0000000000 --- a/Modules/DiffusionImaging/DeepDiffusion/cmdapps/BrainMaskSegmentation.cpp +++ /dev/null @@ -1,231 +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 -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -// Caffe -#include -#include -#include -#include - -// OpenCV -#include -#include - -#include - -std::default_random_engine generator; -std::normal_distribution distribution(0.0,0.1); - -itk::Image< float, 3 >::Pointer predict(caffe::shared_ptr> network, itk::Image< float, 3 >::Pointer input_image) -{ - itk::Image< float, 3 >::Pointer outImage = itk::Image< float, 3 >::New(); - outImage->SetSpacing( input_image->GetSpacing() ); // Set the image spacing - outImage->SetOrigin( input_image->GetOrigin() ); // Set the image origin - outImage->SetDirection( input_image->GetDirection() ); // Set the image direction - outImage->SetLargestPossibleRegion( input_image->GetLargestPossibleRegion()); - outImage->SetBufferedRegion(input_image->GetLargestPossibleRegion()); - outImage->SetRequestedRegion( input_image->GetLargestPossibleRegion()); - outImage->Allocate(); - outImage->FillBuffer(0); - - itk::Size<3> image_size = input_image->GetLargestPossibleRegion().GetSize(); - caffe::Blob* input_layer = network->input_blobs()[0]; - - int padX = 0; - int padY = 0; - if (image_size[0]>256) - padX = (image_size[0]-256)/2; - if (image_size[2]>256) - padY = (image_size[2]-256)/2; - - input_layer->Reshape(1, 1, 256, 256); - network->Reshape(); - - MITK_INFO << "Predicting"; - for (unsigned int slice = 0; slicemutable_cpu_data(); - int counter = 0; - - for (int x = 0; x < input_layer->height(); x++) - for (int y = 0; y < input_layer->width(); y++) - { - itk::Image< float, 3 >::IndexType idx; - idx[0] = padY+y; - idx[1] = slice; - idx[2] = input_layer->height() - (padX+x) - 1; - if (input_image->GetLargestPossibleRegion().IsInside(idx)) - input_data[counter] = input_image->GetPixel(idx); - else - input_data[counter] = 0; - counter++; - } - - network->Forward(); - -// cv::Mat input_img = cv::Mat(input_layer->height(), input_layer->width(), CV_32FC1, input_data)*50 + 128; -// input_img.convertTo(input_img, CV_8UC1); -// cv::namedWindow( "Input", cv::WINDOW_NORMAL ); -// cv::imshow( "Input", input_img ); - - boost::shared_ptr > output_layer = network->blob_by_name("argmax"); - float* output_data = output_layer->mutable_cpu_data(); - cv::Mat out_img = cv::Mat(output_layer->height(), output_layer->width(), CV_32FC1, output_data) * 50; - out_img.convertTo(out_img, CV_8UC1); - -// cv::namedWindow( "Output", cv::WINDOW_NORMAL ); -// cv::imshow( "Output", out_img ); -// cv::waitKey(1); - - counter = 0; - for (int x = 0; x < output_layer->height(); x++) - for (int y = 0; y < output_layer->width(); y++) - { - itk::Image< float, 3 >::IndexType idx; - idx[0] = y; - idx[1] = slice; - idx[2] = output_layer->height() - x - 1; - - if (outImage->GetLargestPossibleRegion().IsInside(idx)) - outImage->SetPixel(idx, output_data[counter]); - counter++; - } - } - - return outImage; -} - -/*! -* \brief Segmentation example for Caffe in MITK -* -*/ -int main(int argc, char* argv[]) -{ - mitkCommandLineParser parser; - parser.setTitle("CaffeTest"); - parser.setCategory("Fiber Tracking and Processing Methods"); - parser.setContributor("MIC"); - parser.setDescription("Barin mask extraction"); - parser.setArgumentPrefix("--", "-"); - parser.addArgument("input_image", "i", mitkCommandLineParser::String, "Input image:", "Input image to segment (T1 or T2)", us::Any(), false); - parser.addArgument("output_image", "o", mitkCommandLineParser::String, "Output image:", "Output segmentation", us::Any(), false); - parser.addArgument("network_file", "", mitkCommandLineParser::String, "network_file:", ".prototxt", us::Any(), false); - parser.addArgument("weights_file", "", mitkCommandLineParser::String, "weights_file:", ".caffemodel", us::Any(), false); - parser.addArgument("use_cpu", "", mitkCommandLineParser::Bool, "Use CPU:", "Use CPU for prediction. Default is GPU."); - - std::map parsedArgs = parser.parseArguments(argc, argv); - if (parsedArgs.size()==0) - return EXIT_FAILURE; - - std::string network_file = us::any_cast(parsedArgs["network_file"]); - std::string weights_file = us::any_cast(parsedArgs["weights_file"]); - std::string input_image_file = us::any_cast(parsedArgs["input_image"]); - std::string output_image_file = us::any_cast(parsedArgs["output_image"]); - - if (parsedArgs.count("use_cpu")) - caffe::Caffe::set_mode(caffe::Caffe::CPU); - else - caffe::Caffe::set_mode(caffe::Caffe::GPU); - - mitk::Image::Pointer input_input_image = dynamic_cast(mitk::IOUtil::Load(input_image_file)[0].GetPointer()); - - typedef itk::Image< float, 3 > FloatImgType; - FloatImgType::Pointer float_img = FloatImgType::New(); - mitk::CastToItkImage(input_input_image, float_img); - - typedef itk::ResampleImageFilter< FloatImgType, FloatImgType > ResamplerType; - - FloatImgType::SpacingType image_spacing = float_img->GetSpacing(); - FloatImgType::SpacingType target_spacing; target_spacing.Fill(0.7); - if (fabs(image_spacing[0]-target_spacing[0]) > mitk::eps || fabs(image_spacing[1]-target_spacing[1]) > mitk::eps || fabs(image_spacing[2]-target_spacing[2]) > mitk::eps) - { - MITK_INFO << "Resampling"; - itk::Vector< double, 3 > sampling; - itk::ImageRegion<3> newRegion; - sampling[0] = image_spacing[0]/target_spacing[0]; - sampling[1] = image_spacing[1]/target_spacing[1]; - sampling[2] = image_spacing[2]/target_spacing[2]; - newRegion = float_img->GetLargestPossibleRegion(); - newRegion.SetSize(0, newRegion.GetSize(0)*sampling[0]); - newRegion.SetSize(1, newRegion.GetSize(1)*sampling[1]); - newRegion.SetSize(2, newRegion.GetSize(2)*sampling[2]); - - itk::Point newOrigin = float_img->GetOrigin(); - newOrigin[0] -= image_spacing[0]/2; - newOrigin[1] -= image_spacing[1]/2; - newOrigin[2] -= image_spacing[2]/2; - newOrigin[0] += target_spacing[0]/2; - newOrigin[1] += target_spacing[1]/2; - newOrigin[2] += target_spacing[2]/2; - - typename FloatImgType::Pointer newImage = FloatImgType::New(); - newImage->SetSpacing( target_spacing ); - newImage->SetOrigin( newOrigin ); - newImage->SetDirection( float_img->GetDirection() ); - newImage->SetLargestPossibleRegion( newRegion ); - newImage->SetBufferedRegion( newRegion ); - newImage->SetRequestedRegion( newRegion ); - newImage->Allocate(); - - ResamplerType::Pointer resampler = ResamplerType::New(); - resampler->SetInput(float_img); - resampler->SetOutputParametersFromImage(newImage); - resampler->Update(); - float_img = resampler->GetOutput(); - } - - MITK_INFO << "Normalizing"; - itk::NormalizeImageSlicesFilter< float >::Pointer normalizer = itk::NormalizeImageSlicesFilter< float >::New(); - normalizer->SetInput(float_img); - normalizer->SetAxis(1); - normalizer->Update(); - float_img = normalizer->GetOutput(); - - caffe::shared_ptr> network; - const std::vector stages = {"deploy"}; - network.reset(new caffe::Net(network_file, caffe::TEST, 0, &stages)); - network->CopyTrainedLayersFrom(weights_file); - - itk::Image< float, 3 >::Pointer output_image = predict(network, float_img); - - typedef itk::ImageFileWriter< itk::Image< float, 3 > > WriterType; - WriterType::Pointer writer = WriterType::New(); - writer->SetFileName(output_image_file); - writer->SetInput(output_image); - writer->Update(); - - return EXIT_SUCCESS; -} - diff --git a/Modules/DiffusionImaging/DeepDiffusion/cmdapps/CMakeLists.txt b/Modules/DiffusionImaging/DeepDiffusion/cmdapps/CMakeLists.txt deleted file mode 100755 index 9044176f38..0000000000 --- a/Modules/DiffusionImaging/DeepDiffusion/cmdapps/CMakeLists.txt +++ /dev/null @@ -1,37 +0,0 @@ -option(BUILD_DeepDiffusionCmdApps "Build MITK diffusion commandline tools with deep learning support." OFF) - -if(BUILD_DeepDiffusionCmdApps OR MITK_BUILD_ALL_APPS) - - # needed include directories - include_directories( - ${CMAKE_CURRENT_SOURCE_DIR} - ${CMAKE_CURRENT_BINARY_DIR} - ) - - # list of diffusion cmdapps - # if an app requires additional dependencies - # they are added after a "^^" and separated by "_" - set( deepdiffusioncmdapps - CaffeTest^^ - CaffeSegmentationTest^^ - BrainMaskSegmentation^^MitkImageStatistics - Caffe2Test^^ - ) - - foreach(cmdapp ${deepdiffusioncmdapps}) - # extract cmd app name and dependencies - string(REPLACE "^^" "\\;" cmdapp_info ${cmdapp}) - set(cmdapp_info_list ${cmdapp_info}) - list(GET cmdapp_info_list 0 appname) - list(GET cmdapp_info_list 1 raw_dependencies) - string(REPLACE "_" "\\;" dependencies "${raw_dependencies}") - set(dependencies_list ${dependencies}) - - mitkFunctionCreateCommandLineApp( - NAME ${appname} - DEPENDS MitkCore MitkDiffusionCore MitkDeepDiffusion ${dependencies_list} - PACKAGE_DEPENDS ITK Eigen Caffe Caffe2 OpenCV - ) - endforeach() - -endif() diff --git a/Modules/DiffusionImaging/DeepDiffusion/cmdapps/Caffe2Test.cpp b/Modules/DiffusionImaging/DeepDiffusion/cmdapps/Caffe2Test.cpp deleted file mode 100755 index 8c0ac7a91b..0000000000 --- a/Modules/DiffusionImaging/DeepDiffusion/cmdapps/Caffe2Test.cpp +++ /dev/null @@ -1,197 +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 -#include -#include -#include -#include -#include "mitkCommandLineParser.h" -#include - -// Caffe2 -#include -#include "caffe2/core/context.h" -#include "caffe2/core/operator.h" -#include "caffe2/core/predictor.h" -#include "caffe2/core/tensor.h" -#include "caffe2/utils/math.h" -#include -#include -#include - -#include - -// OpenCV -#include -#include - -template -void to_tensor(cv::Mat &img, TensorType &tensor) -{ - const int num_channel = tensor.dim(1); - const int height = tensor.dim(2); - const int width = tensor.dim(3); - - assert(img.channels() == num_channel); - assert(img.cols == width); - assert(img.rows == height); - - // convert to float - if (num_channel==3 && img.type()!=CV_32FC3) - img.convertTo(img, CV_32FC3); - else if(num_channel==1 && img.type()!=CV_32FC1) - img.convertTo(img, CV_32FC1); - - // subtract mean - img -= 128; // necessary? - -// caffe2::CPUContext cpu_context; -// caffe2::TensorCPU cpu_input(tensor, &cpu_context); -// float* tensor_data = cpu_input.template mutable_data(); - float* tensor_data = tensor.template mutable_data(); - - // create array of cv::Mat where each matrix points to the tensor data - std::vector bgr; - for (int i = 0; i < num_channel; ++i) - { - bgr.push_back(cv::Mat(height, width, CV_32FC1, tensor_data)); - tensor_data += width * height; - } - - // HWC to CHW - // splits 3 channel matrix into three single channel matrices - cv::split(img, bgr); -} - -/*! -* \brief Minimal example for Caffe2 prediction in MITK -* -*/ -int main(int argc, char* argv[]) -{ - mitkCommandLineParser parser; - parser.setTitle("Caffe2Test"); - parser.setCategory("MITK Diffusion Deep Learning"); - parser.setContributor("MIC"); - parser.setDescription("Minimal example for Caffe2 prediction in MITK"); - parser.setArgumentPrefix("--", "-"); - parser.addArgument("image", "", mitkCommandLineParser::String, "image:", "", us::Any()); - parser.addArgument("init_net", "", mitkCommandLineParser::String, "init_net:", "the network weights (.pb)", us::Any()); - parser.addArgument("predict_net", "", mitkCommandLineParser::String, "predict_net:", "the network definition (.pb)", us::Any()); - -// typedef caffe2::TensorCPU TensorType; - typedef caffe2::TensorCUDA TensorType; - - std::map parsedArgs = parser.parseArguments(argc, argv); - std::string init_net_filename = us::any_cast(parsedArgs["init_net"]); - std::string predict_net_filename = us::any_cast(parsedArgs["predict_net"]); -// std::string image_filename = us::any_cast(parsedArgs["image"]); -// cv::Mat img = cv::imread(image_filename, CV_LOAD_IMAGE_COLOR); -// cv::Mat img = cv::Mat(64,64,CV_32FC3,128); -// cv::namedWindow( "Display window", cv::WINDOW_AUTOSIZE );// Create a window for display. -// cv::imshow( "Display w30indow", img2 ); // Show our image inside it. -// cv::waitKey(0); // Wait for a keystroke in the window - - caffe2::NetDef init_net, predict_net; - CAFFE_ENFORCE(ReadProtoFromFile(init_net_filename, &init_net)); - CAFFE_ENFORCE(ReadProtoFromFile(predict_net_filename, &predict_net)); - - MITK_INFO << "Predict net: " << ProtoDebugString(predict_net); - std::vector outputVec; - - int w,h,c; w=64; h=64; c=1; - TensorType input(std::vector({1, h, w, c})); - -//// TRYING TO ACCESS TENSOR DATA (RESULTS IN ERROR FOR caffe2::TensorCUDA) -// caffe2::CPUContext cpu_context; -// caffe2::TensorCPU cpu_input(input, &cpu_context); -// float* input_data = cpu_input.template mutable_data(); - float* input_data = input.mutable_data(); - - // create input image (simply a square of size 10x10 in a 64x64 image) - // test image for segmentation - int counter = 0; - for (int x = 0; x < h; x++) - for (int y = 0; y < w; y++) - { - for (int j = 0; j < c; j++) - { - input_data[counter] = 0; - if (x>20 && x<30 && y>20 && y<30) - input_data[counter] = 1; - counter++; - } - } - - // show input image - cv::Mat img = cv::Mat(64,64,CV_32FC1,input_data); - cv::namedWindow( "Display window", cv::WINDOW_AUTOSIZE );// Create a window for display. - cv::imshow( "Display window", img ); // Show our image inside it. - cv::waitKey(0); // Wait for a keystroke in the window - - // run network - std::vector inputVec{input}; - caffe2::Workspace ws; - ws.RunNetOnce(init_net); - ws.CreateNet(predict_net, true); - - for (unsigned int i = 0; i < inputVec.size(); ++i) - { - auto* blob = ws.GetBlob(predict_net.external_input(i)); - TensorType* tensor = blob->template GetMutable(); - tensor->ResizeLike(inputVec[i]); - tensor->ShareData(inputVec[i]); - } - CAFFE_ENFORCE(ws.RunNet(predict_net.name())); - - outputVec.resize(predict_net.external_output_size()); - for (unsigned int i = 0; i < outputVec.size(); ++i) - { - auto* blob = ws.GetBlob(predict_net.external_output(i)); - outputVec[i] = blob->template GetMutable(); - } - -//// auto predictor = caffe2::make_unique(init_net, predict_net); -//// predictor->run(inputVec, &outputVec); - - // get ourput from network - TensorType* output = outputVec[outputVec.size()]; - -// const float* output_data = output->data(); - cv::Mat out_img = cv::Mat(64,64,CV_32FC3,output->mutable_data()); - - cv::namedWindow( "Display window", cv::WINDOW_AUTOSIZE );// Create a window for display. - cv::imshow( "Display window", out_img ); // Show our image inside it. - cv::waitKey(0); // Wait for a keystroke in the window - -//// remainder of the classification test -// int max_class = -1; -// float max_prob = 0; -// for (int i=0; isize(); i++) -// { -// if(output_data[i]>max_prob) -// { -// max_prob = output_data[i]; -// max_class = i; -// } -// } -// MITK_INFO << "Class: " << max_class; -// MITK_INFO << "Probability: " << max_prob; - - return EXIT_SUCCESS; -} - diff --git a/Modules/DiffusionImaging/DeepDiffusion/cmdapps/CaffeSegmentationTest.cpp b/Modules/DiffusionImaging/DeepDiffusion/cmdapps/CaffeSegmentationTest.cpp deleted file mode 100755 index 553d687d1b..0000000000 --- a/Modules/DiffusionImaging/DeepDiffusion/cmdapps/CaffeSegmentationTest.cpp +++ /dev/null @@ -1,123 +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 -#include -#include -#include -#include -#include -#include -#include - -// Caffe -#include -#include -#include -#include - - -// OpenCV -#include -#include - -std::default_random_engine generator; -std::normal_distribution distribution(0.0,0.1); - -void predict(caffe::shared_ptr> network) -{ - caffe::Blob* input_layer = network->input_blobs()[0]; - float* input_data = input_layer->mutable_cpu_data(); - - int counter = 0; - for (int x = 0; x < input_layer->height(); x++) - for (int y = 0; y < input_layer->width(); y++) - for (int j = 0; j < input_layer->channels(); j++) - { - input_data[counter] = 0; - if (x>20 && x<40 && y>20 && y<40) - input_data[counter] = 1; - if (x>35 && x<55 && y>25 && y<45) - input_data[counter] = 2; - - if (x>2 && x<12 && y>45 && y<55) - input_data[counter] = 1; - - if (x>50 && x<60 && y>50 && y<60) - input_data[counter] = 1; - - input_data[counter] += distribution(generator); - - counter++; - } - -// // not necessary here -// input_layer->Reshape(1, num_channels, height, width); -// network->Reshape(); - - network->Forward(); - - cv::Mat input_img = cv::Mat(input_layer->height(), input_layer->width(), CV_32FC1, input_data) * 100; - input_img.convertTo(input_img, CV_8UC1); - cv::namedWindow( "Input", cv::WINDOW_NORMAL ); - cv::imshow( "Input", input_img ); - - boost::shared_ptr > output_layer = network->blob_by_name("argmax"); - cv::Mat out_img = cv::Mat(input_layer->height(), input_layer->width(), CV_32FC1, output_layer->mutable_cpu_data()) * 100; - out_img.convertTo(out_img, CV_8UC1); - - cv::namedWindow( "Output", cv::WINDOW_NORMAL ); - cv::imshow( "Output", out_img ); - cv::waitKey(0); -} - -/*! -* \brief Segmentation example for Caffe in MITK -* -*/ -int main(int argc, char* argv[]) -{ - caffe::Caffe::set_mode(caffe::Caffe::GPU); - - mitkCommandLineParser parser; - parser.setTitle("CaffeTest"); - parser.setCategory("MITK Diffusion Deep Learning"); - parser.setContributor("MIC"); - parser.setDescription("Minimal example for Caffe usage in MITK"); - parser.setArgumentPrefix("--", "-"); - parser.addArgument("network_file", "", mitkCommandLineParser::String, "network_file:", ".prototxt", us::Any()); - parser.addArgument("weights_file", "", mitkCommandLineParser::String, "weights_file:", ".caffemodel", us::Any()); - -// google::InitGoogleLogging(argv[0]); -// google::SetCommandLineOption("GLOG_minloglevel", "0"); - - std::map parsedArgs = parser.parseArguments(argc, argv); - if (parsedArgs.size()==0) - return EXIT_FAILURE; - - std::string network_file = us::any_cast(parsedArgs["network_file"]); - std::string weights_file = us::any_cast(parsedArgs["weights_file"]); - - caffe::shared_ptr> network; - const std::vector stages = {"deploy"}; - network.reset(new caffe::Net(network_file, caffe::TEST, 0, &stages)); - network->CopyTrainedLayersFrom(weights_file); - - predict(network); - - return EXIT_SUCCESS; -} - diff --git a/Modules/DiffusionImaging/DeepDiffusion/cmdapps/CaffeTest.cpp b/Modules/DiffusionImaging/DeepDiffusion/cmdapps/CaffeTest.cpp deleted file mode 100755 index ca4d4aba30..0000000000 --- a/Modules/DiffusionImaging/DeepDiffusion/cmdapps/CaffeTest.cpp +++ /dev/null @@ -1,189 +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 -#include -#include -#include -#include -#include -#include -#include - -// Caffe -#include -#include -#include -#include - - -// OpenCV -#include -#include - -caffe::shared_ptr> train(caffe::Solver* solver) -{ - int num_samples = 64; - int num_features = 100; - float *data = new float[1*1*num_features*num_samples]; - float *label = new float[1*1*1*num_samples]; - float *directions = new float[1*1*3*num_samples]; - - caffe::MemoryDataLayer *image_input_layer = (caffe::MemoryDataLayer *) (solver->net()->layer_by_name("image_data").get()); - caffe::MemoryDataLayer *target_input_layer = (caffe::MemoryDataLayer *) (solver->net()->layer_by_name("target_data").get()); - - image_input_layer->Reset(data, label, num_samples); - target_input_layer->Reset(directions, label, num_samples); - solver->Solve(); - return solver->net(); -} - -caffe::Solver* read_solver(std::string solver_file) -{ - caffe::SolverParameter solver_param; - caffe::ReadSolverParamsFromTextFileOrDie(solver_file, &solver_param); - return new caffe::AdamSolver(solver_param); -} - -std::default_random_engine generator; -std::normal_distribution distribution(0.0,0.1); - -void predict(caffe::shared_ptr> network) -{ - caffe::Blob* input_layer = network->input_blobs()[0]; - float* input_data = input_layer->mutable_cpu_data(); - - int counter = 0; - for (int x = 0; x < input_layer->height(); x++) - for (int y = 0; y < input_layer->width(); y++) - for (int j = 0; j < input_layer->channels(); j++) - { - input_data[counter] = 0; - if (x>20 && x<40 && y>20 && y<40) - input_data[counter] = 1; - if (x>35 && x<55 && y>25 && y<45) - input_data[counter] = 2; - - if (x>2 && x<12 && y>45 && y<55) - input_data[counter] = 1; - - if (x>50 && x<60 && y>50 && y<60) - input_data[counter] = 1; - - input_data[counter] += distribution(generator); - - counter++; - } - - network->Forward(); - - cv::Mat input_img = cv::Mat(input_layer->height(), input_layer->width(), CV_32FC1, input_data) * 100; - input_img.convertTo(input_img, CV_8UC1); - cv::namedWindow( "Input", cv::WINDOW_NORMAL ); - cv::imshow( "Input", input_img ); - - boost::shared_ptr > output_layer = network->blob_by_name("argmax"); - cv::Mat out_img = cv::Mat(input_layer->height(), input_layer->width(), CV_32FC1, output_layer->mutable_cpu_data()) * 100; - out_img.convertTo(out_img, CV_8UC1); - - cv::namedWindow( "Output", cv::WINDOW_NORMAL ); - cv::imshow( "Output", out_img ); - cv::waitKey(0); -} - -std::vector predict_data_layer(const cv::Mat& img, caffe::shared_ptr> network) { - caffe::Blob* input_layer = network->input_blobs()[0]; - - assert(img.channels() == input_layer->channels()); - assert(img.cols == input_layer->width()); - assert(img.rows == input_layer->height()); - - cv::Mat img2; - // convert to float - if (img.channels()==3 && img.type()!=CV_32FC3) - img.convertTo(img2, CV_32FC3); - else if(img.channels()==1 && img.type()!=CV_32FC1) - img.convertTo(img2, CV_32FC1); - - float* input_data = input_layer->mutable_cpu_data(); // pointer to the memory data layer - std::vector bgr; - for (int i = 0; i < img2.channels(); ++i) { - cv::Mat channel(input_layer->height(), input_layer->width(), CV_32FC1, input_data); - bgr.push_back(channel); - input_data += input_layer->width() * input_layer->height(); - } - cv::split(img2, bgr); - - network->Forward(); - - /* Copy the output layer to a std::vector */ - caffe::Blob* output_layer = network->output_blobs()[0]; - const float* begin = output_layer->cpu_data(); - const float* end = begin + output_layer->channels(); - return std::vector(begin, end); -} - -/*! -* \brief Segmentation example for Caffe in MITK -* -*/ -int main(int argc, char* argv[]) -{ - caffe::Caffe::set_mode(caffe::Caffe::GPU); - - mitkCommandLineParser parser; - parser.setTitle("CaffeTest"); - parser.setCategory("MITK Diffusion Deep Learning"); - parser.setContributor("MIC"); - parser.setDescription("Minimal example for Caffe usage in MITK"); - parser.setArgumentPrefix("--", "-"); - parser.addArgument("image", "", mitkCommandLineParser::String, "image:", "", us::Any()); - parser.addArgument("solver_file", "", mitkCommandLineParser::String, "solver_file:", "the caffe solver file (.prototxt)", us::Any()); - parser.addArgument("network_file", "", mitkCommandLineParser::String, "network_file:", ".prototxt", us::Any()); - parser.addArgument("weights_file", "", mitkCommandLineParser::String, "weights_file:", ".caffemodel", us::Any()); - - std::map parsedArgs = parser.parseArguments(argc, argv); - if (parsedArgs.size()==0) - return EXIT_FAILURE; - - std::string image_filename = us::any_cast(parsedArgs["image"]); - cv::Mat img = cv::imread(image_filename, CV_LOAD_IMAGE_GRAYSCALE); -// cv::namedWindow( "Display window", cv::WINDOW_AUTOSIZE );// Create a window for display. -// cv::imshow( "Display window", img ); // Show our image inside it. -// cv::waitKey(0); // Wait for a keystroke in the window - - //// TRAINING -// std::string solver_file = us::any_cast(parsedArgs["solver_file"]); -// caffe::Solver* solver = read_solver(solver_file); -// caffe::shared_ptr> trained_net = train(solver); -// const float* test_output = test(trained_net); - - std::string network_file = us::any_cast(parsedArgs["network_file"]); - std::string weights_file = us::any_cast(parsedArgs["weights_file"]); - - caffe::shared_ptr> network; - const std::vector stages = {"deploy"}; - network.reset(new caffe::Net(network_file, caffe::TEST, 0, &stages)); - network->CopyTrainedLayersFrom(weights_file); - - MITK_INFO << "predicting"; - predict(network); - MITK_INFO << "DONE"; - - - return EXIT_SUCCESS; -} - diff --git a/Modules/DiffusionImaging/DeepDiffusion/files.cmake b/Modules/DiffusionImaging/DeepDiffusion/files.cmake deleted file mode 100644 index ba4d98bf12..0000000000 --- a/Modules/DiffusionImaging/DeepDiffusion/files.cmake +++ /dev/null @@ -1,8 +0,0 @@ -set(CPP_FILES - mitkDeepDiffusionModuleActivator.cpp - itkNormalizeImageSlicesFilter.cpp -) - -set(H_FILES - include/itkNormalizeImageSlicesFilter.h -) diff --git a/Modules/DiffusionImaging/DeepDiffusion/include/itkNormalizeImageSlicesFilter.h b/Modules/DiffusionImaging/DeepDiffusion/include/itkNormalizeImageSlicesFilter.h deleted file mode 100644 index 130a5da29c..0000000000 --- a/Modules/DiffusionImaging/DeepDiffusion/include/itkNormalizeImageSlicesFilter.h +++ /dev/null @@ -1,79 +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. - -===================================================================*/ - -/*=================================================================== - -This file is based heavily on a corresponding ITK filter. - -===================================================================*/ -#ifndef __itkNormalizeImageSlicesFilter_h_ -#define __itkNormalizeImageSlicesFilter_h_ - -#include - -namespace itk{ - -/** -* \brief Normalize slices along given axis to 0 mean and 1 std. */ - -template< class TPixelType > -class NormalizeImageSlicesFilter : - public ImageToImageFilter< Image< TPixelType, 3 >, Image< float, 3 > > -{ - -public: - - typedef NormalizeImageSlicesFilter Self; - typedef SmartPointer Pointer; - typedef SmartPointer ConstPointer; - typedef ImageToImageFilter< Image< TPixelType, 3 >, Image< float, 3 > > Superclass; - - /** Method for creation through the object factory. */ - itkFactorylessNewMacro(Self) - itkCloneMacro(Self) - - /** Runtime information support. */ - itkTypeMacro(NormalizeImageSlicesFilter, ImageToImageFilter) - - typedef typename Superclass::InputImageType InputImageType; - typedef typename Superclass::OutputImageType OutputImageType; - typedef typename Superclass::OutputImageRegionType OutputImageRegionType; - - itkSetMacro( Axis, unsigned int ) - - virtual void Update() override{ - this->GenerateData(); - } - -protected: - NormalizeImageSlicesFilter(); - ~NormalizeImageSlicesFilter() {} - - void GenerateData() override; - -private: - - unsigned int m_Axis; -}; - -} - -#ifndef ITK_MANUAL_INSTANTIATION -#include "itkNormalizeImageSlicesFilter.cpp" -#endif - -#endif //__itkNormalizeImageSlicesFilter_h_ - diff --git a/Modules/DiffusionImaging/DeepDiffusion/src/itkNormalizeImageSlicesFilter.cpp b/Modules/DiffusionImaging/DeepDiffusion/src/itkNormalizeImageSlicesFilter.cpp deleted file mode 100644 index 8d1c29f649..0000000000 --- a/Modules/DiffusionImaging/DeepDiffusion/src/itkNormalizeImageSlicesFilter.cpp +++ /dev/null @@ -1,104 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#ifndef __itkNormalizeImageSlicesFilter_txx -#define __itkNormalizeImageSlicesFilter_txx - -#include "itkNormalizeImageSlicesFilter.h" -#include -#include -#include - -#include -#include - -namespace itk { - -template< class TPixelType > -NormalizeImageSlicesFilter< TPixelType > -::NormalizeImageSlicesFilter() - : m_Axis(0) -{ - this->SetNumberOfRequiredInputs( 1 ); -} - -template< class TPixelType > -void NormalizeImageSlicesFilter< TPixelType > -::GenerateData() -{ - typename InputImageType::Pointer inputImage = static_cast< InputImageType * >( this->ProcessObject::GetInput(0) ); - - typename OutputImageType::Pointer outputImage = OutputImageType::New(); - outputImage->SetSpacing( inputImage->GetSpacing() ); - outputImage->SetOrigin( inputImage->GetOrigin() ); - outputImage->SetDirection( inputImage->GetDirection() ); - outputImage->SetRegions( inputImage->GetLargestPossibleRegion() ); - outputImage->Allocate(); - this->SetNthOutput(0, outputImage); - - typename InputImageType::SizeType size = inputImage->GetLargestPossibleRegion().GetSize(); - - int slices = size[m_Axis]; - int ax = (m_Axis+1)%3; - int ay = (m_Axis+2)%3; - int sx = size[ax]; - int sy = size[ay]; - -#pragma omp parallel for - for (int i=0; iGetPixel(idx); - } - mean /= sx*sy; - - for (int x=0; xGetPixel(idx); - - diff *= diff; - std += diff; - } - std = sqrt( std/(sx*sy) ); - if (std<0.0001) - std = 1; - - for (int x=0; xGetPixel(idx); - val -= mean; - val /= std; - outputImage->SetPixel(idx, val); - } - } -} - -} -#endif diff --git a/Modules/DiffusionImaging/DeepDiffusion/src/mitkDeepDiffusionModuleActivator.cpp b/Modules/DiffusionImaging/DeepDiffusion/src/mitkDeepDiffusionModuleActivator.cpp deleted file mode 100644 index 10f12a856f..0000000000 --- a/Modules/DiffusionImaging/DeepDiffusion/src/mitkDeepDiffusionModuleActivator.cpp +++ /dev/null @@ -1,43 +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 - -namespace mitk -{ - /** - \brief Registers services for DeepDiffusion module. - */ - class DeepDiffusionModuleActivator : public us::ModuleActivator - { - public: - - void Load(us::ModuleContext* /*context*/) override - { - - } - - void Unload(us::ModuleContext*) override - { - - } - - private: - - - }; -} - -US_EXPORT_MODULE_ACTIVATOR(mitk::DeepDiffusionModuleActivator)