From 5a68cc0dbecb12e461cc9939b8ade1d25f5e9f31 Mon Sep 17 00:00:00 2001 From: Alessandro Bria Date: Tue, 8 Mar 2016 15:06:38 +0100 Subject: [PATCH] Vaa3D v3.131 / TeraFly version 2.1.41 - Dev: added TeraStitcher submodule --- .gitmodules | 3 + v3d_main/terafly/CMakeLists.txt | 58 +- v3d_main/terafly/changelog.txt | 6 + v3d_main/terafly/src/control/CConverter.h | 2 +- v3d_main/terafly/src/control/CPlugin.cpp | 2 +- v3d_main/terafly/src/control/CPlugin.h | 9 + .../terafly/src/core/crossmips/CMakeLists.txt | 9 - .../terafly/src/core/crossmips/CrossMIPs.h | 112 - .../src/core/crossmips/compute_funcs.cpp | 822 ----- .../src/core/crossmips/compute_funcs.h | 115 - .../src/core/crossmips/libcrossmips.cpp | 438 --- v3d_main/terafly/src/core/crossmips/my_defs.h | 68 - .../src/core/imagemanager/BDVVolume.cpp | 210 -- .../terafly/src/core/imagemanager/BDVVolume.h | 100 - .../src/core/imagemanager/CMakeLists.txt | 30 - .../src/core/imagemanager/HDF5Mngr.cpp | 1002 ------ .../terafly/src/core/imagemanager/HDF5Mngr.h | 118 - .../src/core/imagemanager/IM_config.cpp | 43 - .../terafly/src/core/imagemanager/IM_config.h | 467 --- .../src/core/imagemanager/ProgressBar.h | 76 - .../src/core/imagemanager/RawFmtMngr.cpp | 1508 --------- .../src/core/imagemanager/RawFmtMngr.h | 321 -- .../src/core/imagemanager/RawVolume.cpp | 274 -- .../terafly/src/core/imagemanager/RawVolume.h | 90 - .../src/core/imagemanager/SimpleVolume.cpp | 463 --- .../src/core/imagemanager/SimpleVolume.h | 72 - .../src/core/imagemanager/SimpleVolumeRaw.cpp | 414 --- .../src/core/imagemanager/SimpleVolumeRaw.h | 76 - .../terafly/src/core/imagemanager/Stack.cpp | 447 --- .../terafly/src/core/imagemanager/Stack.h | 109 - .../src/core/imagemanager/StackRaw.cpp | 431 --- .../terafly/src/core/imagemanager/StackRaw.h | 103 - .../src/core/imagemanager/StackedVolume.cpp | 1178 ------- .../src/core/imagemanager/StackedVolume.h | 144 - .../src/core/imagemanager/Tiff3DMngr.cpp | 554 ---- .../src/core/imagemanager/Tiff3DMngr.h | 130 - .../src/core/imagemanager/TiledMCVolume.cpp | 992 ------ .../src/core/imagemanager/TiledMCVolume.h | 158 - .../src/core/imagemanager/TiledVolume.cpp | 1369 -------- .../src/core/imagemanager/TiledVolume.h | 166 - .../src/core/imagemanager/TimeSeries.cpp | 307 -- .../src/core/imagemanager/TimeSeries.h | 55 - .../core/imagemanager/UnstitchedVolume.cpp | 605 ---- .../src/core/imagemanager/UnstitchedVolume.h | 114 - .../src/core/imagemanager/VirtualFmtMngr.cpp | 315 -- .../src/core/imagemanager/VirtualFmtMngr.h | 200 -- .../src/core/imagemanager/VirtualVolume.cpp | 1211 ------- .../src/core/imagemanager/VirtualVolume.h | 322 -- .../src/core/imagemanager/dirent_win.h | 230 -- .../terafly/src/core/imagemanager/imBlock.cpp | 495 --- .../terafly/src/core/imagemanager/imBlock.h | 108 - .../src/core/imagemanager/imProgressBar.cpp | 136 - .../terafly/src/core/iomanager/CMakeLists.txt | 62 - .../terafly/src/core/iomanager/IOPluginAPI.h | 659 ---- .../src/core/iomanager/ProgressBar.cpp | 103 - .../terafly/src/core/iomanager/ProgressBar.h | 63 - .../src/core/iomanager/iomanager.config.cpp | 52 - .../src/core/iomanager/iomanager.config.h | 259 -- .../terafly/src/core/iomanager/ioplugins.h | 3 - .../plugins/exampleplugin2D/CMakeLists.txt | 12 - .../exampleplugin2D/exampleplugin2D.cpp | 186 -- .../plugins/exampleplugin2D/exampleplugin2D.h | 9 - .../iomanager/plugins/opencv2D/CMakeLists.txt | 20 - .../iomanager/plugins/opencv2D/opencv2D.cpp | 481 --- .../iomanager/plugins/opencv2D/opencv2D.h | 8 - .../iomanager/plugins/tiff2D/CMakeLists.txt | 22 - .../core/iomanager/plugins/tiff2D/tiff2D.cpp | 570 ---- .../core/iomanager/plugins/tiff2D/tiff2D.h | 8 - .../iomanager/plugins/tiff3D/CMakeLists.txt | 22 - .../core/iomanager/plugins/tiff3D/tiff3D.cpp | 382 --- .../core/iomanager/plugins/tiff3D/tiff3D.h | 8 - .../terafly/src/core/stitcher/CMakeLists.txt | 22 - .../src/core/stitcher/Displacement.cpp | 106 - .../terafly/src/core/stitcher/Displacement.h | 105 - .../src/core/stitcher/DisplacementMIPNCC.cpp | 367 --- .../src/core/stitcher/DisplacementMIPNCC.h | 93 - .../terafly/src/core/stitcher/MergeTiles.cpp | 1237 -------- v3d_main/terafly/src/core/stitcher/PDAlgo.cpp | 48 - v3d_main/terafly/src/core/stitcher/PDAlgo.h | 68 - .../src/core/stitcher/PDAlgoMIPNCC.cpp | 109 - .../terafly/src/core/stitcher/PDAlgoMIPNCC.h | 53 - v3d_main/terafly/src/core/stitcher/S_config.h | 88 - .../src/core/stitcher/StackRestorer.cpp | 625 ---- .../terafly/src/core/stitcher/StackRestorer.h | 89 - .../src/core/stitcher/StackStitcher.cpp | 1754 ----------- .../terafly/src/core/stitcher/StackStitcher.h | 350 --- v3d_main/terafly/src/core/stitcher/TPAlgo.cpp | 56 - v3d_main/terafly/src/core/stitcher/TPAlgo.h | 57 - .../terafly/src/core/stitcher/TPAlgoMST.cpp | 268 -- .../terafly/src/core/stitcher/TPAlgoMST.h | 64 - .../terafly/src/core/stitcher/resumer.cpp | 209 -- v3d_main/terafly/src/core/stitcher/resumer.h | 47 - .../terafly/src/core/tinyxml/CMakeLists.txt | 6 - v3d_main/terafly/src/core/tinyxml/tinystr.cpp | 116 - v3d_main/terafly/src/core/tinyxml/tinystr.h | 319 -- v3d_main/terafly/src/core/tinyxml/tinyxml.cpp | 1839 ----------- v3d_main/terafly/src/core/tinyxml/tinyxml.h | 1799 ----------- .../terafly/src/core/tinyxml/tinyxmlerror.cpp | 52 - .../src/core/tinyxml/tinyxmlparser.cpp | 1635 ---------- .../src/core/volumeconverter/CMakeLists.txt | 12 - .../src/core/volumeconverter/S_config.h | 36 - .../core/volumeconverter/VolumeConverter.cpp | 2775 ----------------- .../core/volumeconverter/VolumeConverter.h | 262 -- .../src/core/volumeconverter/dirent_win.h | 230 -- .../src/core/volumemanager/CMakeLists.txt | 14 - .../src/core/volumemanager/dirent_win.h | 230 -- .../src/core/volumemanager/vmBlock.cpp | 988 ------ .../terafly/src/core/volumemanager/vmBlock.h | 116 - .../src/core/volumemanager/vmBlockVolume.cpp | 1235 -------- .../src/core/volumemanager/vmBlockVolume.h | 127 - .../src/core/volumemanager/vmStack.cpp | 761 ----- .../terafly/src/core/volumemanager/vmStack.h | 101 - .../core/volumemanager/vmStackedVolume.cpp | 1600 ---------- .../src/core/volumemanager/vmStackedVolume.h | 135 - .../src/core/volumemanager/vmVirtualStack.cpp | 119 - .../src/core/volumemanager/vmVirtualStack.h | 197 -- .../core/volumemanager/vmVirtualVolume.cpp | 272 -- .../src/core/volumemanager/vmVirtualVolume.h | 247 -- .../volumemanager/volumemanager.config.cpp | 51 - .../core/volumemanager/volumemanager.config.h | 350 --- .../terafly/src/presentation/PConverter.cpp | 15 +- .../terafly/src/presentation/PConverter.h | 13 +- v3d_main/terafly/src/presentation/PMain.cpp | 163 +- v3d_main/terafly/src/terarepo | 1 + v3d_main/terafly/teramanager.pro | 223 +- v3d_main/v3d/v3d_version_info.cpp | 2 +- 126 files changed, 183 insertions(+), 41389 deletions(-) create mode 100644 .gitmodules delete mode 100644 v3d_main/terafly/src/core/crossmips/CMakeLists.txt delete mode 100644 v3d_main/terafly/src/core/crossmips/CrossMIPs.h delete mode 100644 v3d_main/terafly/src/core/crossmips/compute_funcs.cpp delete mode 100644 v3d_main/terafly/src/core/crossmips/compute_funcs.h delete mode 100644 v3d_main/terafly/src/core/crossmips/libcrossmips.cpp delete mode 100644 v3d_main/terafly/src/core/crossmips/my_defs.h delete mode 100755 v3d_main/terafly/src/core/imagemanager/BDVVolume.cpp delete mode 100644 v3d_main/terafly/src/core/imagemanager/BDVVolume.h delete mode 100644 v3d_main/terafly/src/core/imagemanager/CMakeLists.txt delete mode 100755 v3d_main/terafly/src/core/imagemanager/HDF5Mngr.cpp delete mode 100755 v3d_main/terafly/src/core/imagemanager/HDF5Mngr.h delete mode 100644 v3d_main/terafly/src/core/imagemanager/IM_config.cpp delete mode 100644 v3d_main/terafly/src/core/imagemanager/IM_config.h delete mode 100644 v3d_main/terafly/src/core/imagemanager/ProgressBar.h delete mode 100644 v3d_main/terafly/src/core/imagemanager/RawFmtMngr.cpp delete mode 100644 v3d_main/terafly/src/core/imagemanager/RawFmtMngr.h delete mode 100644 v3d_main/terafly/src/core/imagemanager/RawVolume.cpp delete mode 100644 v3d_main/terafly/src/core/imagemanager/RawVolume.h delete mode 100644 v3d_main/terafly/src/core/imagemanager/SimpleVolume.cpp delete mode 100644 v3d_main/terafly/src/core/imagemanager/SimpleVolume.h delete mode 100644 v3d_main/terafly/src/core/imagemanager/SimpleVolumeRaw.cpp delete mode 100644 v3d_main/terafly/src/core/imagemanager/SimpleVolumeRaw.h delete mode 100644 v3d_main/terafly/src/core/imagemanager/Stack.cpp delete mode 100644 v3d_main/terafly/src/core/imagemanager/Stack.h delete mode 100644 v3d_main/terafly/src/core/imagemanager/StackRaw.cpp delete mode 100644 v3d_main/terafly/src/core/imagemanager/StackRaw.h delete mode 100644 v3d_main/terafly/src/core/imagemanager/StackedVolume.cpp delete mode 100644 v3d_main/terafly/src/core/imagemanager/StackedVolume.h delete mode 100644 v3d_main/terafly/src/core/imagemanager/Tiff3DMngr.cpp delete mode 100644 v3d_main/terafly/src/core/imagemanager/Tiff3DMngr.h delete mode 100644 v3d_main/terafly/src/core/imagemanager/TiledMCVolume.cpp delete mode 100644 v3d_main/terafly/src/core/imagemanager/TiledMCVolume.h delete mode 100644 v3d_main/terafly/src/core/imagemanager/TiledVolume.cpp delete mode 100644 v3d_main/terafly/src/core/imagemanager/TiledVolume.h delete mode 100644 v3d_main/terafly/src/core/imagemanager/TimeSeries.cpp delete mode 100644 v3d_main/terafly/src/core/imagemanager/TimeSeries.h delete mode 100755 v3d_main/terafly/src/core/imagemanager/UnstitchedVolume.cpp delete mode 100755 v3d_main/terafly/src/core/imagemanager/UnstitchedVolume.h delete mode 100644 v3d_main/terafly/src/core/imagemanager/VirtualFmtMngr.cpp delete mode 100644 v3d_main/terafly/src/core/imagemanager/VirtualFmtMngr.h delete mode 100644 v3d_main/terafly/src/core/imagemanager/VirtualVolume.cpp delete mode 100644 v3d_main/terafly/src/core/imagemanager/VirtualVolume.h delete mode 100644 v3d_main/terafly/src/core/imagemanager/dirent_win.h delete mode 100644 v3d_main/terafly/src/core/imagemanager/imBlock.cpp delete mode 100644 v3d_main/terafly/src/core/imagemanager/imBlock.h delete mode 100644 v3d_main/terafly/src/core/imagemanager/imProgressBar.cpp delete mode 100644 v3d_main/terafly/src/core/iomanager/CMakeLists.txt delete mode 100644 v3d_main/terafly/src/core/iomanager/IOPluginAPI.h delete mode 100644 v3d_main/terafly/src/core/iomanager/ProgressBar.cpp delete mode 100644 v3d_main/terafly/src/core/iomanager/ProgressBar.h delete mode 100644 v3d_main/terafly/src/core/iomanager/iomanager.config.cpp delete mode 100644 v3d_main/terafly/src/core/iomanager/iomanager.config.h delete mode 100644 v3d_main/terafly/src/core/iomanager/ioplugins.h delete mode 100644 v3d_main/terafly/src/core/iomanager/plugins/exampleplugin2D/CMakeLists.txt delete mode 100644 v3d_main/terafly/src/core/iomanager/plugins/exampleplugin2D/exampleplugin2D.cpp delete mode 100644 v3d_main/terafly/src/core/iomanager/plugins/exampleplugin2D/exampleplugin2D.h delete mode 100644 v3d_main/terafly/src/core/iomanager/plugins/opencv2D/CMakeLists.txt delete mode 100644 v3d_main/terafly/src/core/iomanager/plugins/opencv2D/opencv2D.cpp delete mode 100644 v3d_main/terafly/src/core/iomanager/plugins/opencv2D/opencv2D.h delete mode 100644 v3d_main/terafly/src/core/iomanager/plugins/tiff2D/CMakeLists.txt delete mode 100644 v3d_main/terafly/src/core/iomanager/plugins/tiff2D/tiff2D.cpp delete mode 100755 v3d_main/terafly/src/core/iomanager/plugins/tiff2D/tiff2D.h delete mode 100644 v3d_main/terafly/src/core/iomanager/plugins/tiff3D/CMakeLists.txt delete mode 100644 v3d_main/terafly/src/core/iomanager/plugins/tiff3D/tiff3D.cpp delete mode 100755 v3d_main/terafly/src/core/iomanager/plugins/tiff3D/tiff3D.h delete mode 100644 v3d_main/terafly/src/core/stitcher/CMakeLists.txt delete mode 100644 v3d_main/terafly/src/core/stitcher/Displacement.cpp delete mode 100644 v3d_main/terafly/src/core/stitcher/Displacement.h delete mode 100644 v3d_main/terafly/src/core/stitcher/DisplacementMIPNCC.cpp delete mode 100644 v3d_main/terafly/src/core/stitcher/DisplacementMIPNCC.h delete mode 100644 v3d_main/terafly/src/core/stitcher/MergeTiles.cpp delete mode 100644 v3d_main/terafly/src/core/stitcher/PDAlgo.cpp delete mode 100644 v3d_main/terafly/src/core/stitcher/PDAlgo.h delete mode 100644 v3d_main/terafly/src/core/stitcher/PDAlgoMIPNCC.cpp delete mode 100644 v3d_main/terafly/src/core/stitcher/PDAlgoMIPNCC.h delete mode 100644 v3d_main/terafly/src/core/stitcher/S_config.h delete mode 100644 v3d_main/terafly/src/core/stitcher/StackRestorer.cpp delete mode 100644 v3d_main/terafly/src/core/stitcher/StackRestorer.h delete mode 100644 v3d_main/terafly/src/core/stitcher/StackStitcher.cpp delete mode 100644 v3d_main/terafly/src/core/stitcher/StackStitcher.h delete mode 100644 v3d_main/terafly/src/core/stitcher/TPAlgo.cpp delete mode 100644 v3d_main/terafly/src/core/stitcher/TPAlgo.h delete mode 100644 v3d_main/terafly/src/core/stitcher/TPAlgoMST.cpp delete mode 100644 v3d_main/terafly/src/core/stitcher/TPAlgoMST.h delete mode 100644 v3d_main/terafly/src/core/stitcher/resumer.cpp delete mode 100644 v3d_main/terafly/src/core/stitcher/resumer.h delete mode 100644 v3d_main/terafly/src/core/tinyxml/CMakeLists.txt delete mode 100644 v3d_main/terafly/src/core/tinyxml/tinystr.cpp delete mode 100644 v3d_main/terafly/src/core/tinyxml/tinystr.h delete mode 100644 v3d_main/terafly/src/core/tinyxml/tinyxml.cpp delete mode 100644 v3d_main/terafly/src/core/tinyxml/tinyxml.h delete mode 100644 v3d_main/terafly/src/core/tinyxml/tinyxmlerror.cpp delete mode 100644 v3d_main/terafly/src/core/tinyxml/tinyxmlparser.cpp delete mode 100755 v3d_main/terafly/src/core/volumeconverter/CMakeLists.txt delete mode 100755 v3d_main/terafly/src/core/volumeconverter/S_config.h delete mode 100755 v3d_main/terafly/src/core/volumeconverter/VolumeConverter.cpp delete mode 100755 v3d_main/terafly/src/core/volumeconverter/VolumeConverter.h delete mode 100755 v3d_main/terafly/src/core/volumeconverter/dirent_win.h delete mode 100644 v3d_main/terafly/src/core/volumemanager/CMakeLists.txt delete mode 100644 v3d_main/terafly/src/core/volumemanager/dirent_win.h delete mode 100644 v3d_main/terafly/src/core/volumemanager/vmBlock.cpp delete mode 100644 v3d_main/terafly/src/core/volumemanager/vmBlock.h delete mode 100644 v3d_main/terafly/src/core/volumemanager/vmBlockVolume.cpp delete mode 100644 v3d_main/terafly/src/core/volumemanager/vmBlockVolume.h delete mode 100644 v3d_main/terafly/src/core/volumemanager/vmStack.cpp delete mode 100644 v3d_main/terafly/src/core/volumemanager/vmStack.h delete mode 100644 v3d_main/terafly/src/core/volumemanager/vmStackedVolume.cpp delete mode 100644 v3d_main/terafly/src/core/volumemanager/vmStackedVolume.h delete mode 100644 v3d_main/terafly/src/core/volumemanager/vmVirtualStack.cpp delete mode 100644 v3d_main/terafly/src/core/volumemanager/vmVirtualStack.h delete mode 100644 v3d_main/terafly/src/core/volumemanager/vmVirtualVolume.cpp delete mode 100644 v3d_main/terafly/src/core/volumemanager/vmVirtualVolume.h delete mode 100644 v3d_main/terafly/src/core/volumemanager/volumemanager.config.cpp delete mode 100644 v3d_main/terafly/src/core/volumemanager/volumemanager.config.h create mode 160000 v3d_main/terafly/src/terarepo diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000000..deb9ae61dd --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "v3d_main/terafly/src/terarepo"] + path = v3d_main/terafly/src/terarepo + url = https://github.com/abria/TeraStitcher.git diff --git a/v3d_main/terafly/CMakeLists.txt b/v3d_main/terafly/CMakeLists.txt index bc9f8b90ca..56852838c5 100644 --- a/v3d_main/terafly/CMakeLists.txt +++ b/v3d_main/terafly/CMakeLists.txt @@ -58,41 +58,43 @@ include_directories(${Boost_INCLUDE_DIR}) # add internal include directories include_directories(./src/presentation) include_directories(./src/control) -include_directories(./src/core/imagemanager) -include_directories(./src/core/volumeconverter) -include_directories(./src/core/volumemanager) -include_directories(./src/core/stitcher) -include_directories(./src/core/crossmips) -include_directories(./src/core/tinyxml) -include_directories(./src/core/iomanager) -include_directories(./src/core/iomanager/plugins/tiff2D) -include_directories(./src/core/iomanager/plugins/tiff3D) +include_directories(./src/terarepo/imagemanager) +include_directories(./src/terarepo/utils/volumeconverter) +include_directories(./src/terarepo/volumemanager) +include_directories(./src/terarepo/stitcher) +include_directories(./src/terarepo/crossmips) +include_directories(./src/terarepo/tinyxml) +include_directories(./src/terarepo/iomanager) +include_directories(./src/terarepo/iomanager/plugins/tiff2D) +include_directories(./src/terarepo/iomanager/plugins/tiff3D) # add internal header files file(GLOB presentation_h ./src/presentation/*.h) file(GLOB control_h ./src/control/*.h) -file(GLOB imagemanager_h ./src/core/imagemanager/*.h) -file(GLOB volumeconverter_h ./src/core/volumeconverter/*.h) -file(GLOB volumemanager_h ./src/core/volumemanager/*.h) -file(GLOB stitcher_h ./src/core/stitcher/*.h) -file(GLOB crossmips_h ./src/core/crossmips/*.h) -file(GLOB tinyxml_h ./src/core/tinyxml/*.h) -file(GLOB iomanager_h ./src/core/iomanager/*.h) -file(GLOB plugin_tiff2D_h ./src/core/iomanager/plugins/tiff2D/*.h) -file(GLOB plugin_tiff3D_h ./src/core/iomanager/plugins/tiff3D/*.h) +file(GLOB imagemanager_h ./src/terarepo/imagemanager/*.h) +file(GLOB volumeconverter_h ./src/terarepo/utils/volumeconverter/*.h) +file(GLOB volumemanager_h ./src/terarepo/volumemanager/*.h) +file(GLOB stitcher_h ./src/terarepo/stitcher/*.h) +file(GLOB crossmips_h ./src/terarepo/crossmips/*.h) +file(GLOB tinyxml_h ./src/terarepo/tinyxml/*.h) +file(GLOB iomanager_h ./src/terarepo/iomanager/*.h) +file(GLOB plugin_tiff2D_h ./src/terarepo/iomanager/plugins/tiff2D/*.h) +file(GLOB plugin_tiff3D_h ./src/terarepo/iomanager/plugins/tiff3D/*.h) +file(GLOB common_h ./src/terarepo/common/*.h) # add internal source files file(GLOB presentation_src ./src/presentation/*.cpp) file(GLOB control_src ./src/control/*.cpp) -file(GLOB imagemanager_src ./src/core/imagemanager/*.cpp) -file(GLOB volumeconverter_src ./src/core/volumeconverter/*.cpp) -file(GLOB volumemanager_src ./src/core/volumemanager/*.cpp) -file(GLOB stitcher_src ./src/core/stitcher/*.cpp) -file(GLOB crossmips_src ./src/core/crossmips/*.cpp) -file(GLOB tinyxml_src ./src/core/tinyxml/*.cpp) -file(GLOB iomanager_src ./src/core/iomanager/*.cpp) -file(GLOB plugin_tiff2D_src ./src/core/iomanager/plugins/tiff2D/*.cpp) -file(GLOB plugin_tiff3D_src ./src/core/iomanager/plugins/tiff3D/*.cpp) +file(GLOB imagemanager_src ./src/terarepo/imagemanager/*.cpp) +file(GLOB volumeconverter_src ./src/terarepo/utils/volumeconverter/*.cpp) +file(GLOB volumemanager_src ./src/terarepo/volumemanager/*.cpp) +file(GLOB stitcher_src ./src/terarepo/stitcher/*.cpp) +file(GLOB crossmips_src ./src/terarepo/crossmips/*.cpp) +file(GLOB tinyxml_src ./src/terarepo/tinyxml/*.cpp) +file(GLOB iomanager_src ./src/terarepo/iomanager/*.cpp) +file(GLOB plugin_tiff2D_src ./src/terarepo/iomanager/plugins/tiff2D/*.cpp) +file(GLOB plugin_tiff3D_src ./src/terarepo/iomanager/plugins/tiff3D/*.cpp) +file(GLOB common_src ./src/terarepo/common/*.cpp) # look for "Q_OBJECT" in headers to determine which ones to MOC message(STATUS "TeraFly: finding header files containing 'Q_OBJECT' macro...") @@ -129,6 +131,7 @@ add_library(terafly STATIC ${stitcher_src} ${crossmips_src} ${tinyxml_src} + ${common_src} ${presentation_h} ${control_h} ${imagemanager_h} @@ -140,6 +143,7 @@ add_library(terafly STATIC ${stitcher_h} ${crossmips_h} ${tinyxml_h} + ${common_h} ) target_link_libraries(terafly ${HDF5_LIBRARY} ${z_LIBRARY} ${szip_LIBRARY}) diff --git a/v3d_main/terafly/changelog.txt b/v3d_main/terafly/changelog.txt index 8bf6287474..d77e3448be 100644 --- a/v3d_main/terafly/changelog.txt +++ b/v3d_main/terafly/changelog.txt @@ -11,6 +11,12 @@ ties names are: - Rem: a feature no longer available ============================================================================================ +Vaa3D v3.131 / TeraFly version 2.1.41 +March 8th, 2016 +-------------------------------------------------------------------------------------------- +- Dev: added TeraStitcher submodule +-------------------------------------------------------------------------------------------- + Vaa3D v3.113 / TeraFly version 2.1.4 December 12th, 2015 -------------------------------------------------------------------------------------------- diff --git a/v3d_main/terafly/src/control/CConverter.h b/v3d_main/terafly/src/control/CConverter.h index 415b842d69..442bdbc647 100644 --- a/v3d_main/terafly/src/control/CConverter.h +++ b/v3d_main/terafly/src/control/CConverter.h @@ -33,7 +33,7 @@ #include #include "CPlugin.h" #include "../presentation/PConverter.h" -#include "../core/volumeconverter/VolumeConverter.h" +#include "VolumeConverter.h" class teramanager::CConverter : public QThread { diff --git a/v3d_main/terafly/src/control/CPlugin.cpp b/v3d_main/terafly/src/control/CPlugin.cpp index c84f6ccd5f..f968bfd83e 100644 --- a/v3d_main/terafly/src/control/CPlugin.cpp +++ b/v3d_main/terafly/src/control/CPlugin.cpp @@ -47,7 +47,7 @@ namespace teramanager * PARAMETERS * ******************** ---------------------------------------------------------------------------------------------------------------------------*/ - std::string version = "2.1.4"; //software version + std::string version = "2.1.41"; //software version int DEBUG = LEV_MAX; //debug level bool DEBUG_TO_FILE = false; //whether debug messages should be printed on the screen or to a file (default: screen) std::string DEBUG_FILE_PATH = "/home/alex/Scrivania/terafly_debug.log"; //filepath where to save debug information diff --git a/v3d_main/terafly/src/control/CPlugin.h b/v3d_main/terafly/src/control/CPlugin.h index c18bfdd6a1..3c5d222a4e 100644 --- a/v3d_main/terafly/src/control/CPlugin.h +++ b/v3d_main/terafly/src/control/CPlugin.h @@ -37,6 +37,7 @@ #include #include #include +#include class V3DPluginCallback2; @@ -334,6 +335,14 @@ namespace teramanager return (b - a) * step_index / static_cast(steps_number) + a; } + class Sleeper : public QThread + { + public: + static void usleep(unsigned long usecs){QThread::usleep(usecs);} + static void msleep(unsigned long msecs){QThread::msleep(msecs);} + static void sleep(unsigned long secs){QThread::sleep(secs);} + }; + //cross-platform current function macro #if defined(__GNUC__) || (defined(__MWERKS__) && (__MWERKS__ >= 0x3000)) || (defined(__ICC) && (__ICC >= 600)) # define __itm__current__function__ __PRETTY_FUNCTION__ diff --git a/v3d_main/terafly/src/core/crossmips/CMakeLists.txt b/v3d_main/terafly/src/core/crossmips/CMakeLists.txt deleted file mode 100644 index bf0487414c..0000000000 --- a/v3d_main/terafly/src/core/crossmips/CMakeLists.txt +++ /dev/null @@ -1,9 +0,0 @@ -# CmakeLists.txt in CrossMIPs dir - -# Make sure the compiler can find include files of other modules. -include_directories (${TeraStitcher_SOURCE_DIR}/IOManager) - -# Adds a library called crossmips (crossmips.a under Linux, crossmips.lib under Windows) from the all .h and .cpp files -file(GLOB crossmips_headers *.h) -file(GLOB crossmips_sources *.cpp) -add_library(crossmips STATIC ${crossmips_headers} ${crossmips_sources}) \ No newline at end of file diff --git a/v3d_main/terafly/src/core/crossmips/CrossMIPs.h b/v3d_main/terafly/src/core/crossmips/CrossMIPs.h deleted file mode 100644 index b893f99f81..0000000000 --- a/v3d_main/terafly/src/core/crossmips/CrossMIPs.h +++ /dev/null @@ -1,112 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* -* Bria, A., Iannello, G., "TeraStitcher - A Tool for Fast 3D Automatic Stitching of Teravoxel-sized Microscopy Images", (2012) BMC Bioinformatics, 13 (1), art. no. 316. -* -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -* 2015-03-20. Giulio. @ADDED in struct NCC_parms_t: wRangeThr has been splitted into three parameters (for V, H and D direntions) -*/ - -/* - * Alignements.h - * - * Created on: September 2010 - * Author: iannello - * - * Last revision: May, 31 2011 - */ - - -# ifndef ALIGNMENTS_H -# define ALIGNMENTS_H - -# define NK 0 - -// valid side values -# define NORTH_SOUTH 0 -# define WEST_EAST 1 - -# include "my_defs.h" -#include "../iomanager/iomanager.config.h" - -/***************************************** RESULT STRUCTURE ********************************************/ -typedef struct { - int coord[3]; // alignment as offset of the second stack with respect to the first one - iom::real_t NCC_maxs[3]; // reliability of alignment (-1=unreliable, 1=highly reliable) - int NCC_widths[3]; // estimate of potential error in pixels -} NCC_descr_t; - -/********************************* CONTROLLING PARAMETERS STRUCTURE ************************************/ -typedef struct { - bool enhance; // boolean flag that enabled an enhancement step before performing NCC - int maxIter; - iom::real_t maxThr; // threshold for NCC maximum (below this threshold the NCC is considered unreliable) - iom::real_t widthThr; // fraction of maximum used to evaluate the maximum width (belongs to [0,1]) - //int wRangeThr; - // ranges used to evaluate maximum width (when maximum width is greater or equal to this value, width is set to INF_W - int wRangeThr_i; // along V (rows) - int wRangeThr_j; // along H (columns) - int wRangeThr_k; // along D (slices) - iom::real_t UNR_NCC; // unreliable NCC peak value - int INF_W; // infinite NCC peak width - int INV_COORD; // invalid alignment - int n_transforms; // used only if enhance=true; number of scaled linear transformations used to enhance the MIPs - iom::real_t *percents; // used only if enhance=true; list of fractions of pixels; percents[i] is the fraction of pixels - // to be transformed with i-th transformation; percents[n_transforms-1] must be 1.00 - iom::real_t *c; // used only if enhance=true; list of values; the i-th transformations map pixels from value - // c[i-1] to value c[i] -} NCC_parms_t; - -/***************************************** MAIN FUNCTION ***********************************************/ -NCC_descr_t *norm_cross_corr_mips ( iom::real_t *A, iom::real_t *B, - int dimk, int dimi, int dimj, int nk, int ni, int nj, - int delayk, int delayi, int delayj, int side, NCC_parms_t *NCC_params = 0 ) throw (iom::exception); //Alessandro - 23/03/2013 - exceptions are thrown if preconditions do not hold -/* - * returns an alignment between volume A and B; the two volumes are assumed to have the same dimensions - * INPUT PARAMETERS: - * A: first 3D stack to be aligned - * B: second 3D stack to be aligned - * dimk: number of slices of the two stacks - * dimi: number of rows of each slice - * dimj: number of columns of each slice - * nk: initial offset between slices of second stack with respect to the first one (WARNINIG: assumed 0 by the current implementation) - * ni: initial offset between rows of second stack with respect to the first one - * nj: initial offset between columns of second stack with respect to the first one - * delayk: half range of NCC search around initial offset along third dimension - * delayi: half range of NCC search around initial offset along first dimension - * delayj: half range of NCC search around initial offset along second dimension - * side: side with respect to which alignment is computed (if it is NORTH_SOUTH A is over B, if it is WEST_EAST A is at left with respect to B) - * NCC_params: optional parameter; contains parameter values controlling the alignment strategy; default values are assumed if omitted; - * - * WARNING: 3D stacks A and B are supposed to be stored slice by slice; each slice is supposed to be stored row-wise - * WARNING: a subtle relation is assumed to hold among dimi, dimj, dimk, ni, nj, nk, delayi, delayj, delayk, and controlling - * parameter wRangeThr; in practice the dimensions of the MIPS (depending on dimi, dimj, dimk, ni, nj, nk) have - * to be large enough with respect to delayi, delayj, delayk; moreover controlling parameter wRangeThr is supposed - * to be not greater than MIN(delayi,delayj,delayk) - */ - -# endif diff --git a/v3d_main/terafly/src/core/crossmips/compute_funcs.cpp b/v3d_main/terafly/src/core/crossmips/compute_funcs.cpp deleted file mode 100644 index 443c06f777..0000000000 --- a/v3d_main/terafly/src/core/crossmips/compute_funcs.cpp +++ /dev/null @@ -1,822 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* -* Bria, A., Iannello, G., "TeraStitcher - A Tool for Fast 3D Automatic Stitching of Teravoxel-sized Microscopy Images", (2012) BMC Bioinformatics, 13 (1), art. no. 316. -* -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -* 2015-04-06. Giulio. @CHANGED corrected compute_NCC_alignment to deal with the case widthX = 1 which likely to be an anomaly -* 2015-03-20. Giulio. @CHANGED newu and newv have been moved as parameters in compute_Neighborhood -* 2014-10-31. Giulio. @CHANGED computations in compute_NCC are performed in double precision (and not in single precision) to avoit roundoff errors -*/ - -/* - * compute_funcs.cpp - * - * Created on: September 2010 - * Author: iannello - * - * Last revision: May, 31 2011 - */ - -# include -# include -# include - - -# include "compute_funcs.h" - -# define LOG2(V) (log((double)V)/log(2.0)) - - -/**************************** INTERNAL AUXILIARY FUNCTION *******************************/ - -/* search x in the sorted list (a,n) and returns if x has been found; if x is not found, - * returns in pos the index at which x should be inserted (i.e. a[pos] is the first element - * of the list that is greater than x) - * specialized for use by enhance: returns the index of the linear transformation to be - * applied to value x - */ -static -void binary_search ( iom::real_t *a, int n, iom::real_t x, bool &found, int &pos ) { - int f = 0; - int l = n-1; - int m; - - found = false; - while ( f <= l ) { - m = (f+l)/2; - if ( x == a[m] ) { - found = true; - pos = m+1; // if found, the index to be returned is the next one - return; - } - else if ( x < a[m] ) - l = m - 1; - else // V > a[m] - f = m + 1; - } - pos = l+1; - return; -} - -/* given general parameters, the NCC map, its second dimension dimj, the index of NCC maximum - * and the extension of the map along the vertical (wRangeThr1) and horizontal (wRangeThr2) directions - * returns a measure of the vertical (width1) and horizontal (width2) half widths of the NCC peak - * (i.e. the largest distance of the pixel equal to a given fraction of the maximum and the - * maximum itself) - */ -static -void compute_NCC_width ( NCC_parms_t *NCC_params, iom::real_t *NCC, int dimj, int ind, int wRangeThr1, int wRangeThr2, bool failed, int &width1, int &width2 ) { - bool found; - - iom::real_t thr = NCC_params->widthThr * NCC[ind]; - - if(failed) - { - width1 = width2 = NCC_params->INF_W; - } - else - { - // evaluates first maximum width parallel to second dimension (horizontal) - found = false; - width2 = 1; - while ( width2<=wRangeThr2 && !found ) - if ( NCC[ind-width2] <= thr ) - found = true; - else - width2++; - found = false; - while ( width2<=wRangeThr2 && !found ) - if ( NCC[ind+width2] <= thr ) - found = true; - else - width2++; - if ( !found ) - width2 = NCC_params->INF_W; - - // evaluates maximum width parallel to first dimension (vertical) - found = false; - width1 = 1; - while ( width1<=wRangeThr1 && !found ) - if ( NCC[ind-width1*dimj] <= thr ) - found = true; - else - width1++; - found = false; - while ( width1<=wRangeThr1 && !found ) - if ( NCC[ind+width1*dimj] <= thr ) - found = true; - else - width1++; - if ( !found ) - width1 = NCC_params->INF_W; - } - -} - -/*************************** COMPUTE FINAL ALIGNMENT *****************************************/ - -/* given the general parameters, the index i of a dimension (0 for vertical, 1 for horizontal - * and 2 for depth), and two alignments d1 and d2 with the corresponding NCC maxima (peak_val1 - * and peak_val2) and half widths (width1 and width2), returns in result the aligment for that - * with a measure of its reliability and potential error - * - * 2015-04-06. Giulio. The algorithm has been vcorrected as follows: - * when widthX is 1 the alignment is unreliable since it is very likely that it is due to - * a spike or a too little NCC map (e.g. because the stack is very thin); for this reason - * parametes width1 and width2 are first checked and changes if equal to 1 - */ -static -void compute_NCC_alignment ( NCC_parms_t *NCC_params, NCC_descr_t *result, int i, - int d1, iom::real_t peak_val1, int width1, int d2, iom::real_t peak_val2, int width2 ) { - - // check width1 and widthw - if ( width1 == 1 ) // alignment 1 is unreliable - width1 = NCC_params->INF_W; - if ( width2 == 1 ) // alignment 1 is unreliable - width2 = NCC_params->INF_W; - - // check how many values contribute to final alignment - if ( peak_val1 >= NCC_params->maxThr && width1 < NCC_params->INF_W ) // first value may be considered - if ( peak_val2 >= NCC_params->maxThr && width2 < NCC_params->INF_W ) // second value may be considered too - if ( abs(d1 - d2) < MIN(width1,width2) ) { // both values must be considered - result->coord[i] = (int) floor((peak_val1 * d1 + peak_val2 * d2) / (peak_val1 + peak_val2) + 0.5); // weighted mean of alignments - result->NCC_maxs[i] = (peak_val1 * peak_val1 + peak_val2 * peak_val2) / (peak_val1 + peak_val2); // weighted mean of reliabilities - result->NCC_widths[i] = MAX(width1,width2); // maximum width - } - else { // only one value should be considered: take into account both peak value and peak width - if ( peak_val1/width1 > peak_val2/width2 ) { // first value should be considered - result->coord[i] = d1; - result->NCC_maxs[i] = peak_val1; - result->NCC_widths[i] = width1; - } - else { // second value should be considered - result->coord[i] = d2; - result->NCC_maxs[i] = peak_val2; - result->NCC_widths[i] = width2; - } - } - else { // only first value should be considered - result->coord[i] = d1; - result->NCC_maxs[i] = peak_val1; - result->NCC_widths[i] = width1; - } - else - if ( peak_val2 >= NCC_params->maxThr && width2 < NCC_params->INF_W ) { // only second value should be considered - result->coord[i] = d2; - result->NCC_maxs[i] = peak_val2; - result->NCC_widths[i] = width2; - } - else { // none value is reliable - result->coord[i] = NCC_params->INV_COORD; // invalid coordinate - result->NCC_maxs[i] = NCC_params->UNR_NCC; // unreliable NCC - result->NCC_widths[i] = NCC_params->INF_W; // peak of infinite width - } -} -/****************************************************************************************/ - - - -/*********** THREADS PAREMETERS AND CODE ************/ - -# ifdef _PAR_VERSION - -# include - -// parallel configuration ------------------------------ -int n_procs = 0; -int par_degree = 0; - -void init_configuration ( ) { - fprintf(stdout,"--- PARALLEL VERSION RUNNING ---\n"); - n_procs = atoi(getenv("NUMBER_OF_PROCESSORS")); - par_degree = n_procs; -} - -// compute_3_MIPs -------------------------------------- - -typedef struct{ - // input parametres - iom::real_t *A; - iom::real_t *B; - int dimi_v; - int dimj_v; - int dimk_v; - int MIP_stridek; - int stridei; - int stridek; - // input/ouput parameters - // output parametres - iom::real_t *MIP_xy1; - iom::real_t *MIP_xz1; - iom::real_t *MIP_yz1; - iom::real_t *MIP_xy2; - iom::real_t *MIP_xz2; - iom::real_t *MIP_yz2; -} compute_3_MIPs_params_t; - -DWORD WINAPI compute_3_MIPs_worker ( LPVOID lpParam ) { - iom::real_t *A = ((compute_3_MIPs_params_t *) lpParam)->A; - iom::real_t *B = ((compute_3_MIPs_params_t *) lpParam)->B; - int dimi_v = ((compute_3_MIPs_params_t *) lpParam)->dimi_v; - int dimj_v = ((compute_3_MIPs_params_t *) lpParam)->dimj_v; - int dimk_v = ((compute_3_MIPs_params_t *) lpParam)->dimk_v; - int stridei = ((compute_3_MIPs_params_t *) lpParam)->stridei; - int stridek = ((compute_3_MIPs_params_t *) lpParam)->stridek; - int MIP_stridek = ((compute_3_MIPs_params_t *) lpParam)->MIP_stridek; - iom::real_t *MIP_xy1 = ((compute_3_MIPs_params_t *) lpParam)->MIP_xy1; - iom::real_t *MIP_xz1 = ((compute_3_MIPs_params_t *) lpParam)->MIP_xz1; - iom::real_t *MIP_yz1 = ((compute_3_MIPs_params_t *) lpParam)->MIP_yz1; - iom::real_t *MIP_xy2 = ((compute_3_MIPs_params_t *) lpParam)->MIP_xy2; - iom::real_t *MIP_xz2 = ((compute_3_MIPs_params_t *) lpParam)->MIP_xz2; - iom::real_t *MIP_yz2 = ((compute_3_MIPs_params_t *) lpParam)->MIP_yz2; - - iom::real_t *vol1, *vol2; - int i, j, k; - - // calcola MIP su xy, xz, yz scandendo una sola volta i due volumi - for ( k=0, vol1=A, vol2=B; kMIP_1; - iom::real_t *MIP_2 = ((compute_NCC_map_params_t *) lpParam)->MIP_2; - int dimu = ((compute_NCC_map_params_t *) lpParam)->dimu; - int dimv = ((compute_NCC_map_params_t *) lpParam)->dimv; - int delayu = ((compute_NCC_map_params_t *) lpParam)->delayu; - int delayv = ((compute_NCC_map_params_t *) lpParam)->delayv; - int u_start = ((compute_NCC_map_params_t *) lpParam)->u_start; - int v_start = ((compute_NCC_map_params_t *) lpParam)->v_start; - int u_end = ((compute_NCC_map_params_t *) lpParam)->u_end; - int v_end = ((compute_NCC_map_params_t *) lpParam)->v_end; - iom::real_t *NCC_map = ((compute_NCC_map_params_t *) lpParam)->NCC_map; - - iom::real_t *im1, *im2; - int u, v; - - // nel seguito u=0 rappresenta il massimo scostamento negativo del secondo MIP rispetto al primo - // con riferimento alla prima coordinata; v=0 ha il medesimo significato con riferimento alla seconda - // coordinata - for ( u=u_start; u<=u_end; u++ ) - for ( v=v_start; v<=v_end; v++ ) { - im1 = MIP_1 + START_IND(u*dimv) + START_IND(v); - im2 = MIP_2 + START_IND(-u*dimv) + START_IND(-v); - NCC_map[(u+delayu)*(2*delayv+1)+(v+delayv)] = compute_NCC(im1,im2,dimu-abs(u),dimv-abs(v),abs(v)); - } - - return 0; -} - -# endif - - -/************ OPERATIONS IMPLEMENTATION *************/ - -void compute_3_MIPs ( iom::real_t *A, iom::real_t *B, - iom::real_t *MIP_xy1, iom::real_t *MIP_xz1, iom::real_t *MIP_yz1, - iom::real_t *MIP_xy2, iom::real_t *MIP_xz2, iom::real_t *MIP_yz2, - int dimi_v, int dimj_v, int dimk_v, int stridei, int stridek ) { -# ifndef _PAR_VERSION - - iom::real_t *vol1, *vol2; - int i, j, k; - - // calcola MIP su xy, xz, yz scandendo una sola volta i due volumi - for ( k=0, vol1=A, vol2=B; k - * slice_dim = (dimi - ni) * dimj + ni * dimj = dimi * dimj - * - * case WEST_EAST: - * dimi_v = dimi - * dimj_v = dimj - nj - * stridei = nj - * stridek = 0 ====> - * slice_dim = dimi * ( dimj - nj + nj) + 0 = dimi * dimj - */ - int depth = 0; - for ( t=0; t val_max ) { - val_max = vect[i]; - ind_max = i; - } - return ind_max; -} - - -void compute_Neighborhood ( NCC_parms_t *NCC_params, iom::real_t *NCC, int delayu, int delayv, int newu, int newv, int ind_max, - iom::real_t *MIP_1, iom::real_t *MIP_2, int dimu, int dimv, iom::real_t *NCCnew, int &du, int &dv, bool &failed) throw (iom::exception){ - - // suffixes u and v denote the vertical and the horizontal dimensions, respectively - // suffix i denotes linear indices - - int u, v, i, d; // for variables - - // 2015-03-20. Giulio. @CHANGED newu and newv are moved as parameters - //int newu = NCC_params->wRangeThr; // vertical half dimension of NCCnew - //int newv = NCC_params->wRangeThr; // horizontal half dimension of NCCnew - - int ind_ref; // index of the center of NCCnew - - int initu; // vertical index of first pixel of subregion of NCC to be used to initially fill NCCnew - int initv; // horizontal index of first pixel of subregion of NCC to be used to initially fill NCCnew - int initi; // linear index of first pixel of subregion of NCC to be used to initially fill NCCnew - - int srcStartu; // vertical index of first pixel of the subregion of NCCnew to be reused when current maximum is moved to the center of NCCnew - int srcStartv; // horizontal index of first pixel of the subregion of NCCnew to be reused when current maximum is moved to the center of NCCnew - int srcStarti; // linear index of first pixel of the subregion of NCCnew to be reused when current maximum is moved to the center of NCCnew - - int dstStartu; // vertical index of first pixel of the subregion of NCCnew where te subregion to be used has to be copied - int dstStartv; // horizontal index of first pixel of the subregion of NCCnew where te subregion to be used has to be copied - int dstStarti; // linear index of first pixel of the subregion of NCCnew where te subregion to be used has to be copied - - int deltau; // vertical displacement of current maximum from the center of NCCnew - int deltav; // horizontal displacement of current maximum from the center of NCCnew - - int firstv; // first horizontal index for copying elements of NCCnew to be reused - int lastv; // last horizontal index for copying elements of NCCnew to be reused - - int n_miss; // number of NCC to be computed to fill NCCnew - int *missu = new int[(2*newu+1)*(2*newv+1)]; // list of vertical indices of NCC to be computed to fill NCCnew - int *missv = new int[(2*newu+1)*(2*newv+1)]; // list of vertical indices of NCC to be computed to fill NCCnew - - iom::real_t *im1, *im2; - - // INITIALIZATION - - // fill NCCnew copying useful NCCs that have been already computed from NCC to NCCnew - initu = MIN(MAX(0,ind_max/(2*delayv+1) - newu),2*(delayu - newu)); - initv = MIN(MAX(0,ind_max%(2*delayv+1) - newv),2*(delayv - newv)); - initi = initu * (2*delayv+1) + initv; - if(initi < 0) - throw iom::exception("CrossMIPs: negative index detected (initi)"); // Alessandro - 23/03/2013 - throw exception if initi is negative - for ( u=0, i=0, d=0; u<(2*newu+1); u++, d+=2*(delayv-newv) ) // when row changes 2*(delayv-newv) values have to be skipped - for ( v=0; v<(2*newv+1); v++ , i++) - NCCnew[i] = NCC[i + initi + d]; - // compute displacement of the center of NCCnew with respect to the initial alignment (center of NCC) - du = initu - delayu + newu; // displacement of first row + half dimension of NCCnew - dv = initv - delayv + newv; // displacement of first column + half dimension of NCCnew - // update ind_max with respect to NCCnew - // contribution due to rows (integer division is not distributive) contribution due to columns - ind_max = (2*newv+1) * (ind_max/(2*delayv+1) - initi/(2*delayv+1)) + (ind_max%(2*delayv+1)) - (initi%(2*delayv+1)); - // index of the center of the new NCC - ind_ref = (2*newv+1) * newu + newv; - - // UPDATE NEIGHBORHOOD AND SEARCH MAXIMUM - - int c=1; - while ( c < NCC_params->maxIter && ind_max != ind_ref ) { - // update NCCnew - srcStartu = MAX(0,ind_max/(2*newv+1) - newu); - srcStartv = MAX(0,ind_max%(2*newv+1) - newv); - srcStarti = srcStartu * (2*newv+1) + srcStartv; - deltau = ind_max/(2*newv+1) - ind_ref/(2*newv+1); - deltav = ind_max%(2*newv+1) - ind_ref%(2*newv+1); - dstStartu = srcStartu - deltau; - dstStartv = srcStartv - deltav; - dstStarti = dstStartu * (2*newv+1) + dstStartv; - if ( srcStartu > 0 ) { // forward copy is safe - i = 0; - for ( u=0; u<((2*newu+1)-abs(deltau)); u++, i+=abs(deltav) ) // when row changes |deltav| values have to be skipped - for ( v=0; v<((2*newv+1)-abs(deltav)); v++ , i++) - NCCnew[i + dstStarti] = NCCnew[i + srcStarti]; - } - else { // srcStartu == 0 : beckward copy is safe - i=(((2*newu+1)-abs(deltau))*((2*newv+1)-abs(deltav)) - 1); - for ( u=0; u<((2*newu+1)-abs(deltau)); u++, i+=abs(deltav) ) // when row changes |deltav| values have to be skipped - for ( v=0; v<((2*newv+1)-abs(deltav)); v++ , i--) - NCCnew[i + dstStarti] = NCCnew[i + srcStarti]; - } - - // update position of the new center (current maximum) - du += deltau; - dv += deltav; - - // generate list of missing NCCs - n_miss = 0; - for ( u=0; u<(2*newu+1); u++ ) { - if ( u+deltau < 0 || u+deltau >= (2*newu+1) ) { // all this row has to be computed - firstv = 0; - lastv = 2*newv+1; - } - else { // only a fraction of the row has to be computed - if ( deltav < 0 ) { // the initial part of the row has to be computed - firstv = 0; - lastv = -deltav; - } - else if ( deltav > 0 ) { // the final part of the row has to be computed - firstv = (2*newv+1) - deltav; - lastv = 2*newv+1; - } - else { // deltav == 0: no NCCs has to be computed - firstv = 0; - lastv = 0; - } - } - for ( v=firstv; vwRangeThr_i,NCC_params->wRangeThr_j,failed_xy, w1x,w1y); - compute_NCC_width(NCC_params,NCC_xz,(2*dimk+1),(dimi*(2*dimk+1)+dimk),NCC_params->wRangeThr_i,NCC_params->wRangeThr_k,failed_xz, w2x,w1z); - compute_NCC_width(NCC_params,NCC_yz,(2*dimk+1),(dimj*(2*dimk+1)+dimk),NCC_params->wRangeThr_j,NCC_params->wRangeThr_k,failed_yz, w2y,w2z); - - compute_NCC_alignment(NCC_params,result,0,dx1,NCC_xy[(dimi*(2*dimj+1)+dimj)],w1x,dx2,NCC_xz[(dimi*(2*dimk+1)+dimk)],w2x); - compute_NCC_alignment(NCC_params,result,1,dy1,NCC_xy[(dimi*(2*dimj+1)+dimj)],w1y,dy2,NCC_yz[(dimj*(2*dimk+1)+dimk)],w2y); - compute_NCC_alignment(NCC_params,result,2,dz1,NCC_xz[(dimi*(2*dimk+1)+dimk)],w1z,dz2,NCC_yz[(dimj*(2*dimk+1)+dimk)],w2z); -} - - -void enhance ( iom::real_t *im, int imLen, int graylevels, NCC_parms_t *NCC_params ) { -/* - * the enhancement transformation is a multi-linear curve with n_transforms rescaled linear - * tranformations - * for i=0, ..., (n_transforms-1), percentiles[i] contains the fraction of pixels to which the - * (i+1)-th rescaled linear transformation has to be applied; percentiles[n_transforms-1] must be 1.00 - * for i=1, ..., n_transforms, c[i-1] amd c[i] contain the lowest and highest value corresponding to - * the the i-th rescaled linear transformation; c[0] must be 0.00 and c[n_transforms] must be 1.00 - */ - - int n_transforms = NCC_params->n_transforms; - iom::real_t *percentiles = NCC_params->percents; - iom::real_t *c = NCC_params->c; // tranformed values of thresholds - iom::real_t *thresholds = new iom::real_t[n_transforms+1]; - iom::real_t *a = new iom::real_t[n_transforms+1]; - iom::real_t *b = new iom::real_t[n_transforms+1]; - int i, j; - bool found; - - thresholds[0] = (iom::real_t)0.00; - - stack_percentiles(im,imLen,graylevels,percentiles,thresholds,n_transforms); - - for ( i=1; i<=n_transforms; i++ ) { - a[i] = (c[i] - c[i-1]) / (thresholds[i] - thresholds[i-1]); - b[i] = c[i] - a[i]*thresholds[i]; - } - - for ( i=0; i= percentiles[j-1] ) { - thresholds[j] = d * i; - j++; - } - else - i++; - } - thresholds[n_percentiles] = (iom::real_t)1; // to avoid round off errors - - delete cumsum; -} diff --git a/v3d_main/terafly/src/core/crossmips/compute_funcs.h b/v3d_main/terafly/src/core/crossmips/compute_funcs.h deleted file mode 100644 index b34734654c..0000000000 --- a/v3d_main/terafly/src/core/crossmips/compute_funcs.h +++ /dev/null @@ -1,115 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* -* Bria, A., Iannello, G., "TeraStitcher - A Tool for Fast 3D Automatic Stitching of Teravoxel-sized Microscopy Images", (2012) BMC Bioinformatics, 13 (1), art. no. 316. -* -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -* 2015-03-20. Giulio. @CHANGED newu and newv have been moved as parameters in compute_Neighborhood -*/ - -/* - * compute_funcs.h - * - * Created on: September 2010 - * Author: iannello - * - * Last revision: May, 31 2011 - */ - - -#ifndef COMPUTE_FUNCS_H -#define COMPUTE_FUNCS_H - - -# include "my_defs.h" - -# include "CrossMIPs.h" - - -# define GRAY_LEVELS 65536 - - -void compute_3_MIPs ( iom::real_t *A, iom::real_t *B, - iom::real_t *MIP_xy1, iom::real_t *MIP_xz1, iom::real_t *MIP_yz1, - iom::real_t *MIP_xy2, iom::real_t *MIP_xz2, iom::real_t *MIP_yz2, - int dimi_v, int dimj_v, int dimk_v, int stridei, int stridek ); - -void compute_NCC_map ( iom::real_t *NCC_map, iom::real_t *MIP_1, iom::real_t *MIP_2, - int dimu, int dimv, int delayu, int delayv ); - -iom::real_t compute_NCC ( iom::real_t *im1, iom::real_t *im2, int dimi, int dimj, int stride ); - -int compute_MAX_ind ( iom::real_t *vect, int len ); - -void compute_Neighborhood ( NCC_parms_t *NCC_params, iom::real_t *NCC, int delayu, int delayv, int newu, int newv, int ind, - iom::real_t *MIP_1, iom::real_t *MIP_2, int dimu, int dimv, iom::real_t *NCCnew, int &du, int &dv, bool &failed) throw (iom::exception); -/* given an NCC map with dimensions delayu x delayv around the initial alignment, extensions newu and newu - * of the new NCC map, the index ind of its maximum and an empty NCC map NCCnew with dimensions NCC_params->wRangeThr x NCC_params->wRangeThr, - * returns in NCCnew the NCC map with center in the NCC maximum of MIPs MIP_1 and MIP_2, with dimensions dimu x dimv; - * also returns the position (du,dv) of this maximum, relative to the initial alignment - */ - -//void compute_Alignment( NCC_parms_t *NCC_params, REAL_T *NCC_xy, REAL_T *NCC_xz, REAL_T *NCC_yz, -// int dimi, int dimj, int dimk, int ind_xy, int ind_xz, int ind_yz, NCC_descr_t *result); -void compute_Alignment( NCC_parms_t *NCC_params, iom::real_t *NCC_xy, iom::real_t *NCC_xz, iom::real_t *NCC_yz, - int dimi, int dimj, int dimk, int dx1, int dx2, int dy1, int dy2, int dz1, int dz2, bool failed_xy, bool failed_xz, bool failed_yz, NCC_descr_t *result); -/* given the three NCCs, the corresponding indices of NCC maxima and their displacements with respect to the - * initial alignment, returns in the parameter result the three alignments and the corresponding reliability indices; - * alignments represent offsets of the second stack with respect to the first one - */ - -void enhance ( iom::real_t *im, int imLen, int graylevels, NCC_parms_t *NCC_params ); -/* enhance contrast of an image - * INPUT parameters: - * im is a pointer to actual pixels, represented as a linear sequence of length imLen - * graylevels is the number of discrete gray levels to be used to discriminate pixels for - * enhancement - * NCC_params contains data describing the transformation used for enhancement (see - * CrossMIPs.h for details) - */ - -void stack_percentiles ( iom::real_t *im, int imLen, int graylevels, - iom::real_t *percentiles, iom::real_t *thresholds, int n_percentiles ); -/* returns thresholds on pixel values to implement an arbitrary grayscale transformation - * INPUT parameters: - * im is a pointer to actual pixels represented as a linear sequence of length imLen - * percentiles is a pointer to an array of n_percentiles real values representing - * the percentiles of pixels to which the i-th rescaled linear transformation has - * to be applied (i=1,...,n_percentiles) - * INPUT/OUTPUT parmeter: - * thresholds is a pointer to an array of (n_percentiles+1) real values representing the - * pixel values interval to which the i-th linear transformation has to be applied - * (i=1,...,n_percentiles) - * PRE: the value of percentiles[n_percentiles-1] must be (REAL_T)1.0 - * the value of threshold[0] must be 0 - */ - -# ifdef _PAR_VERSION -void init_configuration ( ); -# endif - -# endif diff --git a/v3d_main/terafly/src/core/crossmips/libcrossmips.cpp b/v3d_main/terafly/src/core/crossmips/libcrossmips.cpp deleted file mode 100644 index 3fb4616a49..0000000000 --- a/v3d_main/terafly/src/core/crossmips/libcrossmips.cpp +++ /dev/null @@ -1,438 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* -* Bria, A., Iannello, G., "TeraStitcher - A Tool for Fast 3D Automatic Stitching of Teravoxel-sized Microscopy Images", (2012) BMC Bioinformatics, 13 (1), art. no. 316. -* -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -* 2015-03-20. Giulio. @CHANGED different dimensions for the new NCC to be computed are passed to compute_Neighborhood -* 2015-03-20. Giulio. @CHANGED newu and newv have been moved as parameters in compute_Neighborhood -*/ - -/* - * libcrossmips.cpp - * - * Created on: September 2010 - * Author: iannello - * - * Last revision: May, 31 2011 - * - * --- revision of May, 31 2011 ------------------------------------------------------------------- - * Parameters can be controlled through a structure defined in CrossMIPs.h which can be - * passed as a parameter to norm_cross_corr_mips - * Default values are set in implementation of norm_cross_corr_mips - * - * A structure is returned containing the thre offsets of the second 3d stack with respect to - * the first one. The structure is defined in CrossMIPs.h and it contains also information - * about the reliability and precision of the alignement. Reliability of each offset is measured - * by the value of the NCC maxima used to evaluate it. Precision is measured by the distance - * between NCC maxima and pixels equal to a given fraction of the maxima in the direction of - * each offset. The algorithm used to determine all these quantities is in function - * compute_NCC_alignment, which is internal to the file compute_funcs.cpp - * ---------------------------------------------------------------------------------------------- - */ - - -# include -# include -# include - -# include "CrossMIPs.h" - -# include "compute_funcs.h" - -// 2014-11-04 Giulio. @ADDED improved the conditionally compiled code thaa can be used to save images involved in NCC - -/* Flag _WRITE_IMGS enables the saving of MIPs and NCCs - * Flag _WRITE_STKS enables the saving of the input substacks too - */ - -#ifdef _WRITE_IMGS -# include - -# define _MAX_FNAME_LEN 1000 -# define _PREFIX_LEN 8 // digits used to generate unique file names -# define _MAX_COUNTER 100000000 // max counter value must be 10^(_PREFIX_LEN) - 1 - -// used to generate unique identifiers for image files -static int _counter = 0; -# endif - - -bool write_3D_stack ( char *fname, iom::real_t *stck, int dimi, int dimj, int dimk ); - - -NCC_descr_t *norm_cross_corr_mips ( iom::real_t *A, iom::real_t *B, - int dimk, int dimi, int dimj, int nk, int ni, int nj, - int delayk, int delayi, int delayj, int side, NCC_parms_t *NCC_params ) throw (iom::exception){ -#if CM_VERBOSE > 1 - printf("\nin libcrossmips::norm_cross_corr_mips(A[%.6f-%.6f], B[%.6f-%.6f], dimk[%d], dimi[%d], dimj[%d], nk[%d], ni[%d], nj[%d], delayk[%d], delayi[%d], delayj[%d], side[%d]\n", - A[0], A[(dimk-1)*dimj*dimi + (dimi-1)*dimj + dimj -1], B[0], B[(dimk-1)*dimj*dimi + (dimi-1)*dimj + dimj -1], dimk, dimi, dimj, nk, ni, nj, delayk, delayi, delayj, side ); -#endif - -#ifdef _WRITE_IMGS - char _fname[_MAX_FNAME_LEN]; // used ti assemble file manes - if ( _counter < _MAX_COUNTER ) - sprintf(_fname,"%08d",_counter); // WARNING: check the format string; the number of digits must be _PREFIX_LEN - else - throw iom::exception("CrossMIPs (_WRITE_IMGS enabled): too much substacks"); - _counter++; - -#ifdef _WRITE_STKS - write_3D_stack(strcpy(_fname+_PREFIX_LEN,"_STCK_A.dat")-_PREFIX_LEN,A,dimi,dimj,dimk); - write_3D_stack(strcpy(_fname+_PREFIX_LEN,"_STCK_B.dat")-_PREFIX_LEN,B,dimi,dimj,dimk); -#endif -#endif - - NCC_descr_t *result = new NCC_descr_t; - int dimk_v, dimi_v, dimj_v; - int stridei, stridek; // arrays are stored along j dimension, hence it does not need a stride - iom::real_t *A1; // starting pixels of volume A to be scanned - - iom::real_t *MIP_xy1, *MIP_xz1, *MIP_yz1; - iom::real_t *MIP_xy2, *MIP_xz2, *MIP_yz2; - int i; - - iom::real_t *NCC_xy, *NCC_xz, *NCC_yz; - - iom::real_t *temp; - - int ind_xy, ind_xz, ind_yz; - int dx1, dx2, dy1, dy2, dz1, dz2; - - bool failed_xy=false, failed_xz=false, failed_yz=false; - - bool allocated = !NCC_params; - if ( !NCC_params ) { - - // Alessandro - 31/05/2013 - parameter MUST be passed (and controlled) by the caller - throw iom::exception("CrossMIPs: missing configuration parameters"); - - //// ************************** SET DEFAULT PARAMETERS **************** - //NCC_params = new NCC_parms_t; - //// to change default behavior change the following parameters - //NCC_params->enhance = false; - //NCC_params->maxIter = 2; - //NCC_params->maxThr = CM_DEF_MAX_THR; - //NCC_params->widthThr = CM_DEF_WIDTH_THR; - //NCC_params->wRangeThr = CM_DEF_W_RANGE_THR; - //NCC_params->UNR_NCC = CM_DEF_UNR_NCC; - //NCC_params->INF_W = CM_DEF_INF_W; - //NCC_params->INV_COORD = 0; - - ///* Example of settings for fields 'percents' and 'c' - // * percents = < 0.1, 0.9, 1.0 > and c = < 0.0, 0,0, 1.0, 1.0 > - // * means that: - // * - 10% of pixels with lower values are set to 0 (first transformation maps pixels from c[0]=0.0 to c[1]=0.0 - // * - 10% of pixels with higher values are set to 1 (third transformation maps pixels from c[2]=1.0 to c[3]=1.0 - // * - 80% of pixels with intermediate values are mapped to the interval [0,1] (second transformation maps pixels - // * from c[1]=0.0 to c[2]01.0 - // */ - - //if ( enhance ) { - // //// two transformations defined by pairs (percentiles,value): {(0.0,0.0),(0.8,0.2),(1.0,1.0)} - // //NCC_params->n_transforms = 2; - // //NCC_params->percents = new REAL_T[NCC_params->n_transforms]; - // //NCC_params->c = new REAL_T[NCC_params->n_transforms+1]; - // //// percents must have n_transforms elements and percents[n_transforms-1] must be 1.00 - // //NCC_params->percents[0] = (REAL_T) 0.80; - // //NCC_params->percents[1] = (REAL_T) 1.00; - // //// c must have (n_transforms+1) elements, c[0] must be 0.00 and c[n_transforms] must be 1.00 - // //NCC_params->c[0] = (REAL_T) 0.00; - // //NCC_params->c[1] = (REAL_T) 0.20; - // //NCC_params->c[2] = (REAL_T) 1.00; - - // // three transformations defined by pairs (percentiles,value): {(0.0,0.0),(0.1,0.0),(0.95,1.0),(1.0,1.0)} - // NCC_params->n_transforms = 3; - // NCC_params->percents = new iom::real_t[NCC_params->n_transforms]; - // NCC_params->c = new iom::real_t[NCC_params->n_transforms+1]; - // // percents must have n_transforms elements and percents[n_transforms-1] must be 1.00 - // NCC_params->percents[0] = (iom::real_t) 0.10; - // NCC_params->percents[1] = (iom::real_t) 0.99; - // NCC_params->percents[2] = (iom::real_t) 1.00; - // // c must have (n_transforms+1) elements, c[0] must be 0.00 and c[n_transforms] must be 1.00 - // NCC_params->c[0] = (iom::real_t) 0.00; - // NCC_params->c[1] = (iom::real_t) 0.00; - // NCC_params->c[2] = (iom::real_t) 1.00; - // NCC_params->c[3] = (iom::real_t) 1.00; - //} - } - - // Alessandro - 23/03/2013 - this is the old check, but is seems wrong and it does not throw any exception. The WARNING written into - // CrossMIPs.h says: "moreover controlling parameter wRangeThr is supposed to be not greater than MAX(delayi,delayj,delayk)" - //if ( NCC_params->wRangeThr > 2*MAX(delayi,MAX(delayj,delayk))+1 ) - //{ - // char err_msg[500]; - // sprintf(err_msg, "parameter wRangeThr[=%d] is too large with respect to 2*delayi/j/k +1 [=%d]", NCC_params->wRangeThr, 2*MAX(delayi,MAX(delayj,delayk))+1); - // DISPLAY_ERROR(err_msg); - //} - - // These checks are required by the lines (in compute_funcs.cpp): - // initu = MIN(MAX(0,ind_max/(2*delayv+1) - newu),2*(delayu - newu)); - // initv = MIN(MAX(0,ind_max%(2*delayv+1) - newv),2*(delayv - newv)); - // where newu = newv = NCC_params->wRangeThr and initu, initv must be positive integers - if ( NCC_params->wRangeThr_i > delayi || NCC_params->wRangeThr_j > delayj || NCC_params->wRangeThr_k > delayk ) - { - // Alessandro - 31/05/2013 - throwing an exception instead of automatically correcting parameters - char err_msg[1000]; - sprintf(err_msg, "CrossMIPs: one or more parameters: wRangeThr_i[=%d], wRangeThr_j[=%d], wRangeThr_k[=%d] are too large with respect to: delayi[=%d], delayj[=%d], delayik[=%d]", - NCC_params->wRangeThr_i, NCC_params->wRangeThr_j, NCC_params->wRangeThr_k, delayi, delayj ,delayk); - throw iom::exception(err_msg); - } - - // skipping check for 2D images: see Alessandro's comment in PDAlgoMIPNCC.cpp on 21/08/2013 - if(dimk != 1) - { - // Alessandro - 23/03/2013 - added check to verify precondition written into CrossMIPs.h that says: - // "in practice the dimensions of the MIPS (depending on dimi, dimj, dimk, ni, nj, nk) have to be large enough with respect to delayi, delayj, delayk" - if(side == NORTH_SOUTH && ((dimi - ni < 2*delayi+1) || (dimj - nj < 2*delayj+1) || (dimk - nk < 2*delayk+1))) - throw iom::exception("CrossMIPs: the search region is too big with respect to the overlapping region. " - "Overlapping extent should be > 2*delay+1 for each direction where delay is the " - "search region extent along that direction."); - if(side == WEST_EAST && ((dimj - nj < 2*delayi+1) || (dimi - ni < 2*delayj+1) || (dimk - nk < 2*delayk+1))) - throw iom::exception("CrossMIPs: the search region is too big with respect to the overlapping region. " - "Overlapping extent should be > 2*delay+1 for each direction where delay is the " - "search region extent along that direction."); - } - - - /* - * il seguente codice assume che: - * - le matrici bidimensionali siano memorizzate secondo l'ultima dimensione - * ad esempio il MIP proiettato lungo y, che include le dimensioni x e z, e' memorizzato per - * valori di z consecutivi - * - gli stack 3D siano memorizzati per piani orizzontali e ciascun piano sia memorizzato - * come una metrice bidimensionale (secondo l'ultima dimensione); questa ipotesi ha effetto - * solo nel calcolo delle tre proiezioni MIP - */ - -# ifdef _PAR_VERSION - - init_configuration(); - -# endif - - // calcola parametri per scandire i volumi - if ( side == NORTH_SOUTH ) { - dimk_v = dimk; - dimi_v = dimi - ni; - dimj_v = dimj; - stridei = 0; // rows are entirely scanned - stridek = ni*dimj; // pixels to be skipped when changing slice are all contiguous - A1 = A + stridek; // a block of contiguous pixels of volume A have to be skipped - } - else if ( side == WEST_EAST ) { - dimk_v = dimk; - dimi_v = dimi; - dimj_v = dimj - nj; - stridei = nj; // rows are partially scanned and nj pixels have to be skipped when changing row - stridek = 0; // no more pixels have to be skipped when changing slice - A1 = A + stridei; // a partial row of pixels of volume A have to be skipped - } - else - throw iom::exception("CrossMIPs: unexpected alignment configuration"); - - // alloca le 6 immagini per i MIP - MIP_xy1 = new iom::real_t[dimi_v*dimj_v]; - for ( i=0; i<(dimi_v*dimj_v); i++ ) - MIP_xy1[i] = 0; - MIP_xz1 = new iom::real_t[dimi_v*dimk_v]; - for ( i=0; i<(dimi_v*dimk_v); i++ ) - MIP_xz1[i] = 0; - MIP_yz1 = new iom::real_t[dimj_v*dimk_v]; - for ( i=0; i<(dimj_v*dimk_v); i++ ) - MIP_yz1[i] = 0; - - MIP_xy2 = new iom::real_t[dimi_v*dimj_v]; - for ( i=0; i<(dimi_v*dimj_v); i++ ) - MIP_xy2[i] = 0; - MIP_xz2 = new iom::real_t[dimi_v*dimk_v]; - for ( i=0; i<(dimi_v*dimk_v); i++ ) - MIP_xz2[i] = 0; - MIP_yz2 = new iom::real_t[dimj_v*dimk_v]; - for ( i=0; i<(dimj_v*dimk_v); i++ ) - MIP_yz2[i] = 0; - - compute_3_MIPs(A1,B,MIP_xy1,MIP_xz1,MIP_yz1,MIP_xy2,MIP_xz2,MIP_yz2, - dimi_v,dimj_v,dimk_v,stridei,stridek); - -#ifdef _WRITE_IMGS - write_3D_stack(strcpy(_fname+_PREFIX_LEN,"_MIP_xy1.dat")-_PREFIX_LEN,MIP_xy1,dimi_v,dimj_v,1); - write_3D_stack(strcpy(_fname+_PREFIX_LEN,"_MIP_xy2.dat")-_PREFIX_LEN,MIP_xy2,dimi_v,dimj_v,1); - write_3D_stack(strcpy(_fname+_PREFIX_LEN,"_MIP_xz1.dat")-_PREFIX_LEN,MIP_xz1,dimi_v,dimk_v,1); - write_3D_stack(strcpy(_fname+_PREFIX_LEN,"_MIP_xz2.dat")-_PREFIX_LEN,MIP_xz2,dimi_v,dimk_v,1); - write_3D_stack(strcpy(_fname+_PREFIX_LEN,"_MIP_yz1.dat")-_PREFIX_LEN,MIP_yz1,dimj_v,dimk_v,1); - write_3D_stack(strcpy(_fname+_PREFIX_LEN,"_MIP_yz2.dat")-_PREFIX_LEN,MIP_yz2,dimj_v,dimk_v,1); -#endif - - // calcola NCC su xy - NCC_xy = new iom::real_t[(2*delayi+1)*(2*delayj+1)]; - for ( i=0; i<((2*delayi+1)*(2*delayj+1)); i++ ) - NCC_xy[i] = 0; - - if ( NCC_params->enhance ) { - enhance(MIP_xy1,(dimi_v*dimj_v),GRAY_LEVELS,NCC_params); - enhance(MIP_xy2,(dimi_v*dimj_v),GRAY_LEVELS,NCC_params); - } - - compute_NCC_map(NCC_xy,MIP_xy1,MIP_xy2,dimi_v,dimj_v,delayi,delayj); - - // calcola NCC su xz - NCC_xz = new iom::real_t[(2*delayi+1)*(2*delayk+1)]; - for ( i=0; i<((2*delayi+1)*(2*delayk+1)); i++ ) - NCC_xz[i] = 0; - - if ( NCC_params->enhance ) { - enhance(MIP_xz1,(dimi_v*dimk_v),GRAY_LEVELS,NCC_params); - enhance(MIP_xz2,(dimi_v*dimk_v),GRAY_LEVELS,NCC_params); - } - - compute_NCC_map(NCC_xz,MIP_xz1,MIP_xz2,dimi_v,dimk_v,delayi,delayk); - - // calcola NCC su yz - NCC_yz = new iom::real_t[(2*delayj+1)*(2*delayk+1)]; - for ( i=0; i<((2*delayj+1)*(2*delayk+1)); i++ ) - NCC_yz[i] = 0; - - if ( NCC_params->enhance ) { - enhance(MIP_yz1,(dimj_v*dimk_v),GRAY_LEVELS,NCC_params); - enhance(MIP_yz2,(dimj_v*dimk_v),GRAY_LEVELS,NCC_params); - } - - compute_NCC_map(NCC_yz,MIP_yz1,MIP_yz2,dimj_v,dimk_v,delayj,delayk); - -#ifdef _WRITE_IMGS - if ( NCC_params->enhance ) { - write_3D_stack(strcpy(_fname+_PREFIX_LEN,"_MIP_xy1_en.dat")-_PREFIX_LEN,MIP_xy1,dimi_v,dimj_v,1); - write_3D_stack(strcpy(_fname+_PREFIX_LEN,"_MIP_xy2_en.dat")-_PREFIX_LEN,MIP_xy2,dimi_v,dimj_v,1); - write_3D_stack(strcpy(_fname+_PREFIX_LEN,"_MIP_xz1_en.dat")-_PREFIX_LEN,MIP_xz1,dimi_v,dimk_v,1); - write_3D_stack(strcpy(_fname+_PREFIX_LEN,"_MIP_xz2_en.dat")-_PREFIX_LEN,MIP_xz2,dimi_v,dimk_v,1); - write_3D_stack(strcpy(_fname+_PREFIX_LEN,"_MIP_yz1_en.dat")-_PREFIX_LEN,MIP_yz1,dimj_v,dimk_v,1); - write_3D_stack(strcpy(_fname+_PREFIX_LEN,"_MIP_yz2_en.dat")-_PREFIX_LEN,MIP_yz2,dimj_v,dimk_v,1); - } -#endif - -#ifdef _WRITE_IMGS - write_3D_stack(strcpy(_fname+_PREFIX_LEN,"_NCC_xy.dat")-_PREFIX_LEN,NCC_xy,(2*delayi+1),(2*delayj+1),1); - write_3D_stack(strcpy(_fname+_PREFIX_LEN,"_NCC_xz.dat")-_PREFIX_LEN,NCC_xz,(2*delayi+1),(2*delayk+1),1); - write_3D_stack(strcpy(_fname+_PREFIX_LEN,"_NCC_yz.dat")-_PREFIX_LEN,NCC_yz,(2*delayj+1),(2*delayk+1),1); -#endif - - // max su xy, xz, yz - ind_xy = compute_MAX_ind(NCC_xy,((2*delayi+1)*(2*delayj+1))); - ind_xz = compute_MAX_ind(NCC_xz,((2*delayi+1)*(2*delayk+1))); - ind_yz = compute_MAX_ind(NCC_yz,((2*delayj+1)*(2*delayk+1))); - - // NCC_xy: check neighborhood of maxima and search for better maxima if any - temp = new iom::real_t[(2*NCC_params->wRangeThr_i+1)*(2*NCC_params->wRangeThr_j+1)];; - for ( i=0; i<((2*NCC_params->wRangeThr_i+1)*(2*NCC_params->wRangeThr_j+1)); i++ ) - temp[i] = 0; - compute_Neighborhood(NCC_params,NCC_xy,delayi,delayj,NCC_params->wRangeThr_i,NCC_params->wRangeThr_j,ind_xy,MIP_xy1,MIP_xy2,dimi_v,dimj_v,temp,dx1,dy1, failed_xy); - // substitute NCC map and delete the old one - delete NCC_xy; - NCC_xy = temp; - temp = (iom::real_t *)0; - - // NCC_xz: check neighborhood of maxima and search for better maxima if any - temp = new iom::real_t[(2*NCC_params->wRangeThr_i+1)*(2*NCC_params->wRangeThr_k+1)];; - for ( i=0; i<((2*NCC_params->wRangeThr_i+1)*(2*NCC_params->wRangeThr_k+1)); i++ ) - temp[i] = 0; - compute_Neighborhood(NCC_params,NCC_xz,delayi,delayk,NCC_params->wRangeThr_i,NCC_params->wRangeThr_k,ind_xz,MIP_xz1,MIP_xz2,dimi_v,dimk_v,temp,dx2,dz1, failed_xz); - // substitute NCC map and delete the old one - delete NCC_xz; - NCC_xz = temp; - temp = (iom::real_t *)0; - - // NCC_yz: check neighborhood of maxima and search for better maxima if any - temp = new iom::real_t[(2*NCC_params->wRangeThr_i+1)*(2*NCC_params->wRangeThr_k+1)];; - for ( i=0; i<((2*NCC_params->wRangeThr_i+1)*(2*NCC_params->wRangeThr_k+1)); i++ ) - temp[i] = 0; - compute_Neighborhood(NCC_params,NCC_yz,delayj,delayk,NCC_params->wRangeThr_i,NCC_params->wRangeThr_k,ind_yz,MIP_yz1,MIP_yz2,dimj_v,dimk_v,temp,dy2,dz2, failed_yz); - // substitute NCC map and delete the old one - delete NCC_yz; - NCC_yz = temp; - temp = (iom::real_t *)0; - - //compute_Alignment(NCC_params,NCC_xy,NCC_xz,NCC_yz,delayi,delayj,delayk,ind_xy,ind_xz,ind_yz,result); - - compute_Alignment(NCC_params,NCC_xy,NCC_xz,NCC_yz, - NCC_params->wRangeThr_i,NCC_params->wRangeThr_j,NCC_params->wRangeThr_k,dx1,dx2,dy1,dy2,dz1,dz2,failed_xy, failed_xz, failed_yz, result); - - if ( side == NORTH_SOUTH ) - result->coord[0] += ni; - else if ( side == WEST_EAST ) - result->coord[1] += nj; - else - throw iom::exception("CrossMIPs: unexpected alignment configuration"); - - if ( allocated ) { - delete NCC_params->percents; - delete NCC_params->c; - delete NCC_params; - } - - delete MIP_xy1; - delete MIP_xz1; - delete MIP_yz1; - delete MIP_xy2; - delete MIP_xz2; - delete MIP_yz2; - - delete NCC_xy; - delete NCC_xz; - delete NCC_yz; - - // temp must not be deleted -#if CM_VERBOSE > 1 - printf("\tReturning\n\t\tV[%d, %.6f, %d]\n\t\tH[%d, %.6f, %d]\n\t\tD[%d, %.6f, %d]\n\n", - result->coord[0], result->NCC_maxs[0], result->NCC_widths[0], - result->coord[1], result->NCC_maxs[1], result->NCC_widths[1], - result->coord[2], result->NCC_maxs[2], result->NCC_widths[2]); -#endif - return result; -} - - -bool write_3D_stack ( char *fname, iom::real_t *stck, int dimi, int dimj, int dimk ) { - FILE *fout; - int i, j, k; - - if ( (fout = fopen(fname,"wb")) == NULL ) return false; - - fwrite(&dimi,sizeof(int),1,fout); - fwrite(&dimj,sizeof(int),1,fout); - fwrite(&dimk,sizeof(int),1,fout); - - for ( k=0; k(b)) ? (a) : (b)) -# define START_IND(i) (((i)>0) ? (i) : 0) - - -# ifdef _ERROR_TO_STDERR -# define DISPLAY_ERROR(msg) \ - fprintf(stderr,"*** libcrossmips ERROR: %s\n", msg) -# else -# define DISPLAY_ERROR(msg) -# endif - - -# endif diff --git a/v3d_main/terafly/src/core/imagemanager/BDVVolume.cpp b/v3d_main/terafly/src/core/imagemanager/BDVVolume.cpp deleted file mode 100755 index f45c49743e..0000000000 --- a/v3d_main/terafly/src/core/imagemanager/BDVVolume.cpp +++ /dev/null @@ -1,210 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -* 2015-11-30. Giulio. @CREATED -*/ - -#include -#include -#include "BDVVolume.h" -#include "HDF5Mngr.h" - -#ifdef _WIN32 -#include "dirent_win.h" -#else -#include -#endif -//#include -//#include -//#include -#include -#include -#include "ProgressBar.h" - -using namespace std; -using namespace iim; - -BDVVolume::BDVVolume(const char* _root_dir, int res, int tp, void *_BDV_descr ) throw (IOException) -: VirtualVolume() // _root_dir can be NULL -{ - if ( _root_dir ) { - /**/iim::debug(iim::LEV3, strprintf("_root_dir=%s", _root_dir).c_str(), __iim__current__function__); - root_dir = new char[strlen(_root_dir)+1]; - strcpy(this->root_dir, _root_dir); - if ( !_BDV_descr ) { // file name is given, BDV descriptor is local - BDV_HDF5init(std::string(_root_dir),BDV_descr); - BDV_HDF5getVolumeInfo(BDV_descr, tp, res, HDF5_descr, VXL_1, VXL_2, VXL_3, ORG_V, ORG_H, ORG_D, - DIM_V, DIM_H, DIM_D, DIM_C, BYTESxCHAN, DIM_T, t0, t1 ); - } - else - throw iim::IOException(iim::strprintf("A BDV descriptor cannot be passed if a file name is specified (_root_dir=%s)", _root_dir).c_str(),__iim__current__function__); - } - else // a file name is not given - if ( _BDV_descr ) { // BDV is given and not local - BDV_descr = (void *) 0; - BDV_HDF5getVolumeInfo(_BDV_descr, tp, res, HDF5_descr, VXL_1, VXL_2, VXL_3, ORG_V, ORG_H, ORG_D, DIM_V, DIM_H, DIM_D, DIM_C, BYTESxCHAN, DIM_T, t0, t1 ); - } - else - throw iim::IOException(iim::strprintf("A HDF5 descriptor must be passed if a file name is not specified").c_str(),__iim__current__function__); - - - VXL_V = VXL_2 ; - VXL_H = VXL_1 ; - VXL_D = VXL_3 ; - - n_active = DIM_C; - active = new uint32[n_active]; - for ( int c=0; cprint(print_stacks); -// //} -// printf("\n*** END printing BDVVolume object...\n\n"); -//} - - -//loads given subvolume in a 1-D array of float -real32* BDVVolume::loadSubvolume(int V0,int V1, int H0, int H1, int D0, int D1, list *involved_blocks, bool release_blocks) throw (IOException) -{ - /**/iim::debug(iim::LEV3, strprintf("V0=%d, V1=%d, H0=%d, H1=%d, D0=%d, D1=%d, %s", V0, V1, H0, H1, D0, D1, (involved_blocks? ", involved_stacks" : "")).c_str(), __iim__current__function__); - - char msg[STATIC_STRINGS_SIZE]; - sprintf(msg,"in BDVVolume::loadSubvolume: not completed yet"); - throw IOException(msg); - - //initializations - V0 = (V0 == -1 ? 0 : V0); - V1 = (V1 == -1 ? DIM_V : V1); - H0 = (H0 == -1 ? 0 : H0); - H1 = (H1 == -1 ? DIM_H : H1); - D0 = (D0 == -1 ? 0 : D0); - D1 = (D1 == -1 ? DIM_D : D1); - - //allocation - sint64 sbv_height = V1 - V0; - sint64 sbv_width = H1 - H0; - sint64 sbv_depth = D1 - D0; - real32 *subvol = new real32[sbv_height * sbv_width * sbv_depth]; - - //scanning of stacks matrix for data loading and storing into subvol - Rect_t subvol_area; - subvol_area.H0 = H0; - subvol_area.V0 = V0; - subvol_area.H1 = H1; - subvol_area.V1 = V1; - - return subvol; -} - -//loads given subvolume in a 1-D array of uint8 while releasing stacks slices memory when they are no longer needed -//---03 nov 2011: added color support -uint8* BDVVolume::loadSubvolume_to_UINT8(int V0,int V1, int H0, int H1, int D0, int D1, int *channels, int ret_type) throw (IOException) -{ - /**/iim::debug(iim::LEV3, strprintf("V0=%d, V1=%d, H0=%d, H1=%d, D0=%d, D1=%d, *channels=%d, ret_type=%d", V0, V1, H0, H1, D0, D1, channels ? *channels : -1, ret_type).c_str(), __iim__current__function__); - - //checking for non implemented features - //if( this->BYTESxCHAN != 1 ) { - // char err_msg[STATIC_STRINGS_SIZE]; - // sprintf(err_msg,"BDVVolume::loadSubvolume_to_UINT8: invalid number of bytes per channel (%d)",this->BYTESxCHAN); - // throw iim::IOException(err_msg); - //} - - //if ( (ret_type == iim::DEF_IMG_DEPTH) && ((8 * this->BYTESxCHAN) != iim::DEF_IMG_DEPTH) ) { - // does not support depth conversion: - // return type is 8 bits, but native depth is not 8 bits - if ( (ret_type != iim::NATIVE_RTYPE) && (ret_type != iim::DEF_IMG_DEPTH) ) { - // return type should be converted, but not to 8 bits per channel - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"RawVolume::loadSubvolume_to_UINT8: non supported return type (%d bits) - native type is %d bits",ret_type, 8*this->BYTESxCHAN); - throw IOException(err_msg); - } - - //char *err_rawfmt; - - //initializations - V0 = V0 < 0 ? 0 : V0; - H0 = H0 < 0 ? 0 : H0; - D0 = D0 < 0 ? 0 : D0; - V1 = (V1 < 0 || V1 > (int)DIM_V) ? DIM_V : V1; // iannello MODIFIED - H1 = (H1 < 0 || H1 > (int)DIM_H) ? DIM_H : H1; // iannello MODIFIED - D1 = (D1 < 0 || D1 > (int)DIM_D) ? DIM_D : D1; // iannello MODIFIED - - //checking that the interval is valid - if(V1-V0 <=0 || H1-H0 <= 0 || D1-D0 <= 0) - throw IOException("in BDVVolume::loadSubvolume_to_UINT8: invalid subvolume intervals"); - - //computing dimensions - sint64 sbv_height = V1 - V0; - sint64 sbv_width = H1 - H0; - sint64 sbv_depth = D1 - D0; - - sint64 sbv_ch_dim = sbv_height * sbv_width * sbv_depth; - - // check on ret_type must be included: currently always returns 8-bits buffers - - uint8 *subvol = new uint8[n_active*sbv_ch_dim]; - //uint8 *subvol_ch; - - for ( int c=0; c -#include - -//every object of this class has the default (1,2,3) reference system -class BDVVolume : public iim::VirtualVolume -{ - private: - //******OBJECT ATTRIBUTES****** - void *HDF5_descr; - void *BDV_descr; - float VXL_1, VXL_2, VXL_3; //voxel dimensions of the stored volume - - //***OBJECT PRIVATE METHODS**** - BDVVolume(void); - - //Given the reference system, initializes all object's members using stack's directories hierarchy - //void init() throw (iim::IOException); - - //rotate stacks matrix around D axis (accepted values are theta=0,90,180,270) - //void rotate(int theta); - - //mirror stacks matrix along mrr_axis (accepted values are mrr_axis=1,2,3) - //void mirror(iim::axis mrr_axis); - - // iannello returns the number of channels of images composing the volume - void initChannels ( ) throw (iim::IOException) { } - - public: - //CONSTRUCTORS-DECONSTRUCTOR - BDVVolume(const char* _root_dir, int res = 0, int tp = 0, void *BDV_descr = 0 ) throw (iim::IOException); - - ~BDVVolume(void); - - //GET methods - float getVXL_1(){return VXL_1;} - float getVXL_2(){return VXL_2;} - float getVXL_3(){return VXL_3;} - iim::axis getAXS_1() {return iim::axis(1);}; - iim::axis getAXS_2() {return iim::axis(2);}; - iim::axis getAXS_3() {return iim::axis(3);}; - - // returns a unique ID that identifies the volume format - std::string getPrintableFormat(){return iim::BDV_HDF5_FORMAT;} - - - //PRINT method - //void print( bool print_stacks = false ); - - //loads given subvolume in a 1-D array of iim::real32 while releasing stacks slices memory when they are no longer needed - inline iim::real32 *loadSubvolume_to_real32(int V0=-1,int V1=-1, int H0=-1, int H1=-1, int D0=-1, int D1=-1) throw (iim::IOException) { - return loadSubvolume(V0,V1,H0,H1,D0,D1,0,true); - } - - //loads given subvolume in a 1-D array and puts used Stacks into 'involved_stacks' iff not null - iim::real32 *loadSubvolume(int V0=-1,int V1=-1, int H0=-1, int H1=-1, int D0=-1, int D1=-1, - std::list *involved_blocks = 0, bool release_blocks = false) throw (iim::IOException); - - //loads given subvolume in a 1-D array of iim::uint8 while releasing stacks slices memory when they are no longer needed - iim::uint8 *loadSubvolume_to_UINT8(int V0=-1,int V1=-1, int H0=-1, int H1=-1, int D0=-1, int D1=-1, - int *channels=0, int ret_type=iim::DEF_IMG_DEPTH) throw (iim::IOException); - - friend class iim::VirtualVolume; - -}; - -#endif //_BDV_VOLUME_H diff --git a/v3d_main/terafly/src/core/imagemanager/CMakeLists.txt b/v3d_main/terafly/src/core/imagemanager/CMakeLists.txt deleted file mode 100644 index 1b533e65a0..0000000000 --- a/v3d_main/terafly/src/core/imagemanager/CMakeLists.txt +++ /dev/null @@ -1,30 +0,0 @@ -# CmakeLists.txt in imagemanager dir - -# add used modules to include path -include_directories (${TeraStitcher_SOURCE_DIR}/iomanager) -include_directories (${TeraStitcher_SOURCE_DIR}/volumemanager) -include_directories (${TeraStitcher_SOURCE_DIR}/tinyxml) - -# add 3rd party modules to include path -include_directories (${CMAKE_SOURCE_DIR}/3rdparty/zlib) -include_directories (${CMAKE_BINARY_DIR}/3rdparty/zlib) -include_directories (${CMAKE_SOURCE_DIR}/3rdparty/libtiff) -include_directories (${CMAKE_BINARY_DIR}/3rdparty/libtiff) -include_directories (${CMAKE_SOURCE_DIR}/3rdparty/HDF5) -include_directories (${CMAKE_BINARY_DIR}/3rdparty/HDF5) - -link_directories(${CMAKE_SOURCE_DIR}/3rdparty/libs) - - -# set up OpenCV library -#find_package(OpenCV REQUIRED) -#include_directories(${OpenCV_INCLUDE_DIRS}) -#link_directories(${OpenCV_LIB_DIR}) - -# add STATIC library from the all .h and .cpp files -file(GLOB imagemanager_headers *.h) -file(GLOB imagemanager_sources *.cpp) -add_library(imagemanager STATIC ${imagemanager_headers} ${imagemanager_sources}) - -target_link_libraries(imagemanager hdf5) -target_link_libraries(imagemanager szip) \ No newline at end of file diff --git a/v3d_main/terafly/src/core/imagemanager/HDF5Mngr.cpp b/v3d_main/terafly/src/core/imagemanager/HDF5Mngr.cpp deleted file mode 100755 index 20bff8354c..0000000000 --- a/v3d_main/terafly/src/core/imagemanager/HDF5Mngr.cpp +++ /dev/null @@ -1,1002 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -******************* -* 2015-12-10. Giulio. @ADDED conditional compilation to exclude HDF5 dependent code -* 2015-12-09. Giulio. @RELEASED first working version -* 2015-11-17. Giulio. @CREATED -*/ - -#include "HDF5Mngr.h" -#include "RawFmtMngr.h" -#include // needed by clang: defines size_t -#include - -#define ENABLE_BDV_HDF5 - -#ifdef ENABLE_BDV_HDF5 -#include "hdf5.h" -#endif - -#ifdef _VAA3D_TERAFLY_PLUGIN_MODE -#include -#include "PLog.h" -#include "COperation.h" -#endif - - -#ifdef ENABLE_BDV_HDF5 - -#define HDF5_SUFFIX "h5" - -#include - - -#define MAXSTP 10 -#define MAXRES 10 -#define MAXTPS 10 - -#define DEF_CHNK_DIM 16 - -#define MAX_NAME 1024 - -typedef double vxl_size_t[3]; -typedef hsize_t dims_t[3]; -typedef int subdvsns_t[3]; - -/* WARNINIG: - * current implementation assumes that all setups from 0 to i-1 have been created before creating setup i - * current implementation assumes that all time points from 0 to i-1 have been created before creating timepoint i - */ - -/**************************************************************************** -* BDV-HDF5 file descriptor -****************************************************************************/ - -class BDV_HDF5_fdescr_t { - char *fname; // complete file path and name - hid_t file_id; // file handle - int n_setups; // number of setups - hid_t *setup_groups_id; // handles of setup groups - int n_timepoints; // number of time points - hid_t *tp_groups_id; // handles of time point groups - int n_res; // number of resolutions - vxl_size_t *vxl_sizes; // voxels sizes of each resolution - dims_t *vol_dims; // volume dimensions of each resolution - subdvsns_t *chunk_dims; // chunk dimensions of each resolution - int vxl_nbytes; // number of bytes of each channel - hid_t vxl_type; // HDF5 type of voxel values - hsize_t ***n_slices; // number of slices of each time point at each setup at each resolutions (all setups should have the same number of slices) - - // private methods - void scan_root ( ); - -public: - BDV_HDF5_fdescr_t ( ); - /* default constructor: returns and empty descriptor */ - - BDV_HDF5_fdescr_t ( const char *_fname, int _vxl_nbytes = 2, int maxstp = MAXSTP, int maxres = MAXRES, int maxtps = MAXTPS ); - /* */ - - ~BDV_HDF5_fdescr_t ( ); - /* close the HDF5 file and deallocates memory */ - - // getters - int getN_SETUPS ( ) { return n_setups; } - int getN_TPS ( ) { return n_timepoints; } - int getN_RES ( ) { return n_res; } - hid_t getSETUP_GROUPS_ID ( int sg ) { return setup_groups_id[sg]; } - hid_t getTP_GROUPS_ID ( int tp ) { return tp_groups_id[tp]; } - double *getVXL_SZ ( int r ) { return vxl_sizes[r]; } - hsize_t *getVOL_DIMS ( int r ) { return vol_dims[r]; } - int *getCHUNK_DIMS ( int r ) { return chunk_dims[r]; } - int getVXL_NBYTES ( ) { return vxl_nbytes; } - hsize_t getVXL_TYPE ( ) { return vxl_type; } - hsize_t getN_SLICES ( int tp, int s, int r ) { return n_slices[tp][s][r]; } - - hid_t *getDATASETS_ID ( int tp, int r ); - /* returns a list of the n_setups handles of datasets of resolution r of time point tp */ - - // other operations - int addSetup ( int s ); - /* add setup s to file */ - - int addResolution ( int r, float vxlszV, float vxlszH, float vxlszD, hsize_t dimV, hsize_t dimH, hsize_t dimD, hsize_t chnk_dimV, hsize_t chnk_dimH, hsize_t chnk_dimD ); - /* add resolution r with voxel size (vxlszV x vxlszH x vxlszD), dimensions (dimV x dimH x dimD) and chunk dimensions (chnk_dimV x chnk_dimH x chnk_dimD) to all setups */ - - int addTimePoint ( int t ); - /* add time point t (with all setups and all resolutions) */ - - int writeHyperslab ( int tp, int s, int r, iim::uint8 *buf, hsize_t *dims_buf, hsize_t *hl_buf, hsize_t *hl_file = 0 ); - /* write hyperslab hl_buf stored in buffer buf to hyperslab hl_file at time point tp and resolution r */ -}; - - -/* Descriptor for reading subvolumes with direct access to datasets - */ -struct BDV_volume_descr_t { - int n_setups; - hid_t vxl_type; - int vxl_nbytes; - hid_t *datasets_id; // -}; - - - -BDV_HDF5_fdescr_t::BDV_HDF5_fdescr_t ( ) { - fname = (char *) 0; - file_id = (hid_t) -1; - n_setups = 0; - setup_groups_id = (hid_t *) 0; - n_timepoints = 0; - tp_groups_id = (hid_t *) 0; - n_res = 0; - vxl_sizes = (vxl_size_t *) 0; - vol_dims = (dims_t *) 0; - chunk_dims = (subdvsns_t *) 0; - vxl_nbytes = 0; - vxl_type = -1; - n_slices = (hsize_t ***) 0; -} - - -BDV_HDF5_fdescr_t::BDV_HDF5_fdescr_t ( const char *_fname, int _vxl_nbytes, int maxstp, int maxres, int maxtps ) { - if ( (file_id = H5Fopen(_fname, H5F_ACC_RDWR, H5P_DEFAULT)) < 0 ) { // non existing file: create it empty - - file_id = H5Fcreate(_fname, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT); - - fname = new char[strlen(_fname)+1]; - strcpy(fname,_fname); - n_setups = 0; - setup_groups_id = new hid_t[maxstp]; - n_timepoints = 0; - tp_groups_id = new hid_t[maxtps]; - n_res = 0; - vxl_sizes = new vxl_size_t[maxres]; - vol_dims = new dims_t[maxres]; - chunk_dims = new subdvsns_t[maxres]; - vxl_nbytes = _vxl_nbytes; - - n_slices = new hsize_t **[maxtps]; - - /* - * Create the data types group. - */ - hid_t group_id = H5Gcreate2(file_id, "/__DATA_TYPES__", H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); - - /* Create a named datatype for boolean values */ - unsigned char val; - hid_t type_id = H5Tcreate(H5T_ENUM,sizeof(unsigned char)); - H5Tenum_insert(type_id, "FALSE", (val=0,&val)); - H5Tenum_insert(type_id, "TRUE", (val=1,&val)); - herr_t status = H5Tcommit(group_id,"Enum_Boolean",type_id, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); - H5Tclose(type_id); - - /* Create a named datatype for variable length strings */ - type_id = H5Tcopy(H5T_C_S1); - status = H5Tset_size(type_id, H5T_VARIABLE); - status = H5Tcommit(group_id,"String_VariableLength",type_id, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); - H5Tclose(type_id); - - /* Close the group. */ - status = H5Gclose(group_id); - } - else { // existing file: initialize descriptor - fname = new char[strlen(_fname)+1]; - strcpy(fname,_fname); - scan_root(); - } - - if ( vxl_nbytes == 1 ) - vxl_type = H5T_NATIVE_CHAR; - else if ( vxl_nbytes == 2 ) - vxl_type = H5T_NATIVE_SHORT; - else - throw iim::IOException(iim::strprintf("number of bytes per voxel not allowed (%d)",vxl_nbytes).c_str(),__iim__current__function__); -} - - -BDV_HDF5_fdescr_t::~BDV_HDF5_fdescr_t ( ) { - if ( fname ) - delete fname; - if ( setup_groups_id ) { - for ( int s=0; sgetN_RES(); -#else - throw iim::IOException(iim::strprintf( - "Support to BDV_HDF5 files not available: please verify there is are valid hdf5 static libs (hdf5 and szip) " - "in ""3rdparty/libs"" directory and set the ""ENABLED_BDV_HDF5"" checkbox before configuring CMake project").c_str(),__iim__current__function__); -#endif -} - - -void BDV_HDF5close ( void *descr ) { -#ifdef ENABLE_BDV_HDF5 - delete (BDV_HDF5_fdescr_t *) descr; -#else - throw iim::IOException(iim::strprintf( - "Support to BDV_HDF5 files not available: please verify there is are valid hdf5 static libs (hdf5 and szip) " - "in ""3rdparty/libs"" directory and set the ""ENABLED_BDV_HDF5"" checkbox before configuring CMake project").c_str(),__iim__current__function__); -#endif -} - - -void BDV_HDF5addSetups ( void *file_descr, iim::sint64 height, iim::sint64 width, iim::sint64 depth, - float vxlszV, float vxlszH, float vxlszD, bool *res, int res_size, int chans, int block_height, int block_width, int block_depth ) { -#ifdef ENABLE_BDV_HDF5 - - BDV_HDF5_fdescr_t *int_descr = (BDV_HDF5_fdescr_t *) file_descr; - - if ( int_descr->getN_SETUPS() ) { // file already contains timepoints: check consistency of additional data - throw iim::IOException(iim::strprintf("updating already existing files not supported yet").c_str(),__iim__current__function__); - } - else { // file is empty create setups descriptors - for ( int c=0; caddSetup(c) != c ) - throw iim::IOException(iim::strprintf("cannot add setup %d",c).c_str(),__iim__current__function__); - for ( int r=0; raddResolution(r,vxlszV*iim::powInt(2,r),vxlszH*iim::powInt(2,r),vxlszD*iim::powInt(2,r), - height/iim::powInt(2,r),width/iim::powInt(2,r),depth/iim::powInt(2,r),block_height, block_width, block_depth) != r ) - throw iim::IOException(iim::strprintf("cannot add resolution %d",r).c_str(),__iim__current__function__); - } -#else - throw iim::IOException(iim::strprintf( - "Support to BDV_HDF5 files not available: please verify there is are valid hdf5 static libs (hdf5 and szip) " - "in ""3rdparty/libs"" directory and set the ""ENABLED_BDV_HDF5"" checkbox before configuring CMake project").c_str(),__iim__current__function__); -#endif -} - - -void BDV_HDF5addTimepoint ( void *file_descr, int tp ) { -#ifdef ENABLE_BDV_HDF5 - BDV_HDF5_fdescr_t *int_descr = (BDV_HDF5_fdescr_t *) file_descr; - - if ( int_descr->addTimePoint(tp) != tp ) - throw iim::IOException(iim::strprintf("cannot add time point %d",tp).c_str(),__iim__current__function__); -#else - throw iim::IOException(iim::strprintf( - "Support to BDV_HDF5 files not available: please verify there is are valid hdf5 static libs (hdf5 and szip) " - "in ""3rdparty/libs"" directory and set the ""ENABLED_BDV_HDF5"" checkbox before configuring CMake project").c_str(),__iim__current__function__); -#endif -} - - -void BDV_HDF5writeHyperslab ( void *file_descr, iim::uint8 *buf, iim::sint64 *dims_buf, iim::sint64 *hl, int r, int s, int tp ) { -#ifdef ENABLE_BDV_HDF5 - BDV_HDF5_fdescr_t *int_descr = (BDV_HDF5_fdescr_t *) file_descr; - - if ( int_descr->writeHyperslab(tp,s,r,buf,(hsize_t *)dims_buf,(hsize_t *)hl) ) - throw iim::IOException(iim::strprintf("cannot add hyperslab: buffer size=(%d,%d,%d), hyperslab=[offset=(%d,%d,%d), stride=(%d,%d,%d), size=(%d,%d,%d), block=(%d,%d,%d)]", - dims_buf[0],dims_buf[1],dims_buf[2],hl[0],hl[1],hl[2],hl[3],hl[4],hl[5],hl[6],hl[7],hl[8],hl[9],hl[10],hl[11]).c_str(),__iim__current__function__); -#else - throw iim::IOException(iim::strprintf( - "Support to BDV_HDF5 files not available: please verify there is are valid hdf5 static libs (hdf5 and szip) " - "in ""3rdparty/libs"" directory and set the ""ENABLED_BDV_HDF5"" checkbox before configuring CMake project").c_str(),__iim__current__function__); -#endif -} - - - -void BDV_HDF5getVolumeInfo ( void *descr, int tp, int res, void *&volume_descr, - float &VXL_1, float &VXL_2, float &VXL_3, - float &ORG_V, float &ORG_H, float &ORG_D, - iim::uint32 &DIM_V, iim::uint32 &DIM_H, iim::uint32 &DIM_D, - int &DIM_C, int &BYTESxCHAN, int &DIM_T, int &t0, int &t1 ) { -#ifdef ENABLE_BDV_HDF5 - - BDV_HDF5_fdescr_t *int_descr = (BDV_HDF5_fdescr_t *) descr; - BDV_volume_descr_t *int_volume_descr = new BDV_volume_descr_t; - - // in HDF5 dimensions are ordered as DVH - VXL_1 = (float) int_descr->getVXL_SZ(res)[1]; - VXL_2 = (float) int_descr->getVXL_SZ(res)[2]; - VXL_3 = (float) int_descr->getVXL_SZ(res)[0]; - - ORG_V = ORG_H = ORG_D = 0.0; - - DIM_V = int_descr->getVOL_DIMS(res)[1]; - DIM_H = int_descr->getVOL_DIMS(res)[2]; - DIM_D = int_descr->getVOL_DIMS(res)[0]; - - DIM_C = int_descr->getN_SETUPS(); - BYTESxCHAN = int_descr->getVXL_NBYTES(); - - DIM_T = int_descr->getN_TPS(); - t0 = t1 = 0; - - int_volume_descr->n_setups = int_descr->getN_SETUPS(); - int_volume_descr->vxl_type = int_descr->getVXL_TYPE(); - int_volume_descr->vxl_nbytes = int_descr->getVXL_NBYTES(); - - int_volume_descr->datasets_id = int_descr->getDATASETS_ID(tp,res); - - volume_descr = int_volume_descr; -#else - throw iim::IOException(iim::strprintf( - "Support to BDV_HDF5 files not available: please verify there is are valid hdf5 static libs (hdf5 and szip) " - "in ""3rdparty/libs"" directory and set the ""ENABLED_BDV_HDF5"" checkbox before configuring CMake project").c_str(),__iim__current__function__); -#endif -} - - -void BDV_HDF5getSubVolume ( void *descr, int V0, int V1, int H0, int H1, int D0, int D1, int setup, iim::uint8 *buf ) { -#ifdef ENABLE_BDV_HDF5 - - BDV_volume_descr_t *int_volume_descr = (BDV_volume_descr_t *) descr; - - hsize_t start_buf[3]; - hsize_t start_file[3]; - hsize_t dims_buf[3]; - herr_t status; - - dims_buf[0] = D1 - D0; - dims_buf[1] = V1 - V0; - dims_buf[2] = H1 - H0; - - /* Get filespace handle first. */ - hid_t filespace_id = H5Dget_space(int_volume_descr->datasets_id[setup]); /* dataspace handle */ - //int rank = H5Sget_simple_extent_ndims(filespace_id); - //hsize_t dims[3]; - //status = H5Sget_simple_extent_dims(filespace_id, dims, NULL); - start_file[0] = D0; - start_file[1] = V0; - start_file[2] = H0; - status = H5Sselect_hyperslab(filespace_id, H5S_SELECT_SET, start_file, NULL, - dims_buf, NULL); - - /* Create memory space handle. */ - hid_t bufspace_id = H5Screate_simple(3,dims_buf,NULL); - start_buf[0] = 0; - start_buf[1] = 0; - start_buf[2] = 0; - status = H5Sselect_hyperslab(bufspace_id, H5S_SELECT_SET, start_buf, NULL, - dims_buf, NULL); - - if ( int_volume_descr->vxl_nbytes == 1 ) { - status = H5Dread(int_volume_descr->datasets_id[setup],int_volume_descr->vxl_type,bufspace_id,filespace_id,H5P_DEFAULT,buf); - } - else if ( int_volume_descr->vxl_nbytes == 2 ) { - iim::sint64 sbv_ch_dim = dims_buf[0] * dims_buf[1] * dims_buf[2]; - iim::uint8 *tempbuf = new iim::uint8[2 * sbv_ch_dim]; - status = H5Dread(int_volume_descr->datasets_id[setup],int_volume_descr->vxl_type,bufspace_id,filespace_id,H5P_DEFAULT,tempbuf); - - // convert to 8 bit and copy to buf - char *err_rawfmt; - if ( (err_rawfmt = convert2depth8bits(int_volume_descr->vxl_nbytes, sbv_ch_dim, 1, tempbuf, buf)) != 0 ) - throw iim::IOException(iim::strprintf("cannot convert buffer from %d bits to 8 bits (%s)",8*int_volume_descr->vxl_nbytes,err_rawfmt).c_str(),__iim__current__function__); - } - - H5Sclose(bufspace_id); - H5Sclose(filespace_id); -#else - throw iim::IOException(iim::strprintf( - "Support to BDV_HDF5 files not available: please verify there is are valid hdf5 static libs (hdf5 and szip) " - "in ""3rdparty/libs"" directory and set the ""ENABLED_BDV_HDF5"" checkbox before configuring CMake project").c_str(),__iim__current__function__); -#endif -} - -void BDV_HDF5closeVolume ( void *descr ) { -#ifdef ENABLE_BDV_HDF5 - BDV_volume_descr_t *int_volume_descr = (BDV_volume_descr_t *) descr; - if ( int_volume_descr->datasets_id ) - delete int_volume_descr->datasets_id; - delete (BDV_volume_descr_t *) descr; -#else - throw iim::IOException(iim::strprintf( - "Support to BDV_HDF5 files not available: please verify there is are valid hdf5 static libs (hdf5 and szip) " - "in ""3rdparty/libs"" directory and set the ""ENABLED_BDV_HDF5"" checkbox before configuring CMake project").c_str(),__iim__current__function__); -#endif -} - diff --git a/v3d_main/terafly/src/core/imagemanager/HDF5Mngr.h b/v3d_main/terafly/src/core/imagemanager/HDF5Mngr.h deleted file mode 100755 index e74a5c2dac..0000000000 --- a/v3d_main/terafly/src/core/imagemanager/HDF5Mngr.h +++ /dev/null @@ -1,118 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -******************* -* 2015-11-17. Giulio. @CREATED -*/ - -#ifndef HDF5_MNGR_H -#define HDF5_MNGR_H - -#include "IM_config.h" -#include - -/* Hyperslab conventions - * - * for N-dimensional datasets are 4 x N matrices - * first row is START (offset) - * second row is STRIDE - * third row is COUNT (how many elements) - * fourth row is BLOCK (how many blocks) - * - * For N=3, for each row: - * first element is D dimension - * second element is V dimension - * third element is H dimension - */ - - -void BDV_HDF5init ( std::string fname, void *&descr, int vxl_nbytes = 1 ) throw (iim::IOException); -/* opens or creates xHDF5 file fname according to the BigDataViewer format and returns an opaque descriptor - * - * fname: HDF5 filename - * vxl_nbytes: number of bytes per voxel of datasets to be stored in the file; it is ignored if the file already exists - * descr: pointer to the returned opaque descriptor - */ - - int BDV_HDF5n_resolutions ( void *descr ); - /* returns how many resolutions there are in the HDF5 file handled by descr - * It is assumed that all resolutions from 0 to the interger returned minus 1 are available - */ - -void BDV_HDF5close ( void *descr ); -/* close the HDF5 file represented by descr and deallocates the descriptor - * - * descr: opaque descriptor of the HDF5 file - */ - -void BDV_HDF5addSetups ( void *file_descr, iim::sint64 height, iim::sint64 width, iim::sint64 depth, - float vxlszV, float vxlszH, float vxlszD, bool *res, int res_size, int chans, int block_height = -1, int block_width = -1, int block_depth = -1 ); -/* creates setup descriptors with resolution and subdivisions datasets - * - * file_descr: - * height: - * width: - * depth: - * vxlszV: - * vxlszH* - * vxlszD: - * res: - * res_size: - * chans: - * block_height: - * block_width: - * block_depth: - */ - - -void BDV_HDF5addTimepoint ( void *file_descr, int tp = 0 ); -/* add time point at time tp (first time point is the default) - */ - - -void BDV_HDF5writeHyperslab ( void *file_descr, iim::uint8 *buf, iim::sint64 *dims, iim::sint64 *hl, int r, int s, int tp = 0 ); -/* write one hiperslab to file - */ - - -void BDV_HDF5getVolumeInfo ( void *descr, int tp, int res, void *&volume_descr, - float &VXL_1, float &VXL_2, float &VXL_3, - float &ORG_V, float &ORG_H, float &ORG_D, - iim::uint32 &DIM_V, iim::uint32 &DIM_H, iim::uint32 &DIM_D, - int &DIM_C, int &BYTESxCHAN, int &DIM_T, int &t0, int &t1 ); - - -void BDV_HDF5getSubVolume ( void *descr, int V0, int V1, int H0, int H1, int D0, int D1, int setup, iim::uint8 *buf ); -/* must copy a subvolume into buffer buf; voxels have to be converted to 8-bit if needed - */ - - -void BDV_HDF5closeVolume ( void *descr ); - - - #endif - \ No newline at end of file diff --git a/v3d_main/terafly/src/core/imagemanager/IM_config.cpp b/v3d_main/terafly/src/core/imagemanager/IM_config.cpp deleted file mode 100644 index 3417f4a8aa..0000000000 --- a/v3d_main/terafly/src/core/imagemanager/IM_config.cpp +++ /dev/null @@ -1,43 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - - -#include "IM_config.h" - -namespace IconImageManager -{ - - /******************* - * PARAMETERS * - ******************** - ---------------------------------------------------------------------------------------------------------------------------*/ - int DEBUG = NO_DEBUG; //debug level - bool DEBUG_TO_FILE = false; //whether debug messages should be printed on the screen or to a file (default: screen) - std::string DEBUG_FILE_PATH = "/home/alex/Scrivania/iim_debug.log"; //filepath where to save debug information - bool ADD_NOISE_TO_TIME_SERIES = false; // whether to mark individual frames of a time series with increasing gaussian noise - int CHANNEL_SELECTION = ALL; // channel to be loaded (default is ALL) - /*-------------------------------------------------------------------------------------------------------------------------*/ -} - - diff --git a/v3d_main/terafly/src/core/imagemanager/IM_config.h b/v3d_main/terafly/src/core/imagemanager/IM_config.h deleted file mode 100644 index a9f2ca07c5..0000000000 --- a/v3d_main/terafly/src/core/imagemanager/IM_config.h +++ /dev/null @@ -1,467 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -* 2015-03-17. Giulio. @CHANGED includes of standard header files (stdlib.h and stdio.h) moved outside the directive #ifdef _WIN32 -* 2015-02-18. Giulio. @ADDED Identifier for unstitched volume -*/ - - -#ifndef _IM_CONFIG_H -#define _IM_CONFIG_H - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#ifdef _WIN32 -#include -#include -#else -#include -#include -#include -#endif - -#ifdef max -#undef max -#endif -#ifdef min -#undef min -#endif - -//#ifdef __MACH__ -//#include -//#include -//#endif - -typedef struct {int V0, V1, H0, H1;} Rect_t; // used by iim::Stack and iim::Block - -namespace IconImageManager -{ - - /******************* - * INTERFACES * - ******************** - ---------------------------------------------------------------------------------------------------------------------------*/ - class imProgressBar; - class Stack; - class Block; - class VirtualVolume; - class StackedVolume; - class VirtualFmtMngr; - class Tiff3DFmtMngr; - class Vaa3DRawFmtMngr; - /*-------------------------------------------------------------------------------------------------------------------------*/ - - - /******************* - * TYPES * - ******************** - ---------------------------------------------------------------------------------------------------------------------------*/ - typedef signed char sint8; //8-bit signed integers (-128 -> +127) - typedef short sint16; //16-bit signed integers (-32,768 -> +32,767) - typedef int sint32; //32-bit signed integers (-2,147,483,648 -> +2,147,483,647) - typedef long long sint64; //64-bit signed integers (–9,223,372,036,854,775,808 -> +9,223,372,036,854,775,807) - typedef unsigned char uint8; //8-bit unsigned integers (0 -> +255) - typedef unsigned short int uint16; //16-bit unsigned integers (0 -> +65,535) - typedef unsigned int uint32; //32-bit unsigned integers (0 -> +4,294,967,295) - typedef unsigned long long uint64; //64-bit unsigned integers (0 -> +18,446,744,073,709,551,615 - typedef float real32; //real single precision - typedef double real64; //real double precision - /*-------------------------------------------------------------------------------------------------------------------------*/ - - - /******************* - * CONSTANTS * - ******************** - ---------------------------------------------------------------------------------------------------------------------------*/ - const std::string VERSION = "1.0.0"; // version of current module - const std::string MDATA_BIN_FILE_NAME = "mdata.bin"; // name of binary metadata file - const int MDATA_BIN_FILE_VERSION = 2; // version of binary metadata file - const std::string MC_MDATA_BIN_FILE_NAME = "cmap.bin"; // name of binary metadata file for multichannel volumes - const std::string FORMAT_MDATA_FILE_NAME = ".iim.format"; // name of format metadata file - const std::string CHANNEL_PREFIX = "CH_"; // prefix identifying a folder containing data of a certain channel - const std::string TIME_FRAME_PREFIX = "T_"; // prefix identifying a folder containing data of a certain time frame - const int DEF_IMG_DEPTH = 8; // default image depth - const int NUL_IMG_DEPTH = 0; // invalid image depth - const int NATIVE_RTYPE = 0; // loadVolume returns 1 byte per channel type - const std::string DEF_IMG_FORMAT = "tif"; // default image format - const int STATIC_STRINGS_SIZE = 1024; // size of static C-strings - const std::string TILED_MC_FORMAT = "Vaa3D raw (tiled, 4D)"; // unique ID for the TiledMCVolume class - const std::string TILED_FORMAT = "Vaa3D raw (tiled, 3D)"; // unique ID for the TiledVolume class - const std::string STACKED_FORMAT = "TIFF (tiled, 2D)"; // unique ID for the StackedVolume class - const std::string SIMPLE_FORMAT = "TIFF (series, 2D)"; // unique ID for the SimpleVolume class - const std::string SIMPLE_RAW_FORMAT = "Vaa3D raw (series, 2D)"; // unique ID for the SimpleVolumeRaw class - const std::string RAW_FORMAT = "Vaa3D raw"; // unique ID for the RawVolume class - const std::string TIF3D_FORMAT = "TIFF (3D)"; // unique ID for multipage TIFF format (nontiled) - const std::string TILED_TIF3D_FORMAT = "TIFF (tiled, 3D)"; // unique ID for multipage TIFF format (tiled) - const std::string TILED_MC_TIF3D_FORMAT = "TIFF (tiled, 4D)"; // unique ID for multipage TIFF format (nontiled, 4D) - const std::string UNST_TIF3D_FORMAT = "TIFF (unstitched, 3D)"; // unique ID for multipage TIFF format (nontiled, 4D) - const std::string BDV_HDF5_FORMAT = "HDF5 (BigDataViewer)"; // unique ID for BDV HDF5 - const std::string TIME_SERIES = "Time series"; // unique ID for the TimeSeries class - - const double PI = 3.14159265; // pi - const int TMITREE_MAX_HEIGHT = 10; // maximum depth of the TMITREE - const int TMITREE_MIN_BLOCK_DIM = 250; // minimum dimension of TMITREE block along X/Y/Z - - /*-------------------------------------------------------------------------------------------------------------------------*/ - - - /******************* - * PARAMETERS * - ******************** - default values have to be set in IM_config.cpp. - ---------------------------------------------------------------------------------------------------------------------------*/ - extern int DEBUG; // debug level of current module - extern bool DEBUG_TO_FILE; // whether debug messages should be printed on the screen or to a file (default: screen) - extern std::string DEBUG_FILE_PATH; // filepath where to save debug information - extern bool ADD_NOISE_TO_TIME_SERIES; // whether to mark individual frames of a time series with increasing gaussian noise - extern int CHANNEL_SELECTION; // channel to be used when image must be converted to an intensity image (default is ALL) - /*-------------------------------------------------------------------------------------------------------------------------*/ - - - /******************* - * ENUMS * - ******************** - ---------------------------------------------------------------------------------------------------------------------------*/ - enum axis { vertical=1, inv_vertical=-1, horizontal=2, inv_horizontal=-2, depth=3, inv_depth=-3, axis_invalid=0}; - enum debug_level { NO_DEBUG, LEV1, LEV2, LEV3, LEV_MAX }; - enum channel { ALL, R, G, B }; - /*-------------------------------------------------------------------------------------------------------------------------*/ - - - /******************* - * STRUCTS * - ******************** - ---------------------------------------------------------------------------------------------------------------------------*/ - struct VHD_triple{int V, H, D;}; - struct interval_t{ - int start, end; - interval_t(void) : start(-1), end(-1) {} - interval_t(int _start, int _end) : start(_start), end(_end){} - }; - struct ref_sys{ - axis first, second, third; - ref_sys(axis _first, axis _second, axis _third) : first(_first), second(_second), third(_third){} - ref_sys(const ref_sys &_rvalue) : first(_rvalue.first), second(_rvalue.second), third(_rvalue.third){} - ref_sys(): first(axis_invalid), second(axis_invalid), third(axis_invalid){} - }; - - - /******************************************** - * Cross-platform UTILITY inline functions * - ******************************************** - ---------------------------------------------------------------------------------------------------------------------------*/ - // round functions - inline int round(float x) { return static_cast(x > 0.0f ? x + 0.5f : x - 0.5f);} - inline int round(double x) { return static_cast(x > 0.0 ? x + 0.5 : x - 0.5 );} - - // sign function - template int sgn ( T x ){ return x < 0 ? -1 : 1;} - - // integer pow - inline int powInt(int base, int exp){ return static_cast( pow(static_cast(base), exp)); } - - // string-based sprintf function - inline std::string strprintf(const std::string fmt, ...){ - int size = 100; - std::string str; - va_list ap; - while (1) { - str.resize(size); - va_start(ap, fmt); - int n = vsnprintf((char *)str.c_str(), size, fmt.c_str(), ap); - va_end(ap); - if (n > -1 && n < size) { - str.resize(n); - return str; - } - if (n > -1) - size = n + 1; - else - size *= 2; - } - return str; - } - - //returns true if the given path is a directory - inline bool isDirectory(std::string path){ - struct stat s; - if( stat(path.c_str(),&s) == 0 ) - { - if( s.st_mode & S_IFDIR ) - return true; - else if( s.st_mode & S_IFREG ) - return false; - else return false; - } - else return false; - } - - //returns true if the given path is a file - inline bool isFile(std::string path){ - struct stat s; - if( stat(path.c_str(),&s) == 0 ) - { - if( s.st_mode & S_IFDIR ) - return false; - else if( s.st_mode & S_IFREG ) - return true; - else return false; - } - else return false; - } - - //returns true if the given string ends with - inline bool hasEnding (std::string const &fullString, std::string const &ending){ - if (fullString.length() >= ending.length()) { - return (0 == fullString.compare (fullString.length() - ending.length(), ending.length(), ending)); - } else { - return false; - } - } - - //returns file extension, if any (otherwise returns "") - inline std::string getFileExtension(const std::string& FileName){ - if(FileName.find_last_of(".") != std::string::npos) - return FileName.substr(FileName.find_last_of(".")+1); - return ""; - } - - //number to string conversion function and vice versa - template - std::string num2str ( T Number ){ - std::stringstream ss; - ss << Number; - return ss.str(); - } - template - T str2num ( const std::string &Text ){ - std::stringstream ss(Text); - T result; - return ss >> result ? result : 0; - } - - //time computation -// #ifdef _WIN32 -// inline double getTimeSeconds(){ -// return static_cast(clock()) / CLOCKS_PER_SEC; -// } -// #else -// #ifdef __MACH__ // OS X does not have clock_gettime, use clock_get_time -// inline double getTimeSeconds() -// { -// clock_serv_t cclock; -// mach_timespec_t mts; -// host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock); -// clock_get_time(cclock, &mts); -// mach_port_deallocate(mach_task_self(), cclock); -// return mts.tv_sec; -// } -// #else -// inline double getTimeSeconds(){ -// timespec event; -// clock_gettime(CLOCK_REALTIME, &event); -// return (event.tv_sec*1000.0 + event.tv_nsec/1000000.0)/1000.0; -// } -// #endif -// #endif - - - //make dir - #ifdef _WIN32 - #include - inline bool makeDir(const char* arg){ -// printf("Creating directory \"%s\" ...", arg); - bool done = _mkdir(arg) == 0; - bool result = done || errno != ENOENT; -// printf("%s\n", result? "DONE!" : "ERROR!"); - return result; - } - #else - inline bool makeDir(const char* arg){ -// printf("Creating directory \"%s\" ...", arg); - bool done = mkdir(arg, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == 0; - bool result = done || errno == EEXIST; -// printf("%s\n", result? "DONE!" : "ERROR!"); - return result; - } - #endif - - // check-and-makedir - inline bool check_and_make_dir(const char *dirname){ - if(isDirectory(dirname)) - return true; - else - return makeDir(dirname); - } - - - - //file deleting - #ifdef _WIN32 - inline void delete_file( const char* arg ){ - if(system(strprintf("del /F /Q /S \"%s\"", arg).c_str())!=0) - fprintf(stderr,"Can't delete file \"%s\"\n", arg); - } - #else - inline void delete_file( const char* arg ){ - if(system(strprintf("rm -f \"%s\"", arg).c_str())!=0) - fprintf(stderr,"Can't delete file \"%s\"\n", arg); - } - #endif - - //cross-platform current function macro - #if defined(__GNUC__) || (defined(__MWERKS__) && (__MWERKS__ >= 0x3000)) || (defined(__ICC) && (__ICC >= 600)) - # define __iim__current__function__ __PRETTY_FUNCTION__ - #elif defined(__DMC__) && (__DMC__ >= 0x810) - # define __iim__current__function__ __PRETTY_FUNCTION__ - #elif defined(__FUNCSIG__) - # define __iim__current__function__ __FUNCSIG__ - #elif (defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 600)) || (defined(__IBMCPP__) && (__IBMCPP__ >= 500)) - # define __iim__current__function__ __FUNCTION__ - #elif defined(__BORLANDC__) && (__BORLANDC__ >= 0x550) - # define __iim__current__function__ __FUNC__ - #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901) - # define __iim__current__function__ __func__ - #else - # define __iim__current__function__ "(unknown)" - #endif - - - inline const char* axis_to_str(axis ax){ - if(ax == 1) - return "Vertical"; - else if(ax == -1) - return "Inverse Vertical"; - else if(ax == 2) - return "Horizontal"; - else if(ax == -2) - return "Inverse Horizontal"; - else if(ax == 3) - return "Depth"; - else if(ax == -3) - return "Inverse Depth"; - else return ""; - } - /*-------------------------------------------------------------------------------------------------------------------------*/ - - - /*********************************************** - * DEBUG, WARNING and EXCEPTION FUNCTIONS * - ************************************************ - ---------------------------------------------------------------------------------------------------------------------------*/ - inline void warning(const char* message, const char* source = 0) - { - if(DEBUG_TO_FILE) - { - FILE* f = fopen(DEBUG_FILE_PATH.c_str(), "a"); - if(source) - fprintf(f, "\n**** WARNING (source: \"%s\") ****\n" - " |=> \"%s\"\n\n", source, message); - else - fprintf(f, "\n**** WARNING ****: %s\n", message); - fclose(f); - } - else - { - if(source) - printf("\n**** WARNING (source: \"%s\") ****\n" - " |=> \"%s\"\n\n", source, message); - else - printf("\n**** WARNING ****: %s\n", message); - } - } - - inline void debug(debug_level dbg_level, const char* message=0, const char* source=0) - { - if(DEBUG >= dbg_level){ - if(DEBUG_TO_FILE) - { - FILE* f = fopen(DEBUG_FILE_PATH.c_str(), "a"); - if(message && source) - fprintf(f, "\n--------------------- IconImageManager module: DEBUG (level %d) ----: in \"%s\") ----\n" - " message: %s\n\n", dbg_level, source, message); - else if(message) - fprintf(f, "\n--------------------- IconImageManager module: DEBUG (level %d) ----: %s\n", dbg_level, message); - else if(source) - fprintf(f, "\n--------------------- IconImageManager module: DEBUG (level %d) ----: in \"%s\"\n", dbg_level, source); - fclose(f); - } - else - { - if(message && source) - printf("\n--------------------- IconImageManager module: DEBUG (level %d) ----: in \"%s\") ----\n" - " message: %s\n\n", dbg_level, source, message); - else if(message) - printf("\n--------------------- IconImageManager module: DEBUG (level %d) ----: %s\n", dbg_level, message); - else if(source) - printf("\n--------------------- IconImageManager module: DEBUG (level %d) ----: in \"%s\"\n", dbg_level, source); - } - } - } - - - class IOException - { - private: - - std::string source; - std::string message; - IOException(void); - - public: - - IOException(std::string _message, std::string _source = "unknown"){ - source = _source; message = _message;} - ~IOException(void){} - const char* what() const {return message.c_str();} - const char* getSource() const {return source.c_str();} - }; -} -namespace iim = IconImageManager; //a short alias for the current namespace - -#endif //_IM_CONFIG_H - - -//time computation -#include -#ifdef _WIN32 - #define TIME( arg ) (((double) clock()) / CLOCKS_PER_SEC) - #define system_PAUSE() \ - system("PAUSE"); \ - cout< -#include -#include "IM_config.h" - -class iim::imProgressBar -{ - private: - - /********************************************************************************* - * Singleton design pattern: this class can have one instance only, which must be - * instantiated by calling static method "istance(...)" - **********************************************************************************/ - static imProgressBar* uniqueInstance; - imProgressBar(); - - char message_level_1[1000]; // main operation - char message_level_2[1000]; // sub-operation - char message_level_3[1000]; // sub-sub-operation - float progress_value; - double proctime; - int minutes_remaining; - int seconds_remaining; - - public: - - /********************************************************************************** - * Singleton design pattern: this class can have one instance only, which must be - * instantiated by calling static method "instance(...)" - ***********************************************************************************/ - static imProgressBar* instance(); - static imProgressBar* getInstance() - { - if(uniqueInstance) - return uniqueInstance; - else - return instance(); - } - ~imProgressBar(){} - - - void start(const char* new_operation_desc, bool toConverter = true); - void update(float new_progress_value, const char* new_progress_info); - void updateInfo(const char* new_progress_info); - void setMessage(int level, const char* message); - void show(bool toConverter = true); - void reset(); -}; - -#endif diff --git a/v3d_main/terafly/src/core/imagemanager/RawFmtMngr.cpp b/v3d_main/terafly/src/core/imagemanager/RawFmtMngr.cpp deleted file mode 100644 index a2cbefe352..0000000000 --- a/v3d_main/terafly/src/core/imagemanager/RawFmtMngr.cpp +++ /dev/null @@ -1,1508 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -*/ - -/* - * This file is a modified version of code extracted from the files stackutil.cpp and - * stackutil-11.cpp of the V3D project. See the following licence notice for more details. - * - * modified by Giulio Iannello, Centro Integrato di Ricerca, Universita' Campus Bio-Medico di Roma - * December 2012 - */ - - -/* - * Copyright (c)2006-2010 Hanchuan Peng (Janelia Farm, Howard Hughes Medical Institute). - * All rights reserved. - */ - - -/************ - ********* LICENSE NOTICE ************ - -This folder contains all source codes for the V3D project, which is subject to the following conditions if you want to use it. - -You will ***have to agree*** the following terms, *before* downloading/using/running/editing/changing any portion of codes in this package. - -1. This package is free for non-profit research, but needs a special license for any commercial purpose. Please contact Hanchuan Peng for details. - -2. You agree to appropriately cite this work in your related studies and publications. - -Peng, H., Ruan, Z., Long, F., Simpson, J.H., and Myers, E.W. (2010) “V3D enables real-time 3D visualization and quantitative analysis of large-scale biological image data sets,†Nature Biotechnology, Vol. 28, No. 4, pp. 348-353, DOI: 10.1038/nbt.1612. ( http://penglab.janelia.org/papersall/docpdf/2010_NBT_V3D.pdf ) - -Peng, H, Ruan, Z., Atasoy, D., and Sternson, S. (2010) “Automatic reconstruction of 3D neuron structures using a graph-augmented deformable model,†Bioinformatics, Vol. 26, pp. i38-i46, 2010. ( http://penglab.janelia.org/papersall/docpdf/2010_Bioinfo_GD_ISMB2010.pdf ) - -3. This software is provided by the copyright holders (Hanchuan Peng), Howard Hughes Medical Institute, Janelia Farm Research Campus, and contributors "as is" and any express or implied warranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the copyright owner, Howard Hughes Medical Institute, Janelia Farm Research Campus, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; reasonable royalties; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage. - -4. Neither the name of the Howard Hughes Medical Institute, Janelia Farm Research Campus, nor Hanchuan Peng, may be used to endorse or promote products derived from this software without specific prior written permission. - -*************/ - - - - -/* - * stackutil.cpp - * - * - * Created (extracted from earlier codes) by Hanchuan Peng on 7/31/06. - * Modified on 060803 by Hanchuan Peng: change the size information to be 4 V3DLONG (4-byte) instead of 4-short-int (2byte). - * Updated 060806: correct a bug in 4-byte swapping. And notice the compatibility of 32-bit system and 64-bit system about the length of int/V3DLONG types - * Copyright 2006 __Hanchuan Peng__. All rights reserved. - * - * 060816: add tif support - * 060828: add surfix extraction function here - * - * 060920: add 2-byte formatted raw format support back to increase the compatibility of existing data in the worm project - * - * 070214: add two simple interface to read any file formats supported (raw or tif) based on the surfix of filename - * 070220: add b_VERBOSE_PRINT - * 070306: add tif file exist verification - * 070713: George tried to add lsm file reading functions but unsucecssful - * 070806: Hanchuan added lsm 8-bit reading functions - * 070807/08: try to handle the imcomplete data generated by the Zeiss lsm writer. The current solution is to change the a function in libtiff tif_lzw.c file - * and force it return the value 2, instead of 0, when the input strip size is bigger than real. In this way, the tif function TIFFReadEncodedStrip() - * will continue to do postprocessing of the already read data. - * - * Special note: in this way, I will have to build a customary libtiff library and install at my own location ~/work/3rdsoft/lib instead of - * the default /usr/local/lib. When I will have to reset the .bashrc/.profile file and use LD_LIBRARY_PATH (and probably also DYLD_LIBRARY_PATH) - * for Mac to link them. This works for the case of V3D already. However, interestingly, I read an article arguing that using otool/ldd/nm, the dependency - * of objects files can be seen, and that Mac uses the absolute path in library dependency, and that LD_LIBRARY_PATH does not work. The - * interesting thing is that after I tried both, I found otool does show the absolute path, but LD_LIBARY_PATH/DYLD_LIBRARY_PATH works! - * - * 070819: add several functions to read LSM file thumbnails and middle slice. - * 071125: update the copy on my G4 Mac so that it use CPP interface to Gene's codes instead of the C interface - * 080103: add some further verbose printing - * 20080213: add interface functions to read single slice of a tiff stack, or the respective thumbnail: Note that the lsm and tif interfaces are DIfferent! - * 20080301: add handling of 12/16 bit LSM - * 20080302: change the include "basic_memory.h" to .cpp, due to the template instantiation in V3D - * 20080401: add the ifndef tag as this will often be included in other files - * 20080828: add file size limitation, so avoid loading too big file that may cause the tif reader to crash - * 20080930: return the original tiff pixel value but not the automatically scaled down version - * 20081204: add overload functions to read only a channel of a stack - * 20090413: add simple MRC file reading and writing - * 20090802: add raw5d read/write - * 20100520: try to revise ZZBIG to allow big file, also add fstat check for windows large file size , instead of using fseek and ftell - * 20100816: add mylib interface, by PHC. - * 20110708: fix a memory leak (non-crashing) of redudnant memory allocation of a sz variable - * 20110804: fix a new Mac fread issue to read more than 2G data in one call (I don't believe I saw this on the old Leopard 64 bit Mac Pro desktop, as we (both Zongcai and I should have) - * benched tested the >3G v3draw file read. This problem is not found for Linux 64bit. Is that a new Mac std libc bug?? - * Anyway, I have now used a 2G buffer to read >2G data. I have not changed the saveStack2Raw functions. It seems they work in the Matlab mex functions. Thus I assumed - * they don't need to change. Need tests anyway. - * 20120410: fix a bug when strcasecmp_l() taking a NULL parameter so that it crashes - */ - - -// 64-bit and 32-bit checking -// Windows -#if _WIN32 || _WIN64 -#if _WIN64 -#define ENVIRONMENT64 -#else -#define ENVIRONMENT32 -#endif -#endif - -// GCC -#if __GNUC__ -#if __x86_64__ || __ppc64__ -#define ENVIRONMENT64 -#else -#define ENVIRONMENT32 -#endif -#endif - -//#include "../elementmexheader.h" - -#include -#include -#include -#include - -#include "RawFmtMngr.h" - -#include "IM_config.h" -using namespace iim; - -//#include "basic_memory.cpp" //change basic_memory.h to basic_memory.cpp, 080302 - -/* -extern "C" { -*/ -//#include "mg_image_lib.h" -/* -}; -*/ - -#define b_VERBOSE_PRINT 0 -#define ZZBIG 10000 //previous I define it as 1500, so that to limit the size of an image is at most 1.5G //change 2010-05-21 // hang 2011-08-25 6000->10000 - -#ifdef _MSC_VER //2010-05-21, by PHC -#include -#include -#endif - -#define DEFINE_NBYTE2G \ - V3DLONG nBytes2G = (V3DLONG(1024)*V3DLONG(1024)*V3DLONG(1024)-1)*V3DLONG(2); - -static char err_message[5000]; // a pointer to this message is returned when there is an exception - - -/**************************************************** - * AUXILIARY FUNCTIONS - ****************************************************/ - -/* function to check endianness of the machine - * returns: - * L for little endian machines - * B for big endian machines - * M for machines that swap 16-bits words - * N for unknown endianness - */ -static -char checkMachineEndian() -{ - char e='N'; //for unknown endianness - - V3DLONG a=0x44332211; // eliminated 'int' - unsigned char * p = (unsigned char *)&a; - if ((*p==0x11) && (*(p+1)==0x22) && (*(p+2)==0x33) && (*(p+3)==0x44)) - e = 'L'; - else if ((*p==0x44) && (*(p+1)==0x33) && (*(p+2)==0x22) && (*(p+3)==0x11)) - e = 'B'; - else if ((*p==0x22) && (*(p+1)==0x11) && (*(p+2)==0x44) && (*(p+3)==0x33)) - e = 'M'; - else - e = 'N'; - - //printf("[%c] \n", e); - return e; -} - - -/* functions to swap 2-bytes and 4-bytes words */ - -static -void swap2bytes(void *targetp) -{ - unsigned char * tp = (unsigned char *)targetp; - unsigned char a = *tp; - *tp = *(tp+1); - *(tp+1) = a; -} - -static -void swap4bytes(void *targetp) -{ - unsigned char * tp = (unsigned char *)targetp; - unsigned char a = *tp; - *tp = *(tp+3); - *(tp+3) = a; - a = *(tp+1); - *(tp+1) = *(tp+2); - *(tp+2) = a; -} - -/* This function opens 2-4D image stack from raw data and returns metadata contained in the header - * assuming that sz elements are stored as 4-bytes integers. - * The input parameters sz, and datatype should be empty, especially the pointer "sz". - * The file is closed. - */ -static -char *loadMetadata ( char * filename, V3DLONG * &sz, int &datatype, int &b_swap, int &header_len ) { - - FILE * fid = fopen(filename, "rb"); - if (!fid) - return ((char *)"Fail to open file for reading"); - - fseek (fid, 0, SEEK_END); - V3DLONG fileSize = ftell(fid); - rewind(fid); - - /* Read header */ - - char formatkey[] = "raw_image_stack_by_hpeng"; - V3DLONG lenkey = strlen(formatkey); - - // for 4 byte integers: datatype has 2 bytes, and sz has 4*4 bytes and endian flag has 1 byte - // WARNINIG: this should still be valid even for 2 byte integres assuming that there are at least 8 data bytes - if (fileSize0) - { - V3DLONG curReadBytes = (remainingBytesimg[myii]) minvv=img[myii]; - // else if (maxvv 31 ) { - // printf("%d %d %d %d\n",c,slice,j,img[c][j]); - // a = 1; - // break; - // } - fseek(fid,(long)(header_len + c*block_size + slice*slice_size),SEEK_SET); - fwrite((img + (c*slice_size)),sizeof(unsigned char),slice_size,fid); - //if ( a ) - // closeRawFile(fid); - } - - closeRawFile(fid); - - delete []sz; - - return 0; -} - - -char *copyRawFileBlock2Buffer ( char *filename, int sV0, int sV1, int sH0, int sH1, int sD0, int sD1, - unsigned char *buf, int pxl_size, sint64 offs, sint64 stridex, sint64 stridexy, sint64 stridexyz ) { - - //if ( pxl_size != sizeof(unsigned char) ) - //{ - // return ((char *)"Wrong pixel size.\n"); - //} - - char *err_rawfmt; - FILE *fid; - void *fhandle; - V3DLONG *sz = 0; - int datatype; - int b_swap; - int header_len; - - if ( (err_rawfmt = loadRaw2Metadata(filename,sz,datatype,b_swap,fhandle,header_len)) != 0 ) { - if ( sz ) delete[] sz; - return err_rawfmt; - } - if ( datatype != pxl_size ) - { - delete []sz; - return ((char *)"requested and native data types are different.\n"); - } - fid = (FILE *) fhandle; - - fseek (fid, 0, SEEK_END); - //V3DLONG fileSize = ftell(fid); // unused - rewind(fid); - - V3DLONG unitSize = datatype; /* temporarily I use the same number, which indicates the number of bytes for each data point (pixel). This can be extended in the future. */ - - V3DLONG startx = sH0; - V3DLONG starty = sV0; - V3DLONG startz = sD0; - V3DLONG endx = sH1; - V3DLONG endy = sV1; - V3DLONG endz = sD1; - - V3DLONG tmpw = endx - startx; // width of sub block - V3DLONG tmph = endy - starty; // height of sub block - V3DLONG tmpz = endz - startz; // depth of sub block - - V3DLONG head = header_len; //4*4+2+1+lenkey; // header_len ? - V3DLONG pgsz1=sz[2]*sz[1]*sz[0]; // #values per channel - V3DLONG pgsz2=sz[1]*sz[0]; // #values per slice - V3DLONG pgsz3=sz[0]; - //V3DLONG cn = tmpw*tmph*tmpz; // unused - //V3DLONG kn = tmpw*tmph; // unused - //V3DLONG total = tmpw*tmph*tmpz*sz[3]; // unused - - //V3DLONG count=0; // unused - V3DLONG c,i,j,k; - - unsigned char *buftmp_c; - unsigned char *buftmp_k; - unsigned char *buftmp_j; - - /* swap the data bytes if necessary */ - - if (b_swap==1 && unitSize>1 ) // endianess is different and pixels are longer than 1 byte - { - for (c=0, buftmp_c=(buf + (offs*unitSize)); cn_blocks; i++ ) { - if ( (err_rawfmt = loadRaw2Metadata(streamer->bDescr[i].filename, - sz,datatype,b_swap,fhandle,header_len)) != 0 ) { - if ( sz ) delete[] sz; - return err_rawfmt; - } - streamer->bDescr[i].fhandle = fhandle; - } - - if ( sz ) delete[] sz; - - return 0; -} - -char *streamer_dostep ( Streamer_Descr_t *streamer, unsigned char *buffer2 ) { - - streamer->cur_step++; - - if ( streamer->cur_step > streamer->steps ) { - return ((char *)"Too many steps in a streamed operation.\n"); - } - - for ( int i=0; in_blocks; i++ ) { - - if ( streamer->cur_step > streamer->bDescr[i].step_r ) { // from now the number of stripes to be copied is decremented by 1 - streamer->bDescr[i].step_n--; - streamer->bDescr[i].step_r = streamer->steps; // guarantees that next times this clause should be skipped - } - - // copy step_n stripes of i-th sub-block from file to buffer - FILE *fid; - fid = (FILE *) streamer->bDescr[i].fhandle; - - fseek (fid, 0, SEEK_END); - //V3DLONG fileSize = ftell(fid); // unused - rewind(fid); - - V3DLONG unitSize = streamer->bDescr[i].datatype; /* temporarily I use the same number, which indicates the number of bytes for each data point (pixel). This can be extended in the future. */ - - int bstridey = (int) (streamer->stridexy / streamer->stridex); // stridey of buffer - int fstridey = (int) (streamer->bDescr[i].stridexy / streamer->bDescr[i].stridex); // stridey of file - - for ( int c=0; cn_chans; c++ ) { - - // set initial pointer to buffer; each channel starts from the same relative position - unsigned char *buftmp = streamer->buf + ((c * streamer->stridexyz) + - streamer->bDescr[i].boffs + streamer->stridex * (streamer->cur_step - 1)) * (int)unitSize; - - // beginning of second slice in the buffer - unsigned char *next_bslice = streamer->buf + ((c * streamer->stridexyz) + - streamer->bDescr[i].boffs + streamer->bDescr[i].height * streamer->stridex) * (int)unitSize; - - // set initial position of file; each channel starts from the same relative position - sint64 postmp = streamer->bDescr[i].header_len + ((c * streamer->bDescr[i].stridexyz) + - streamer->bDescr[i].foffs + streamer->bDescr[i].stridex * (streamer->cur_step - 1)) * (int)unitSize; - - // beginning of second slice in the file - sint64 next_fslice = streamer->bDescr[i].header_len + ((c * streamer->bDescr[i].stridexyz) + - streamer->bDescr[i].foffs + streamer->bDescr[i].height * streamer->bDescr[i].stridex) * (int)unitSize; - - for (int s=0; sbDescr[i].step_n; s++, - buftmp+=streamer->steps * streamer->stridex * (int)unitSize, - postmp+=streamer->steps * streamer->bDescr[i].stridex * (int)unitSize ) { - // before the copy, the pointer to buffer and the file position has to be advanced of steps stripes - - if ( buftmp >= next_bslice ) { // moved to next buffer slice - //further incease the pointer to buffer to skip other sub-blocks - buftmp += streamer->stridex * (bstridey - streamer->bDescr[i].height) * (int)unitSize; - next_bslice += streamer->stridexy * (int)unitSize; - } - if ( postmp >= next_fslice ) { // moved to next file slice - //further incease the position into file to skip other sub-blocks - postmp += streamer->bDescr[i].stridex * (fstridey - streamer->bDescr[i].height) * (int)unitSize; - next_fslice += streamer->bDescr[i].stridexy * (int)unitSize; - } - - // copy one stripe - rewind(fid); - fseek(fid,(long)postmp,SEEK_SET); - int dummy = (int)ftell(fid); - dummy = (int)fread(buftmp,unitSize,streamer->bDescr[i].width,fid); - - // WARNING: code for testing - if ( buffer2 ) { - for ( int j=0; jbDescr[i].width; j++ ) { - unsigned char *buftmp2 = buffer2 + (buftmp - streamer->buf); - if ( buftmp[j]!=buftmp2[j] ) { - //printf("%d %d\n",buftmp[j],buftmp2[j]); - return ((char *)"Mismatch between streamed and non-streamed operation.\n"); - } - } - } - } - } - } - - return 0; -} - -char *streamer_cpydata ( Streamer_Descr_t *streamer, unsigned char *buffer, unsigned char *buffer2 ) { - - if ( streamer->cur_step > streamer->steps ) { - return ((char *)"Too many steps in a streamed operation.\n"); - } - - for ( int i=0; in_blocks; i++ ) { - - V3DLONG unitSize = streamer->bDescr[i].datatype; /* temporarily I use the same number, which indicates the number of bytes for each data point (pixel). This can be extended in the future. */ - - int bstridey = (int) (streamer->stridexy / streamer->stridex); // stridey of buffer - //int fstridey = (int) (streamer->bDescr[i].stridexy / streamer->bDescr[i].stridex); // stridey of file (unused) - - for ( int c=0; cn_chans; c++ ) { - - // set initial pointer to buffers; each channel starts from the same relative position - unsigned char *sbuftmp = streamer->buf + ((c * streamer->stridexyz) + - streamer->bDescr[i].boffs + streamer->stridex * (streamer->cur_step - 1)) * (int)unitSize; - unsigned char *dbuftmp = buffer + (sbuftmp - streamer->buf); - - // beginning of second slice in the buffer - unsigned char *next_bslice = streamer->buf + ((c * streamer->stridexyz) + - streamer->bDescr[i].boffs + streamer->bDescr[i].height * streamer->stridex) * (int)unitSize; - - for (int s=0; sbDescr[i].step_n; s++, - sbuftmp+=streamer->steps * streamer->stridex * (int)unitSize, - dbuftmp+=streamer->steps * streamer->stridex * (int)unitSize ) { - // before the copy, the pointers to both buffer have to be advanced of steps stripes - - if ( sbuftmp >= next_bslice ) { // moved to next buffer slice - //further incease the pointer to buffer to skip other sub-blocks - sbuftmp += streamer->stridex * (bstridey - streamer->bDescr[i].height) * (int)unitSize; - dbuftmp += streamer->stridex * (bstridey - streamer->bDescr[i].height) * (int)unitSize; - next_bslice += streamer->stridexy * (int)unitSize; - } - - // copy one stripe - memcpy(dbuftmp,sbuftmp,streamer->bDescr[i].width); - //memcpy(dbuftmp,sbuftmp,streamer->stridex); - - // WARNING: code for testing - if ( buffer2 ) { - for ( int j=0; jbDescr[i].width; j++ ) { - unsigned char *buftmp2 = buffer2 + (sbuftmp - streamer->buf); - if ( dbuftmp[j]!=buftmp2[j] ) { - //printf("%d %d\n",buftmp[j],buftmp2[j]); - return ((char *)"Mismatch between streamed and non-streamed operation.\n"); - } - } - } - } - } - } - - return 0; -} - -char *streamer_close ( Streamer_Descr_t *streamer ) { - - for ( int i=0; in_blocks; i++ ) { - closeRawFile(streamer->bDescr[i].fhandle); - } - - return 0; -} - - -/***************************** Streamer_Descr_t METHODS *****************************/ - -Streamer_Descr_t::Streamer_Descr_t ( unsigned char *_buf, int _pxl_size, sint64 _stridex, sint64 _stridexy, sint64 _stridexyz, sint64 _n_chans, int _steps ) { - buf = _buf; - pxl_size = _pxl_size; - stridex = _stridex; - stridexy = _stridexy; - stridexyz = _stridexyz; - n_chans = _n_chans; - steps = _steps; - max_blocks = DEFAULT_MAX_BLOCKS; - n_blocks = 0; - bDescr = new Block_Descr_t[DEFAULT_MAX_BLOCKS]; - cur_step = 0; // the first step is 1 -} - -Streamer_Descr_t::~Streamer_Descr_t ( ) -{ - - if ( bDescr ) { - for ( int i=0; isteps + 1; // in case the remainder is not 0 - bDescr[n_blocks].step_r = bDescr[n_blocks].n_stripes % this->steps; - bDescr[n_blocks].fhandle = 0; - bDescr[n_blocks].filename = new char[strlen(filename)+1]; - strcpy(bDescr[n_blocks].filename,filename); - bDescr[n_blocks].datatype = datatype; - bDescr[n_blocks].header_len = header_len; - - n_blocks++, - - // terminates - delete []sz; - - return 0; -} - -/********* SUPPORT TO VISUALIZATION OF 16/32 BITS PER CHANNEL ***********/ - -char *convert2depth8bits ( int red_factor, sint64 totalBlockSize, sint64 sbv_channels, uint8 *&subvol, iim::uint8 *dstbuf ) { - int c, i, j, p; - sint64 totalUnits = totalBlockSize * sbv_channels; - - char endianCodeMachine = checkMachineEndian(); - if ( endianCodeMachine == 'L' ) { - j = red_factor - 1; // MSB is the last - } - else if ( endianCodeMachine == 'B' ) { - j = 0; // MSB is the first - } - else { - return ((char *) "unknown machine endianess"); - } - - // look for maximum values in each channel and rescale each channel separately - unsigned short maxVal; - unsigned short *temp = (unsigned short *) subvol; - sint64 count; - for ( c=0; c maxVal ) - maxVal = temp[i]; - for ( i=1, p=8*red_factor; i (0.5*maxVal) ) - count++; - temp[i] <<= p; - } - //printf("\t\t\t\tin RawFmtMngr - convert2depth8bits: c=%d, maxVal=%d, p=%d, count=%lld\n\n",c,maxVal,p,count); - } - - uint8 *temp_buf = dstbuf ? dstbuf : new uint8[totalUnits]; - memset(temp_buf,0,totalUnits); - for ( i=0; i -#define V3DLONG int64_t //long long -#define fseek _fseeki64 -#define ftell _ftelli64 - -#else - -#define V3DLONG long - -#endif - - -typedef char BIT8_UNIT; -typedef short int BIT16_UNIT; -typedef int BIT32_UNIT; -typedef V3DLONG BIT64_UNIT; - -# define DEFAULT_MAX_BLOCKS 27 - -/* structure containing data to manage a sub-block in a streamed copy - */ -struct Block_Descr_t { - char *filename; // complete path of file containing the sub-block - void *fhandle; // handle to file containing the sub-block - int datatype; // size of pixel in bytes - int header_len; // header length - iim::sint64 foffs; // offset in the file from which start next copy step - iim::sint64 boffs; // offset in the buffer from which start next copy step - iim::sint64 stridex; // stripe stride of the 3D image stored in the file - iim::sint64 stridexy; // slice stride of the 3D image stored in the file - iim::sint64 stridexyz; // block stride of the 3D image stored in the file - int width; // width of stripes to be copied - int height; // height of slices to be copied - int n_stripes; // total number of stripes to be copied - int step_n; // number of stripes to be copied in the next step - int step_r; // number of steps after which step_n has to decremented by 1 -}; - -class Streamer_Descr_t { - -public: - unsigned char *buf; // pointer to 3D buffer in which sub-blocks have to be copied - int pxl_size; // buffer pixel size in bytes - iim::sint64 stridex; // line stride of the 3D buffer - iim::sint64 stridexy; // slice stride of the 3D buffer - iim::sint64 stridexyz; // block stride of the 3D buffer (pixels in one channel) - iim::sint64 n_chans; // number of channels in the buffer - int steps; // steps in which the copy jas to be decomposed - Block_Descr_t *bDescr; // array of sub-blocks decriptors - int max_blocks; // maximum elements of bDescr - int n_blocks; // number of sub-blocks descriptors - int cur_step; // current step - -public: - Streamer_Descr_t ( unsigned char *_buf, int _pxl_size, iim::sint64 _stridex, iim::sint64 _stridexy, iim::sint64 _stridexyz, iim::sint64 _n_chans, int _steps ); - - ~Streamer_Descr_t ( ); - - char *addSubBlock ( char *filename, iim::sint64 boffs, int sV0, int sV1, int sH0, int sH1, int sD0, int sD1 ); -}; - - -/***************************** FUNCTION HEADERS *****************************/ - -char *loadRaw2Metadata ( char * filename, V3DLONG * &sz, int &datatype, int &b_swap, void * &fhandle, int &header_len ); -/* opens the file filename in raw format containing a 4D image and returns in parameters: - * sz: a four component array containing image dimensions along horizontal (x), - * vertical (y), depth (z) directions, and the number of channels - * datatype: the number of bytes per pixel - * b_swap: a 0/1 value that indicates if endianness of the file is the same (0) or - * is different (1) from the one of the current machine - * fhandle: a pointer to a FILE structure associated to the file which is left opened - * - * the file is not closed - * - * if some exception occurs, returns a string describing the exception; returns a NULL pointer - * if there are no exceptions - */ - -void closeRawFile ( void *fhandle ); -/* closes the file associated to fhandle which is a pointer to e FILE structure */ - -char *loadRaw2SubStack ( void *fhandle, unsigned char *img, V3DLONG *sz, - V3DLONG startx, V3DLONG starty, V3DLONG startz, - V3DLONG endx,V3DLONG endy, V3DLONG endz, - int datatype, int b_swap, int header_len ); //4-byte raw reading -/* read a substack of the 4D image stored in raw format in the file associated to fhandle - * input parameters: - * image: a pointer to an empty buffer large enough to contain the substack - * sz: a four component array containing image dimensions along horizontal (x), - * vertical (y), depth (z) directions, and the number of channels - * startx: index along x of the pixel which is the first vertex of the substack - * starty: index along y of the pixel which is the first vertex of the substack - * startz: index along z of the pixel which is the first vertex of the substack - * endx: index along x of the pixel which is the last vertex of the substack - * endy: index along y of the pixel which is the last vertex of the substack - * endz: index along z of the pixel which is the last vertex of the substack - * datatype: the number of bytes per pixel - * b_swap: a 0/1 value that indicates if endianness of the file is the same (0) or - * is different (1) from the one of the current machine - * header_len: the length of the header in bytes - * - * if some exception occurs, returns a string describing the exception; returns a NULL pointer - * if there are no exceptions - */ - - -char *loadRaw2WholeStack(char * filename, unsigned char * & img, V3DLONG * & sz, int & datatype); //4-byte raw reading -/* opens and reads the file filename in raw format containing a 4D image and returns - * in parameters: - * img: a pointer to a newly allocated buffer where the whole image is stored - * one channel after another - * sz: a four component array containing image dimensions along horizontal (x), - * vertical (y), depth (z) directions, and the number of channels - * datatype: the number of bytes per pixel - * - * if some exception occurs, returns a string describing the exception; returns a NULL pointer - * if there are no exceptions - */ - -char *saveWholeStack2Raw(const char * filename, unsigned char *img, V3DLONG *sz, int datatype); //4-byte raw reading -/* save a 4D image in raw format - * in parameters: - * img: a pointer to the buffer where the whole image is stored - * one channel after another - * sz: a four component array containing image dimensions along horizontal (x), - * vertical (y), depth (z) directions, and the number of channels - * datatype: the number of bytes per pixel - * - * if some exception occurs, returns a string describing the exception; returns a NULL pointer - * if there are no exceptions - */ - -char *initRawFile ( char *filename, const V3DLONG *sz, int datatype ); -/* creates a file containing an empty 3D, multi-channel image - * - * filename: complete path of the file to be initialized - * sz: 4-element array containing width, height, depth and the number of channels - * datatype: pixel size in bytes - */ - -char *writeSlice2RawFile ( char *filename, int slice, unsigned char *img, int img_height, int img_width ); -/* writes one slice to a file containing a 3D image - * - * filename: complete path of the file to be modified - * img: pointer to slice (2D buffer) - * img_height: height of the slice - * img_width: width of the slice - */ - -char *copyRawFileBlock2Buffer ( char *filename, int sV0, int sV1, int sH0, int sH1, int sD0, int sD1, - unsigned char *buf, int pxl_size, iim::sint64 offs, iim::sint64 stridex, iim::sint64 stridexy, iim::sint64 stridexyz ); -/* copies a block in file 'filename' to a region of 3D buffer buf - * - * filename: complete path of the file to be read - * sv0, ..., sD0: indices of the up, left, front pixel of the block stored in 'filename' - * sv1, ..., sD1: indices of the bottom, right, back pixel of the block stored in 'filename' - * buf: pointer to buffer to be filled - * pxl_size: pixel size in bytes - * offs: offset on buf from which the copy has to start - * stridex: number of pixels of the 3D buffer along x (H) dimension - * stridexy: number of pixels in one slice of the 3D buffer (plane xy or VH) - * stridexyz: number of pixels in one channel of the 3D buffer (volume xyz or VHD) - * - * WARNING: current implementation assumes that datatype is 1-byte pixels and that - * the endianess of the machine is the same as that of the machine that generated the - * data in 'filename' - */ - -char *streamer_open ( Streamer_Descr_t *streamer ); -/* initilizes a streamed load operation based on the content of the descriptor 'streamer' - */ - -char *streamer_dostep ( Streamer_Descr_t *streamer, unsigned char *buffer2=0 ); -/* performs one step of the streamed operation specified by 'streamer' - * if the second parameter is not a null pointer, uses it to check if data copied into - * the operation buffer is exactly the same as that contained in buffer2 - */ - -char *streamer_cpydata ( Streamer_Descr_t *streamer, unsigned char *buffer, unsigned char *buffer2=0 ); -/* copies the last data read from files to buffer - * positions in which data are copied depend on the which data have been read in - * the last step - */ - -char *streamer_close ( Streamer_Descr_t *streamer ); -/* closes the streamed operation specified by 'streamer' - */ - -char *convert2depth8bits ( int red_factor, iim::sint64 totalBlockSize, iim::sint64 sbv_channels, iim::uint8 *&subvol, iim::uint8 *dstbuf = 0 ); -/* convert the buffer pointed by subvol to 8 bits per channel - * - * red_factor: number of bytes per channel in the input buffer - * (reduction factor for the conversion to 8 bits: must be > 1) - * totalBlockSize: number of voxels in each channel (sbv_height*sbv_width*sbv_depth) - * sbv_channels: number of channels - * subvol: buffer to be converted (of length totalBlockSize*sbv_channels*red_factor) - * the input buffer is always deallocated before returning - * if dstbuf = 0, a newly allocated converted buffer (of length totalBlockSize*sbv_channels) is returned - * otherwise dstbuf buffer is returned - * dstbuf: if != 0 points to destination buffer (which has been allocated by the caller) - */ - -#endif - - - diff --git a/v3d_main/terafly/src/core/imagemanager/RawVolume.cpp b/v3d_main/terafly/src/core/imagemanager/RawVolume.cpp deleted file mode 100644 index af23193977..0000000000 --- a/v3d_main/terafly/src/core/imagemanager/RawVolume.cpp +++ /dev/null @@ -1,274 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -******************* -* 2015-12-10. Giulio. @ADDED support for single Tiff 3D volumes -*/ - -# include "RawVolume.h" -#include "VirtualFmtMngr.h" -#include "iomanager.config.h" - -# include - -using namespace iim; - -static char *get_path ( const char *_file_name ) throw (IOException); - -RawVolume::RawVolume(const char* _file_name) throw (IOException) -: VirtualVolume(get_path(_file_name), 1.0f, 1.0f, 1.0f) -{ - /**/iim::debug(iim::LEV3, strprintf("_file_name = \"%s\"", _file_name).c_str(), __iim__current__function__); - - this->file_name = new char[strlen(_file_name)+1]; - strcpy(this->file_name, _file_name); - - ffmt = ""; - fmtMngr = 0; - - init(); - initChannels(); -} - - -RawVolume::~RawVolume(void) -{ - /**/iim::debug(iim::LEV3, 0, __iim__current__function__); - - if(file_name) - delete[] file_name; - if (img) - delete[] img; - if (sz) - delete[] sz; - if (fhandle) - closeRawFile(fhandle); - - if ( fmtMngr ) - delete fmtMngr; -} - - -void RawVolume::init ( ) throw (IOException) -{ - /**/iim::debug(iim::LEV3, 0, __iim__current__function__); - - /************************* 1) LOADING STRUCTURE ************************* - *************************************************************************/ - - img = (unsigned char *) 0; - sz = (iim::sint64 *) 0; - fhandle = (void *) 0; - b_swap = 0; - header_len = -1; - - //int berror = loadRaw2Stack(file_name,img,sz,datatype); - - // get the file format of the blocks - char *temp = file_name+strlen(file_name)-3; - if ( strcmp(temp,"tif")==0 ) { - ffmt = "Tiff3D"; - // 2015-02-27. Alessandro. @ADDED automated selection of IO plugin if not provided. - if(iom::IMIN_PLUGIN.compare("empty") == 0) - iom::IMIN_PLUGIN = "tiff3D"; - fmtMngr = new Tiff3DFmtMngr(); - } - else if ( strcmp(temp,"raw")==0 ) { - ffmt = "Vaa3DRaw"; - fmtMngr = new Vaa3DRawFmtMngr(); - } - else { - char msg[STATIC_STRINGS_SIZE]; - sprintf(msg,"in RawVolume::init(...): Unknown file format \"%s\"", temp); - throw IOException(msg); - } - - char *internal_msg; - if ( (internal_msg = fmtMngr->loadMetadata(file_name,sz,datatype,b_swap,fhandle,header_len)) ) { - if ( sz ) delete[] sz; - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"RawVolume::init: error in loading metadata - %s",internal_msg); - throw IOException(err_msg); - } - // fhandle must remain opened since it is a private member of RawVolume - // @FIXED by Alessandro on 2014-03-29: fhandle MUST BE CLOSED, otherwise it is not possible to open more than 1000 files - fmtMngr->closeFile(fhandle); - fhandle = 0; - - DIM_V = (uint32) sz[1]; // in raw format first dimension is horizontal - DIM_H = (uint32) sz[0]; - DIM_D = (uint32) sz[2]; - - // sz shold not be deallocated -} - -void RawVolume::initChannels ( ) throw (IOException) -{ - /**/iim::debug(iim::LEV3, 0, __iim__current__function__); - - DIM_C = (int) sz[3]; - BYTESxCHAN = datatype; - - n_active = DIM_C; - active = new uint32[n_active]; - for ( int c=0; cBYTESxCHAN > 2 ) { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"RawVolume::loadSubvolume_to_UINT8: invalid number of bytes per channel (%d)",this->BYTESxCHAN); - throw IOException(err_msg); - } - - if ( (ret_type == iim::DEF_IMG_DEPTH) && ((8 * this->BYTESxCHAN) != iim::DEF_IMG_DEPTH) ) { - // return type is 8 bits, but native depth is not 8 bits - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"RawVolume::loadSubvolume_to_UINT8: non supported return type (%d bits) - native type is %d bits",ret_type, 8*this->BYTESxCHAN); - throw IOException(err_msg); - } - - // check #channels - //if ( CHANS == 1 ) - // *channels = 1; - //else if ( CHANS <=3 ) - // *channels = 3; - //else { - // char err_msg[STATIC_STRINGS_SIZE]; - // sprintf(err_msg,"RawVolume::loadSubvolume_to_UINT8: too many channels [%d]",CHANS); - // throw iim::IOException(err_msg); - //} - if(channels) - *channels = DIM_C; // returns the exact number of channels; - else - channels = &DIM_C; - // WARNING: the caller must check if it suppports only 1 or 3 channels - - //initializations - V0 = (V0 == -1 ? 0 : V0); - V1 = (V1 == -1 ? DIM_V : V1); - H0 = (H0 == -1 ? 0 : H0); - H1 = (H1 == -1 ? DIM_H : H1); - D0 = (D0 == -1 ? 0 : D0); - D1 = (D1 == -1 ? DIM_D : D1); - - // allocate buffer - sint64 sbv_height = V1 - V0; - sint64 sbv_width = H1 - H0; - sint64 sbv_depth = D1 - D0; - sint64 total_buf_size = sbv_height * sbv_width * sbv_depth * (*channels) * datatype; - uint8 *subvol = new uint8[total_buf_size]; - memset(subvol,0,sizeof(uint8)*total_buf_size); - - //// @ADDED by Alessandro on 2014-03-29: re-opening the file if needed - //if(fhandle == 0) - // fhandle = static_cast(fopen(file_name, "rb")); - // @CHANGED by Giulio on 2015-12-07: support to Tiff3D assumes that the file has been closed - if (fhandle) - closeRawFile(fhandle); - - char *internal_msg=0; - //if ( (internal_msg = loadRaw2SubStack(fhandle,subvol,sz,H0,V0,D0,H1,V1,D1,datatype,b_swap,header_len)) ) { - if ( (internal_msg = fmtMngr->copyFileBlock2Buffer( - file_name, - V0,V1,H0,H1,D0,D1, - (unsigned char *)subvol, - (int)datatype, // this is native rtype, it has substituted sizeof(iim::uint8) - 0, // offset is always 0 since all data are copied once - sbv_width, - sbv_width*sbv_height, - sbv_width*sbv_height*sbv_depth) ) != 0 ) { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"RawVolume::init: error in loading metadata - %s",internal_msg); - throw IOException(err_msg); - } - - //// @FIXED by Alessandro on 2014-03-29: the file MUST be closed, otherwise the maximum number of opened files will be reached - //closeRawFile(fhandle); - // @CHANGED by Giulio on 2015-12-07: support to Tiff3D assumes that the file has been closed by copyFileBlock2Buffer - fhandle = 0; - - return subvol; -} - - - -# define PATH_BUF_LEN 5000 - -static char path_buffer[PATH_BUF_LEN]; -static const char *suffixes[] = { ".raw", ".RAW", ".v3draw", ".V3DRAW", ".tif", "" }; -static int suf_lens[] = { 3, 3, 6, 6, 3 }; - -char *get_path ( const char *_file_name ) throw (IOException) { - strcpy(path_buffer,_file_name); - char *tPtr = 0; - for ( int i=0; !tPtr && *suffixes[i] != '\0'; i++ ) - // check only if last characters match the suffix - tPtr = strstr(path_buffer+strlen(path_buffer)-suf_lens[i]-1,suffixes[i]); - if ( !tPtr ) { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"RawVolume::get_path: unknown suffix of source file"); - throw IOException(err_msg); - } - tPtr--; - while ( *tPtr != '\\' && *tPtr != '/' ) - tPtr--; - *(tPtr+1) = '\0'; - return path_buffer; -} diff --git a/v3d_main/terafly/src/core/imagemanager/RawVolume.h b/v3d_main/terafly/src/core/imagemanager/RawVolume.h deleted file mode 100644 index c0c5942266..0000000000 --- a/v3d_main/terafly/src/core/imagemanager/RawVolume.h +++ /dev/null @@ -1,90 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -******************* -* 2015-12-10. Giulio. @ADDED support for single Tiff 3D volumes -*/ - -# ifndef _RAW_VOLUME_H -# define _RAW_VOLUME_H - -# include "VirtualVolume.h" -# include "RawFmtMngr.h" - -typedef char BIT8_UNIT; -typedef short int BIT16_UNIT; -typedef int BIT32_UNIT; -typedef V3DLONG BIT64_UNIT; - - -class RawVolume : public iim::VirtualVolume -{ - private: - - char *file_name; - unsigned char *img; - iim::sint64 *sz; - int datatype; - int b_swap; - int header_len; - - std::string ffmt; - iim::VirtualFmtMngr *fmtMngr; - - void *fhandle; - - void init ( ) throw (iim::IOException); - - // iannello returns the number of channels of images composing the volume - void initChannels ( ) throw (iim::IOException); - - public: - - RawVolume(const char* _file_name) throw (iim::IOException); - - ~RawVolume(void); - - // returns a unique ID that identifies the volume format - std::string getPrintableFormat(){return iim::RAW_FORMAT;} - - // added by Alessandro on 2014-02-18: additional info on the reference system (where available) - float getVXL_1() {return VXL_H;} - float getVXL_2() {return VXL_V;} - float getVXL_3() {return VXL_D;} - iim::axis getAXS_1() {return iim::horizontal;} - iim::axis getAXS_2() {return iim::vertical;} - iim::axis getAXS_3() {return iim::depth;} - - std::string getFFMT(){return ffmt;} - iim::VirtualFmtMngr *getFMT_MNGR(){return fmtMngr;} - - iim::real32 *loadSubvolume_to_real32(int V0=-1,int V1=-1, int H0=-1, int H1=-1, int D0=-1, int D1=-1) throw (iim::IOException); - - iim::uint8 *loadSubvolume_to_UINT8(int V0=-1,int V1=-1, int H0=-1, int H1=-1, int D0=-1, int D1=-1, - int *channels=0, int ret_type=iim::DEF_IMG_DEPTH) throw (iim::IOException); -}; -# endif diff --git a/v3d_main/terafly/src/core/imagemanager/SimpleVolume.cpp b/v3d_main/terafly/src/core/imagemanager/SimpleVolume.cpp deleted file mode 100644 index 7cc3e1e868..0000000000 --- a/v3d_main/terafly/src/core/imagemanager/SimpleVolume.cpp +++ /dev/null @@ -1,463 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -* 2015-04-15. Alessandro. @ADDED definition for default constructor. -* 2015-02-27. Alessandro. @ADDED automated selection of IO plugin if not provided. -* 2014-11-27 Giulio. @FIXED eliminated part of the dipendences from OpenCV and restored the corresponding code -* 2014-11-22 Giulio. @CHANGED code using OpenCV has been commente. It can be found searching comments containing 'Giulio_CV' -*/ - -#include "SimpleVolume.h" -#include "Stack.h" -#ifdef _WIN32 -#include "dirent_win.h" -#else -#include -#endif -#include -// Giulio_CV #include -// Giulio_CV #include -// Giulio_CV #include -#include "Tiff3DMngr.h" - -#include "IOPluginAPI.h" // 2014-11-26. Giulio. - -using namespace std; -using namespace iim; - -// 2015-04-15. Alessandro. @ADDED definition for default constructor. -SimpleVolume::SimpleVolume(void) : VirtualVolume() -{ - /**/iim::debug(iim::LEV3, 0, __iim__current__function__); - - N_ROWS = N_COLS = 0; - STACKS = 0; -} - -SimpleVolume::SimpleVolume(const char* _root_dir) throw (IOException) -: VirtualVolume(_root_dir, 1.0f, 1.0f, 1.0f) -{ - /**/iim::debug(iim::LEV3, strprintf("_root_dir = \"%s\"", root_dir).c_str(), __iim__current__function__); - - init(); - initChannels(); -} - - -SimpleVolume::~SimpleVolume(void) -{ - /**/iim::debug(iim::LEV3, 0, __iim__current__function__); - - if(STACKS) - { - for(int row=0; row stacks_list; //each stack found in the hierarchy is pushed into this list - char stack_i_j_path[STATIC_STRINGS_SIZE]; - - //obtaining DIR pointer to root_dir (=NULL if directory doesn't exist) - if (!(cur_dir_lev1=opendir(root_dir))) - { - char msg[STATIC_STRINGS_SIZE]; - sprintf(msg,"in SimpleVolume::init(...): Unable to open directory \"%s\"", root_dir); - throw IOException(msg); - } - closedir(cur_dir_lev1); - - // Simple format has only one stack - N_ROWS = 1; - N_COLS = 1; - - //allocating the only stack - sprintf(stack_i_j_path,"%s",""); - iim::Stack *new_stk = new iim::Stack(this,i,j,stack_i_j_path); - stacks_list.push_back(new_stk); - - //converting stacks_list (STL list of Stack*) into STACKS (2-D array of Stack*) - STACKS = new iim::Stack**[N_ROWS]; - for(int row=0; row < N_ROWS; row++) - STACKS[row] = new iim::Stack*[N_COLS]; - for(list::iterator i = stacks_list.begin(); i != stacks_list.end(); i++) - STACKS[(*i)->getROW_INDEX()][(*i)->getCOL_INDEX()] = (*i); - - /******************** 3) COMPUTING VOLUME DIMENSIONS ******************** - *************************************************************************/ - for(int row=0; row < N_ROWS; row++) - for(int col=0; col < N_COLS; col++) - { - if(row==0) - DIM_H+=STACKS[row][col]->getWIDTH(); - if(col==0) - DIM_V+=STACKS[row][col]->getHEIGHT(); - DIM_D = STACKS[row][col]->getDEPTH() > DIM_D ? STACKS[row][col]->getDEPTH() : DIM_D; - } - - /**************** 4) COMPUTING STACKS ABSOLUTE POSITIONS **************** - *************************************************************************/ - for(int row=0; row < N_ROWS; row++) - for(int col=0; col < N_COLS; col++) - { - if(row) - STACKS[row][col]->setABS_V(STACKS[row-1][col]->getABS_V()+STACKS[row-1][col]->getHEIGHT()); - else - STACKS[row][col]->setABS_V(0); - - if(col) - STACKS[row][col]->setABS_H(STACKS[row][col-1]->getABS_H()+STACKS[row][col-1]->getWIDTH()); - else - STACKS[row][col]->setABS_H(0); - } -} - -void SimpleVolume::initChannels ( ) throw (IOException) -{ - /**/iim::debug(iim::LEV3, 0, __iim__current__function__); - - char slice_fullpath[STATIC_STRINGS_SIZE]; - int img_width; - int img_height; - std::string params; - - - sprintf(slice_fullpath, "%s/%s/%s", root_dir, STACKS[0][0]->getDIR_NAME(), STACKS[0][0]->getFILENAMES()[0]); - - try - { - iomanager::IOPluginFactory::getPlugin2D("tiff2D")->readMetadata(slice_fullpath, img_width, img_height, BYTESxCHAN, DIM_C, params); - } - catch (iom::exception & ex) - { - throw iim::IOException(ex.what()); - } - - /* Giulio_CV - - IplImage* slice = cvLoadImage(slice_fullpath, CV_LOAD_IMAGE_ANYDEPTH | CV_LOAD_IMAGE_ANYCOLOR); //without CV_LOAD_IMAGE_ANYDEPTH, image is converted to 8-bits if needed - if(!slice) - throw IOException(std::string("Unable to load slice at \"").append(slice_fullpath).append("\"").c_str()); - DIM_C = slice->nChannels; - if ( slice->depth == IPL_DEPTH_8U ) - BYTESxCHAN = 1; - else if ( slice->depth == IPL_DEPTH_16U ) - BYTESxCHAN = 2; - else if ( slice->depth == IPL_DEPTH_32F ) - BYTESxCHAN = 4; - else { - char msg[STATIC_STRINGS_SIZE]; - sprintf(msg,"in SimpleVolume::initChannels: unknown color depth"); - throw IOException(msg); - } - - */ - - n_active = DIM_C; - active = new uint32[n_active]; - for ( int c=0; cIntersects(subvol_area); - if(intersect_area) - { - STACKS[row][col]->loadStack(D0, D1-1); - - for(int k=0; kgetSTACKED_IMAGE()[D0+k]; - int step = slice->step/sizeof(float); - float *data = slice->data.fl; - int ABS_V_stk = STACKS[row][col]->getABS_V(); - int ABS_H_stk = STACKS[row][col]->getABS_H(); - - for(int i=intersect_area->V0-V0; iV1-V0; i++) - for(int j=intersect_area->H0-H0; jH1-H0; j++) - subvol[k*sbv_height*sbv_width + i*sbv_width + j] = (data+(i-ABS_V_stk+V0)*step)[j-ABS_H_stk+H0]; - } - - // allocated space has to always released - STACKS[row][col]->releaseStack(); - } - } - - */ - - return subvol; -} - - -uint8 *SimpleVolume::loadSubvolume_to_UINT8(int V0,int V1, int H0, int H1, int D0, int D1, int *channels, int ret_type) throw (IOException) { - - /**/iim::debug(iim::LEV3, strprintf("V0=%d, V1=%d, H0=%d, H1=%d, D0=%d, D1=%d, *channels=%d, ret_type=%d", V0, V1, H0, H1, D0, D1, channels ? *channels : -1, ret_type).c_str(), __iim__current__function__); - - //throw IOException("in SimpleVolume::loadSubvolume_to_UINT8(...): disabled to remove dependence from openCV"); // Giulio_CV - - //checking for non implemented features - if( this->BYTESxCHAN > 2 ) { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"SimpleVolume::loadSubvolume_to_UINT8: invalid number of bytes per channel (%d)",this->BYTESxCHAN); - throw IOException(err_msg); - } - - if ( (ret_type == iim::DEF_IMG_DEPTH) && ((8 * this->BYTESxCHAN) != iim::DEF_IMG_DEPTH) ) { - // return type is 8 bits, but native depth is not 8 bits - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"SimpleVolume::loadSubvolume_to_UINT8: non supported return type (%d bits) - native type is %d bits",ret_type, 8*this->BYTESxCHAN); - throw IOException(err_msg); - } - - //initializations - V0 = (V0 == -1 ? 0 : V0); - V1 = (V1 == -1 ? DIM_V : V1); - H0 = (H0 == -1 ? 0 : H0); - H1 = (H1 == -1 ? DIM_H : H1); - D0 = (D0 == -1 ? 0 : D0); - D1 = (D1 == -1 ? DIM_D : D1); - - uint8 *subvol = 0; - - //allocation - sint64 sbv_height = V1 - V0; - sint64 sbv_width = H1 - H0; - sint64 sbv_depth = D1 - D0; - - //initializing the number of channels with an undefined value (it will be detected from the first slice read) - sint64 sbv_channels = -1; - sint64 sbv_bytes_chan = -1; - - //scanning of stacks matrix for data loading and storing into subvol - Rect_t subvol_area; - subvol_area.H0 = H0; - subvol_area.V0 = V0; - subvol_area.H1 = H1; - subvol_area.V1 = V1; - bool first_time = true; - - for(int row=0; rowIntersects(subvol_area); - if(intersect_area) // probably can be eliminated: intersect_area is always true - { - //LOCAL VARIABLES - char slice_fullpath[STATIC_STRINGS_SIZE]; - // Giulio_CV IplImage *slice; - - for(int k=0; kgetDIR_NAME(), - STACKS[row][col]->getFILENAMES()[D0+k]); - //loading image - - char *err_Tiff3Dfmt; - - unsigned int rows; - unsigned int cols; - unsigned int n_slices; - unsigned int channels; - int bytes_x_chan; - int swap; - void *dummy; - int dummy_len; - - if ( (err_Tiff3Dfmt = loadTiff3D2Metadata((char *)slice_fullpath,cols,rows,n_slices,channels,bytes_x_chan,swap,dummy,dummy_len)) != 0 ) { - throw iom::exception(iom::strprintf("unable to read tiff file (%s)",err_Tiff3Dfmt), __iom__current__function__); - } - closeTiff3DFile(dummy); - uint8 *slice = new uint8[rows * cols * channels * bytes_x_chan]; - if ( (err_Tiff3Dfmt = readTiff3DFile2Buffer((char *)slice_fullpath,slice,cols,rows,0,0)) != 0 ) { - throw iom::exception(iom::strprintf("unable to read tiff file (%s)",err_Tiff3Dfmt), __iom__current__function__); - } - - /* Giulio_CV - - slice = cvLoadImage(slice_fullpath, CV_LOAD_IMAGE_ANYDEPTH | CV_LOAD_IMAGE_ANYCOLOR); //without CV_LOAD_IMAGE_ANYDEPTH, image is converted to 8-bits if needed - // old version: slice_img_i = cvLoadImage(slice_fullpath, CV_LOAD_IMAGE_GRAYSCALE | CV_LOAD_IMAGE_ANYDEPTH); - if(!slice) - { - char msg[STATIC_STRINGS_SIZE]; - sprintf(msg,"in SimpleVolume::loadSubvolume_to_UINT: unable to open image \"%s\". Wrong path or format.\nSupported formats are BMP, DIB, JPEG, JPG, JPE, JP2, PNG, PBM, PGM, PPM, SR, RAS, TIFF, TIF", slice_fullpath); - throw IOException(msg); - } - - */ - - //if this is the first time a slice is loaded, detecting the number of channels and safely allocating memory for data - if(first_time) - { - first_time = false; - sbv_channels = channels; // Giulio_Cv slice->nChannels; - sbv_bytes_chan = bytes_x_chan; // Giulio_Cv slice->depth / 8; - if(sbv_channels != 1 && sbv_channels != 3) - throw IOException(std::string("Unsupported number of channels at \"").append(slice_fullpath).append("\". Only 1 and 3-channels images are supported").c_str()); - if(sbv_bytes_chan != this->BYTESxCHAN) - throw IOException(std::string("Wrong number of bits per channel\"").c_str()); - - try - { - subvol = new uint8[sbv_height * sbv_width * sbv_depth * sbv_channels * sbv_bytes_chan]; - } - catch(...){throw IOException("in SimpleVolume::loadSubvolume_to_UINT8: unable to allocate memory");} - } - //otherwise checking that all the other slices have the same bitdepth of the first one - else { - if (channels != sbv_channels || cols != sbv_width || rows != sbv_height) - throw IOException(std::string("Image depth mismatch at slice at \"").append(slice_fullpath).append("\": all slices must have the same bitdepth").c_str()); - if (bytes_x_chan != sbv_bytes_chan) - throw IOException(std::string("Image bytes per channel mismatch at slice at \"").append(slice_fullpath).append("\": all slices must have the same bitdepth").c_str()); - } - - //computing offsets - int slice_step = cols * bytes_x_chan * channels; // Giulio_CV slice->widthStep / sizeof(uint8); // widthStep takes already into account the number of bytes per channel - int ABS_V_offset = V0 - STACKS[row][col]->getABS_V(); - int ABS_H_offset = (H0 - STACKS[row][col]->getABS_H())*((int)sbv_channels); - - //different procedures for 1 and 3 channels images - int istart, iend, jstart, jend; - istart = intersect_area->V0-V0; - iend = intersect_area->V1-V0; - jstart = intersect_area->H0-H0; - jend = intersect_area->H1-H0; - if(sbv_channels == 1) - { - // about subvol index: actually there is always just one stack, - // hence all the subvolume has to be filled - // this is why for k=0 is k_offset=0 - sint64 k_offset = k*sbv_height*sbv_width*sbv_bytes_chan; - for(int i = istart; i < iend; i++) - { - uint8* slice_row = slice + (i+ABS_V_offset)*slice_step; - int c = 0; // controls the number of bytes to be copied - for(sint64 j = (jstart * sbv_bytes_chan); c <((jend-jstart) * sbv_bytes_chan); j++, c++) { - // all horizontal indices have to be multiplied by sbv_bytes_chan, including jstart - // the number of bytes to be copied is [(jend-jstart) * sbv_bytes_chan] - subvol[k_offset + i*sbv_width*sbv_bytes_chan + j] = slice_row[j+ABS_H_offset]; - } - } - } - else if(sbv_channels == 3) // channels in subvol are separated, where as in slice_row are arranged in triplets - { - // about subvol index: actually there is always just one stack, - // hence all the subvolume has to be filled - // this is why for k=0 offset1=0 - sint64 offset1 = k*sbv_height*sbv_width*sbv_bytes_chan; - sint64 offset2 = offset1 + sbv_height*sbv_width*sbv_bytes_chan*sbv_depth; - sint64 offset3 = offset2 + sbv_height*sbv_width*sbv_bytes_chan*sbv_depth; - for(int i = istart; i < iend; i++) - { - uint8* slice_row = slice + (i+ABS_V_offset)*slice_step; - int c = 0; // controls the number of bytes to be copied - for(sint64 j1 = (jstart * sbv_bytes_chan), j2 = (3 * jstart * sbv_bytes_chan); c <(jend-jstart); j1+=sbv_bytes_chan, j2+=3*sbv_bytes_chan, c++) - { - // all horizontal indices have to be multiplied by sbv_bytes_chan, including jstart - // the number of triplets to be copied is (jend-jstart) - for ( int b=0; b - - void init ( ) throw (iim::IOException); - - // iannello returns the number of channels of images composing the volume - void initChannels ( ) throw (iim::IOException); - - public: - - SimpleVolume(const char* _root_dir) throw (iim::IOException); - - SimpleVolume(void); - ~SimpleVolume(void); - - // returns a unique ID that identifies the volume format - std::string getPrintableFormat(){return iim::SIMPLE_FORMAT;} - - // added by Alessandro on 2014-02-18: additional info on the reference system (where available) - float getVXL_1() {return VXL_H;} - float getVXL_2() {return VXL_V;} - float getVXL_3() {return VXL_D;} - iim::axis getAXS_1() {return iim::horizontal;} - iim::axis getAXS_2() {return iim::vertical;} - iim::axis getAXS_3() {return iim::depth;} - - iim::real32 *loadSubvolume_to_real32(int V0=-1,int V1=-1, int H0=-1, int H1=-1, int D0=-1, int D1=-1) throw (iim::IOException); - - iim::uint8 *loadSubvolume_to_UINT8(int V0=-1,int V1=-1, int H0=-1, int H1=-1, int D0=-1, int D1=-1, - int *channels=0, int ret_type=iim::DEF_IMG_DEPTH) throw (iim::IOException); - - friend class iim::VirtualVolume; -}; - -# endif // _SIMPLE_VOLUME - diff --git a/v3d_main/terafly/src/core/imagemanager/SimpleVolumeRaw.cpp b/v3d_main/terafly/src/core/imagemanager/SimpleVolumeRaw.cpp deleted file mode 100644 index 678831cd70..0000000000 --- a/v3d_main/terafly/src/core/imagemanager/SimpleVolumeRaw.cpp +++ /dev/null @@ -1,414 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -* 2015-04-15 Alessandro. @ADDED definition for default constructor. -* 2014-11-22 Giulio. @CHANGED code using OpenCV has been commente. It can be found searching comments containing 'Giulio_CV' -*/ - -#include "SimpleVolumeRaw.h" -#include "StackRaw.h" -#include "RawFmtMngr.h" - -#ifdef _WIN32 -#include "dirent_win.h" -#else -#include -#endif -#include -// Giulio_CV #include -// Giulio_CV #include -// Giulio_CV #include - -using namespace std; -using namespace iim; - -// 2015-04-15. Alessandro. @ADDED definition for default constructor. -SimpleVolumeRaw::SimpleVolumeRaw(void) : VirtualVolume() -{ - /**/iim::debug(iim::LEV3, 0, __iim__current__function__); - - N_ROWS = N_COLS = 0; - STACKS = 0; -} - -SimpleVolumeRaw::SimpleVolumeRaw(const char* _root_dir) throw (IOException) -: VirtualVolume(_root_dir, 1.0f, 1.0f, 1.0f) -{ - /**/iim::debug(iim::LEV3, strprintf("_root_dir = \"%s\"", _root_dir).c_str(), __iim__current__function__); - - init(); - initChannels(); -} - - -SimpleVolumeRaw::~SimpleVolumeRaw(void) -{ - /**/iim::debug(iim::LEV3, 0, __iim__current__function__); - - // iannello if(root_dir) - // iannello delete[] root_dir; - - if(STACKS) - { - for(int row=0; row stacks_list; //each stack found in the hierarchy is pushed into this list - char stack_i_j_path[STATIC_STRINGS_SIZE]; - - //obtaining DIR pointer to root_dir (=NULL if directory doesn't exist) - if (!(cur_dir_lev1=opendir(root_dir))) - { - char msg[STATIC_STRINGS_SIZE]; - sprintf(msg,"in SimpleVolumeRaw::init(...): Unable to open directory \"%s\"", root_dir); - throw IOException(msg); - } - closedir(cur_dir_lev1); - - // Simple format has only one stack - N_ROWS = 1; - N_COLS = 1; - - //allocating the only stack - sprintf(stack_i_j_path,"%s",""); - StackRaw *new_stk = new StackRaw(this,i,j,stack_i_j_path); - stacks_list.push_back(new_stk); - - //converting stacks_list (STL list of StackRaw*) into STACKS (2-D array of StackRaw*) - STACKS = new StackRaw**[N_ROWS]; - for(int row=0; row < N_ROWS; row++) - STACKS[row] = new StackRaw*[N_COLS]; - for(list::iterator i = stacks_list.begin(); i != stacks_list.end(); i++) - STACKS[(*i)->getROW_INDEX()][(*i)->getCOL_INDEX()] = (*i); - - /******************** 3) COMPUTING VOLUME DIMENSIONS ******************** - *************************************************************************/ - for(int row=0; row < N_ROWS; row++) - for(int col=0; col < N_COLS; col++) - { - if(row==0) - DIM_H+=STACKS[row][col]->getWIDTH(); - if(col==0) - DIM_V+=STACKS[row][col]->getHEIGHT(); - DIM_D = STACKS[row][col]->getDEPTH() > DIM_D ? STACKS[row][col]->getDEPTH() : DIM_D; - } - - /**************** 4) COMPUTING STACKS ABSOLUTE POSITIONS **************** - *************************************************************************/ - for(int row=0; row < N_ROWS; row++) - for(int col=0; col < N_COLS; col++) - { - if(row) - STACKS[row][col]->setABS_V(STACKS[row-1][col]->getABS_V()+STACKS[row-1][col]->getHEIGHT()); - else - STACKS[row][col]->setABS_V(0); - - if(col) - STACKS[row][col]->setABS_H(STACKS[row][col-1]->getABS_H()+STACKS[row][col-1]->getWIDTH()); - else - STACKS[row][col]->setABS_H(0); - } -} - -void SimpleVolumeRaw::initChannels ( ) throw (IOException) -{ - /**/iim::debug(iim::LEV3, 0, __iim__current__function__); - - char slice_fullpath[STATIC_STRINGS_SIZE]; - - sprintf(slice_fullpath, "%s/%s/%s", root_dir, STACKS[0][0]->getDIR_NAME(), STACKS[0][0]->getFILENAMES()[0]); - - // get file attributes - char *err_rawfmt; - void *fhandle; - V3DLONG *sz = 0; - int datatype; - int b_swap; - int header_len; - - if ( (err_rawfmt = loadRaw2Metadata(slice_fullpath,sz,datatype,b_swap,fhandle,header_len)) != 0 ) { - if ( sz ) delete[] sz; - char msg[STATIC_STRINGS_SIZE]; - sprintf(msg,"in SimpleVolumeRaw::initChannels: unable to open image \"%s\". Wrong path or format (%s)", - slice_fullpath,err_rawfmt); - throw IOException(msg); - } - closeRawFile((FILE *)fhandle); - - DIM_C = (int)sz[3]; - BYTESxCHAN = datatype; - - n_active = DIM_C; - active = new uint32[n_active]; - for ( int c=0; cIntersects(subvol_area); - if(intersect_area) - { - STACKS[row][col]->loadStack(D0, D1-1); - - for(int k=0; kgetSTACKED_IMAGE()[D0+k]; - int step = slice->step/sizeof(float); - float *data = slice->data.fl; - int ABS_V_stk = STACKS[row][col]->getABS_V(); - int ABS_H_stk = STACKS[row][col]->getABS_H(); - - for(int i=intersect_area->V0-V0; iV1-V0; i++) - for(int j=intersect_area->H0-H0; jH1-H0; j++) - subvol[k*sbv_height*sbv_width + i*sbv_width + j] = (data+(i-ABS_V_stk+V0)*step)[j-ABS_H_stk+H0]; - } - - // allocated space has to always released - STACKS[row][col]->releaseStack(); - } - } - - */ - - return subvol; -} - - -uint8 *SimpleVolumeRaw::loadSubvolume_to_UINT8(int V0,int V1, int H0, int H1, int D0, int D1, int *channels, int ret_type) throw (IOException) -{ - /**/iim::debug(iim::LEV3, strprintf("V0=%d, V1=%d, H0=%d, H1=%d, D0=%d, D1=%d, *channels=%d, ret_type=%d", V0, V1, H0, H1, D0, D1, channels ? *channels : -1, ret_type).c_str(), __iim__current__function__); - - //checking for non implemented features - if( this->BYTESxCHAN > 2 ) { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"SimpleVolumeRaw::loadSubvolume_to_UINT8: invalid number of bytes per channel (%d)",this->BYTESxCHAN); - throw IOException(err_msg); - } - - if ( (ret_type == iim::DEF_IMG_DEPTH) && ((8 * this->BYTESxCHAN) != iim::DEF_IMG_DEPTH) ) { - // return type is 8 bits, but native depth is not 8 bits - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"SimpleVolumeRaw::loadSubvolume_to_UINT8: non supported return type (%d bits) - native type is %d bits",ret_type, 8*this->BYTESxCHAN); - throw IOException(err_msg); - } - - //initializations - V0 = (V0 == -1 ? 0 : V0); - V1 = (V1 == -1 ? DIM_V : V1); - H0 = (H0 == -1 ? 0 : H0); - H1 = (H1 == -1 ? DIM_H : H1); - D0 = (D0 == -1 ? 0 : D0); - D1 = (D1 == -1 ? DIM_D : D1); - - uint8 *subvol = 0; - - //allocation - sint64 sbv_height = V1 - V0; - sint64 sbv_width = H1 - H0; - sint64 sbv_depth = D1 - D0; - - //initializing the number of channels with an undefined value (it will be detected from the first slice read) - sint64 sbv_channels = -1; - - //scanning of stacks matrix for data loading and storing into subvol - Rect_t subvol_area; - subvol_area.H0 = H0; - subvol_area.V0 = V0; - subvol_area.H1 = H1; - subvol_area.V1 = V1; - bool first_time = true; - - for(int row=0; rowIntersects(subvol_area); - if(intersect_area) - { - //LOCAL VARIABLES - char slice_fullpath[STATIC_STRINGS_SIZE]; - //IplImage *slice; - unsigned char *slice = 0; - - for(int k=0; kgetDIR_NAME(), - STACKS[row][col]->getFILENAMES()[D0+k]); - - //loading image - char *err_rawfmt; - V3DLONG *sz = 0; - int datatype; - - if ( (err_rawfmt = loadRaw2WholeStack(slice_fullpath,slice,sz,datatype)) != 0 ) { - if ( sz ) delete[] sz; - char msg[STATIC_STRINGS_SIZE]; - sprintf(msg,"in SimpleVolumeRaw::loadSubvolume_to_UINT8: unable to open image \"%s\". Wrong path or format (%s)", - slice_fullpath,err_rawfmt); - throw IOException(msg); - } - - //slice = cvLoadImage(slice_fullpath, CV_LOAD_IMAGE_ANYCOLOR); //without CV_LOAD_IMAGE_ANYDEPTH, image is converted to 8-bits if needed - // old version: slice_img_i = cvLoadImage(slice_fullpath, CV_LOAD_IMAGE_GRAYSCALE | CV_LOAD_IMAGE_ANYDEPTH); - - if(sz[2] != 1) - { - if ( sz ) delete[] sz; - char msg[STATIC_STRINGS_SIZE]; - sprintf(msg,"in SimpleVolumeRaw::loadSubvolume_to_UINT8: raw image contains more than one slice (%s)", - slice_fullpath); - throw IOException(msg); - } - - if(!slice) - { - if ( sz ) delete[] sz; - char msg[STATIC_STRINGS_SIZE]; - sprintf(msg,"in SimpleVolumeRaw::loadSubvolume_to_UINT8: unable to read image \"%s\". Wrong path or format", - slice_fullpath); - throw IOException(msg); - } - - //if this is the first time a slice is loaded, detecting the number of channels and safely allocating memory for data - if(first_time) - { - first_time = false; - sbv_channels = sz[3]; - //if(sbv_channels != 1 && sbv_channels != 3) - // throw iim::IOException(std::string("Unsupported number of channels at \"").append(slice_fullpath).append("\". Only 1 and 3-channels images are supported").c_str()); - - try - { - subvol = new uint8[sbv_height * sbv_width * sbv_depth * sbv_channels * datatype]; - } - catch(...){ - if ( sz ) delete[] sz; - throw IOException("in SimpleVolumeRaw::loadSubvolume_to_UINT8: unable to allocate memory"); - } - } - //otherwise checking that all the other slices have the same bitdepth of the first one - else if(sz[3] != sbv_channels) { - if ( sz ) delete[] sz; - throw IOException(std::string("Image depth mismatch at slice at \"").append(slice_fullpath).append("\": all slices must have the same bitdepth").c_str()); - } - - //computing offsets - int slice_step = (int)sz[0] * datatype; // WARNING, not sure: to be checked - int ABS_V_offset = V0 - STACKS[row][col]->getABS_V(); - int ABS_H_offset = (H0 - STACKS[row][col]->getABS_H())*((int)sbv_channels); - - int istart, iend, jstart, jend; - istart = intersect_area->V0-V0; - iend = intersect_area->V1-V0; - jstart = intersect_area->H0-H0; - jend = intersect_area->H1-H0; - for ( int c=0; c - - void init ( ) throw (iim::IOException); - - // iannello returns the number of channels of images composing the volume - void initChannels ( ) throw (iim::IOException); - - public: - - SimpleVolumeRaw(const char* _root_dir) throw (iim::IOException); - SimpleVolumeRaw(void); - ~SimpleVolumeRaw(void); - - // returns a unique ID that identifies the volume format - std::string getPrintableFormat(){return iim::SIMPLE_RAW_FORMAT;} - - // added by Alessandro on 2014-02-18: additional info on the reference system (where available) - float getVXL_1() {return VXL_H;} - float getVXL_2() {return VXL_V;} - float getVXL_3() {return VXL_D;} - iim::axis getAXS_1() {return iim::horizontal;} - iim::axis getAXS_2() {return iim::vertical;} - iim::axis getAXS_3() {return iim::depth;} - - iim::real32 *loadSubvolume_to_real32(int V0=-1,int V1=-1, int H0=-1, int H1=-1, int D0=-1, int D1=-1) throw (iim::IOException); - - iim::uint8 *loadSubvolume_to_UINT8(int V0=-1,int V1=-1, int H0=-1, int H1=-1, int D0=-1, int D1=-1, - int *channels=0, int ret_type=iim::DEF_IMG_DEPTH) throw (iim::IOException); - - friend class iim::VirtualVolume; -}; - -# endif // _SIMPLE_VOLUME - diff --git a/v3d_main/terafly/src/core/imagemanager/Stack.cpp b/v3d_main/terafly/src/core/imagemanager/Stack.cpp deleted file mode 100644 index c15750d1aa..0000000000 --- a/v3d_main/terafly/src/core/imagemanager/Stack.cpp +++ /dev/null @@ -1,447 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -* 2015-04-14 Alessandro. @FIXED folder image scan: Only .tif/.TIF/.tiff/.TIFF files have to be included in the image list. -* 2014-11-22 Giulio. @CHANGED code using OpenCV has been commente. It can be found searching comments containing 'Giulio_CV' -*/ - -#include "Stack.h" -#include "VirtualVolume.h" -// Giulio_CV #include -// Giulio_CV #include -#ifdef _WIN32 -#include "dirent_win.h" -#else -#include -#endif -#include -#include - -#include "IOPluginAPI.h" // 2014-11-26. Giulio. - - -// 140427_IANNELLO -#ifdef min -#undef min -#endif - -#ifdef max -#undef max -#endif - -// Giulio_CV #include - -//2014-11-27 Giulio. @ADDED MIN, MAX macros -#ifndef MIN -#define MIN(a,b) ((a)<(b) ? (a) : (b)) -#endif -#ifndef MAX -#define MAX(a,b) ((a)>(b) ? (a) : (b)) -#endif - -using namespace std; -using namespace iim; - -Stack::Stack(VirtualVolume* _CONTAINER, int _ROW_INDEX, int _COL_INDEX, char* _DIR_NAME) throw (IOException) -{ - /**/iim::debug(iim::LEV3, strprintf("_ROW_INDEX=%d, _COL_INDEX=%d, _DIR_NAME=%s", _ROW_INDEX, _COL_INDEX, _DIR_NAME).c_str(), __iim__current__function__); - - // throw IOException("in Stack::Stack(...): disabled to remove dependence from openCV"); // Giulio_CV - - this->CONTAINER = _CONTAINER; - - this->DIR_NAME = new char[strlen(_DIR_NAME)+1]; - strcpy(this->DIR_NAME, _DIR_NAME); - - this->ROW_INDEX = _ROW_INDEX; - this->COL_INDEX = _COL_INDEX; - - STACKED_IMAGE = 0; - FILENAMES = 0; - HEIGHT = WIDTH = DEPTH = 0; - ABS_V = ABS_H = 0; - - init(); -} - -Stack::Stack(VirtualVolume* _CONTAINER, int _ROW_INDEX, int _COL_INDEX, FILE* bin_file) throw (IOException) -{ - /**/iim::debug(iim::LEV3, strprintf("_ROW_INDEX=%d, _COL_INDEX=%d", _ROW_INDEX, _COL_INDEX).c_str(), __iim__current__function__); - - // throw IOException("in Stack::Stack(...): disabled to remove dependence from openCV"); // Giulio_CV - - CONTAINER = _CONTAINER; - ROW_INDEX = _ROW_INDEX; - COL_INDEX = _COL_INDEX; - - DIR_NAME = 0; - STACKED_IMAGE = 0; - FILENAMES = 0; - HEIGHT = WIDTH = DEPTH = 0; - ABS_V = ABS_H = 0; - - unBinarizeFrom(bin_file); - - //initializing STACKED_IMAGE array - this->STACKED_IMAGE = new uint8 *[DEPTH]; // Giulio_CV new CvMat*[DEPTH]; - for(uint32 z=0; zSTACKED_IMAGE[z] = 0; -} - -Stack::~Stack(void) -{ - /**/iim::debug(iim::LEV3, strprintf("_ROW_INDEX=%d, _COL_INDEX=%d", ROW_INDEX, COL_INDEX).c_str(), __iim__current__function__); - - for(uint32 z=0; z entries_lev3; - list::iterator entry_k; - string entry; - - //building filenames_list - char abs_path[STATIC_STRINGS_SIZE]; - sprintf(abs_path,"%s/%s", CONTAINER->getROOT_DIR(), DIR_NAME); - cur_dir_lev3 = opendir(abs_path); - if (!cur_dir_lev3) - { - char errMsg[STATIC_STRINGS_SIZE]; - sprintf(errMsg, "in Stack::init(): can't open directory \"%s\"", abs_path); - throw IOException(errMsg); - } - - //scanning third level of hierarchy which entries need to be ordered alphabetically. This is done using STL. - // 2015-04-14 Alessandro. @FIXED folder image scan: Only .tif/.TIF/.tiff/.TIFF files have to be included in the image list. - while ((entry_lev3=readdir(cur_dir_lev3))) - { - tmp = entry_lev3->d_name; - if(tmp.compare(".") != 0 && tmp.compare("..") != 0 && - (tmp.find(".tif") != string::npos || tmp.find(".TIF") != string::npos) ) - entries_lev3.push_back(tmp); - } - entries_lev3.sort(); - DEPTH = (int)entries_lev3.size(); - - //----- Alessandro added on August 12, 2013 - //----- Bug fixed: exceeding the maximum number of directories opened at the same time - closedir(cur_dir_lev3); - - for(entry_k = entries_lev3.begin(); entry_k != entries_lev3.end(); entry_k++) - /**/iim::debug(iim::LEV3, strprintf("ROW_INDEX=%d, COL_INDEX=%d, found \"%s\"", ROW_INDEX, COL_INDEX, entry_k->c_str()).c_str(), __iim__current__function__); - - //checking if current stack is not empty - if(DEPTH == 0) - throw IOException(iim::strprintf("in Stack::init(): cannot find .tif/.TIF/.tiff/.TIFF files within folder \"%s\"", abs_path)); - - //converting filenames_list (STL list of C-strings) into FILENAMES (1-D array of C-strings) - FILENAMES = new char*[DEPTH]; - for(uint32 z=0; zSTACKED_IMAGE = new uint8 *[DEPTH]; // Giulio_CV new CvMat*[DEPTH]; - for(uint32 z=0; zSTACKED_IMAGE[z] = NULL; - - //extracting HEIGHT and WIDTH attributes from first slice - char slice_fullpath[STATIC_STRINGS_SIZE]; - sprintf(slice_fullpath, "%s/%s/%s", CONTAINER->getROOT_DIR(), DIR_NAME, FILENAMES[0]); - /**/iim::debug(iim::LEV3, strprintf("ROW_INDEX=%d, COL_INDEX=%d: trying to load image at \"%s\"", ROW_INDEX, COL_INDEX, slice_fullpath).c_str(), __iim__current__function__); - - int img_width; - int img_height; - int img_depth; - int img_chans; - std::string params; - - try - { - iomanager::IOPluginFactory::getPlugin2D("tiff2D")->readMetadata(slice_fullpath, img_width, img_height, img_depth, img_chans, params); - } - catch (iom::exception & ex) - { - throw iim::IOException(ex.what()); - } - - /* Giulio_CV - - IplImage *img_tmp = cvLoadImage(slice_fullpath, CV_LOAD_IMAGE_GRAYSCALE); - if(!img_tmp) - { - char msg[STATIC_STRINGS_SIZE]; - sprintf(msg,"in Stack[%d,%d]::init(): unable to open image \"%s\". Wrong path or format.\nSupported formats are BMP, DIB, JPEG, JPG, JPE, JP2, PNG, PBM, PGM, PPM, SR, RAS, TIFF, TIF", - ROW_INDEX, COL_INDEX, slice_fullpath); - throw IOException(msg); - } - - */ - - /**/iim::debug(iim::LEV3, strprintf("ROW_INDEX=%d, COL_INDEX=%d: successfully loaded image at \"%s\"", ROW_INDEX, COL_INDEX, slice_fullpath).c_str(), __iim__current__function__); - - HEIGHT = img_height; - WIDTH = img_width; - - // Giuilo_CV cvReleaseImage(&img_tmp); -} - -//PRINT method -void Stack::print() -{ - printf("\t |\t[%d,%d]\n", ROW_INDEX, COL_INDEX); - printf("\t |\tDirectory:\t\t%s\n", DIR_NAME); - printf("\t |\tDimensions:\t\t%d(V) x %d(H) x %d(D)\n", HEIGHT, WIDTH, DEPTH); - printf("\t |\tAbsolute position:\t%d(V) x %d(H) x %d(D)\n", ABS_V, ABS_H, 0); - /*printf("\t |\tFilenames:\t\n"); - for(int z=0; zgetROOT_DIR(), DIR_NAME, FILENAMES[file_i]); - - //loading image - slice_img_i = cvLoadImage(slice_fullpath, CV_LOAD_IMAGE_GRAYSCALE | CV_LOAD_IMAGE_ANYDEPTH); - if(!slice_img_i) - { - char msg[1000]; - sprintf(msg,"in Stack[%d,%d]::loadStack(%d,%d): unable to open image \"%s\". Wrong path or format.\nSupported formats are BMP, DIB, JPEG, JPG, JPE, PNG, PBM, PGM, PPM, SR, RAS, TIFF, TIF", - ROW_INDEX, COL_INDEX, first_file, last_file, slice_fullpath); - throw IOException(msg); - } - - //allocating CvMat - STACKED_IMAGE[file_i] = cvCreateMat(HEIGHT, WIDTH, CV_32FC1); - - //rescaling into 'data[sample_i]', i.e. after rescaling values are between 0.0 and 1.0 - cvConvertScale(cvGetMat(slice_img_i,mat_buffer),STACKED_IMAGE[file_i],slice_img_i->depth == IPL_DEPTH_16U ? scale_factor_16b : scale_factor_8b); - - //releasing image - cvReleaseImage(&slice_img_i); - } - } - cvReleaseMat(&mat_buffer); - - */ -} - -//releases images of current stack (from 'first_file' to 'last_file' extremes included, if not specified loads entire stack) -void Stack::releaseStack(int first_file, int last_file) -{ - /**/iim::debug(iim::LEV3, strprintf("_ROW_INDEX=%d, _COL_INDEX=%d, first_file=%d, last_file=%d", ROW_INDEX, COL_INDEX, first_file, last_file).c_str(), __iim__current__function__); - - //initializations - first_file = (first_file == -1 ? 0 : first_file); - last_file = (last_file == -1 ? DEPTH-1 : last_file); - - //memory deallocation - for(int file_i = first_file; file_i <= last_file; file_i++) - { - if(STACKED_IMAGE[file_i]) - { - delete []STACKED_IMAGE[file_i]; // Giulio_CV cvReleaseMat(&(STACKED_IMAGE[file_i])); - STACKED_IMAGE[file_i] = 0; - } - } -} - -//returns a pointer to the intersection rectangle if the given area intersects current stack, otherwise returns NULL -Rect_t* Stack::Intersects(const Rect_t& area) -{ - //first determining if intersection occurs - bool intersects = ( area.H0 < (int)(ABS_H + WIDTH) && - area.H1 > ABS_H && - area.V0 < (int)(ABS_V + HEIGHT) && - area.V1 > ABS_V ); - //if intersection occurs, computing intersection area, otherwise returning NULL - if(intersects) - { - Rect_t *intersect_rect = new Rect_t; - intersect_rect->H0 = MAX(ABS_H, area.H0); - intersect_rect->V0 = MAX(ABS_V, area.V0); - intersect_rect->H1 = MIN((int)(ABS_H + WIDTH), area.H1); - intersect_rect->V1 = MIN((int)(ABS_V + HEIGHT), area.V1); - - return intersect_rect; - } - else - return 0; -} diff --git a/v3d_main/terafly/src/core/imagemanager/Stack.h b/v3d_main/terafly/src/core/imagemanager/Stack.h deleted file mode 100644 index bd7237c6a5..0000000000 --- a/v3d_main/terafly/src/core/imagemanager/Stack.h +++ /dev/null @@ -1,109 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -* 2014-11-22 Giulio. @CHANGED code using OpenCV has been commente. It can be found searching comments containing 'Giulio_CV' -*/ - -#ifndef _IIM_STACK_H -#define _IIM_STACK_H - -#include -#include "IM_config.h" -#include "VirtualVolume.h" - -//FORWARD-DECLARATIONS -//struct CvMat; // Giulio_CV - -//class iim::VirtualVolume; -/* modified (iannello) - * abstract class VirtualVolume has been substituted to derived class StackedVolume - * since class Stack can be used to manage also volumes stored simply as a sequence of images - * in one directory - */ - -//TYPE DEFINITIONS -//typedef struct {int V0, V1, H0, H1;} Rect_t; - -class iim::Stack -{ - private: - - //*********** OBJECT ATTRIBUTES *********** - iim::VirtualVolume* CONTAINER; //pointer to object that contains the current object - iim::uint8** STACKED_IMAGE; //1-D dinamic array of pointers. Every stores a single 2-D image - char** FILENAMES; //1-D dinamic array of pointers to images filanames - iim::uint32 HEIGHT, WIDTH, DEPTH; //VHD (Vertical, Horizontal, Depth) dimensions of current stack - int ROW_INDEX, COL_INDEX; //row and col index relative to stack matrix - int ABS_V, ABS_H; //absolute VH voxel coordinates of current stack - char* DIR_NAME; //string containing current stack directory - - //******** OBJECT PRIVATE METHODS ********* - Stack(void); - - //Initializes all object's members given DIR_NAME - void init() throw (iim::IOException); - - public: - - Stack(iim::VirtualVolume* _CONTAINER, int _ROW_INDEX, int _COL_INDEX, FILE* bin_file) throw (iim::IOException); - Stack(iim::VirtualVolume* _CONTAINER, int _ROW_INDEX, int _COL_INDEX, char* _DIR_NAME) throw (iim::IOException); - ~Stack(void); - - //GET methods - char* getDIR_NAME() {return DIR_NAME;} - int getROW_INDEX() {return ROW_INDEX;} - int getCOL_INDEX() {return COL_INDEX;} - iim::uint32 getHEIGHT() {return HEIGHT;} - iim::uint32 getWIDTH() {return WIDTH;} - iim::uint32 getDEPTH() {return DEPTH;} - int getABS_V() {return ABS_V;} - int getABS_H() {return ABS_H;} - char** getFILENAMES() {return FILENAMES;} - /* Giulio_CV CvMat */ iim::uint8** getSTACKED_IMAGE() {return STACKED_IMAGE;} - - //SET methods - void setROW_INDEX(int _ROW_INDEX){ROW_INDEX = _ROW_INDEX;} - void setCOL_INDEX(int _COL_INDEX){COL_INDEX = _COL_INDEX;} - void setABS_V (int _ABS_V) {ABS_V = _ABS_V; } - void setABS_H (int _ABS_H) {ABS_H = _ABS_H; } - - //PRINT method - void print(); - - //binarizing-unbinarizing methods - void binarizeInto(FILE* file); - void unBinarizeFrom(FILE* file) throw (iim::IOException); - - //loads/releases images of current stack (from 'first_file' to 'last_file' extremes included, if not specified loads entire stack) - void loadStack (int first_file=-1, int last_file=-1); - void releaseStack(int first_file=-1, int last_file=-1); - - //returns a pointer to the intersection rectangle if the given area intersects current stack, otherwise returns NULL - Rect_t* Intersects(const Rect_t& area); -}; - -#endif //_STACK_H diff --git a/v3d_main/terafly/src/core/imagemanager/StackRaw.cpp b/v3d_main/terafly/src/core/imagemanager/StackRaw.cpp deleted file mode 100644 index fd7486bb92..0000000000 --- a/v3d_main/terafly/src/core/imagemanager/StackRaw.cpp +++ /dev/null @@ -1,431 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -* 2015-04-14 Alessandro. @FIXED folder image scan: Only .raw/.RAW/.v3draw/.V3DRAW files have to be included in the image list. -* 2014-11-22 Giulio. @CHANGED code using OpenCV has been commente. It can be found searching comments containing 'Giulio_CV' -*/ - -#include "StackRaw.h" -#include "VirtualVolume.h" -#include "RawFmtMngr.h" -// Giulio_CV #include -// Giulio_CV #include -#ifdef _WIN32 -#include "dirent_win.h" -#else -#include -#endif -#include -#include - -// 140427_IANNELLO -#ifdef min -#undef min -#endif - -#ifdef max -#undef max -#endif - -// Giulio_CV #include - -//2014-11-21 Giulio. @ADDED MIN, MAX macros -#ifndef MIN -#define MIN(a,b) ((ab) ? (a) : (b)) -#endif - -using namespace std; -using namespace iim; - -StackRaw::StackRaw(VirtualVolume* _CONTAINER, int _ROW_INDEX, int _COL_INDEX, char* _DIR_NAME) throw (IOException) -{ - /**/iim::debug(iim::LEV3, strprintf("_ROW_INDEX=%d, _COL_INDEX=%d, _DIR_NAME=%s", _ROW_INDEX, _COL_INDEX, _DIR_NAME).c_str(), __iim__current__function__); - - this->CONTAINER = _CONTAINER; - - this->DIR_NAME = new char[strlen(_DIR_NAME)+1]; - strcpy(this->DIR_NAME, _DIR_NAME); - - this->ROW_INDEX = _ROW_INDEX; - this->COL_INDEX = _COL_INDEX; - - STACKED_IMAGE = NULL; - FILENAMES = NULL; - HEIGHT = WIDTH = DEPTH = 0; - ABS_V = ABS_H = 0; - - init(); -} - -StackRaw::StackRaw(VirtualVolume* _CONTAINER, int _ROW_INDEX, int _COL_INDEX, FILE* bin_file) throw (IOException) -{ - /**/iim::debug(iim::LEV3, strprintf("_ROW_INDEX=%d, _COL_INDEX=%d", _ROW_INDEX, _COL_INDEX).c_str(), __iim__current__function__); - - CONTAINER = _CONTAINER; - ROW_INDEX = _ROW_INDEX; - COL_INDEX = _COL_INDEX; - - DIR_NAME = 0; - STACKED_IMAGE = 0; - FILENAMES = 0; - HEIGHT = WIDTH = DEPTH = 0; - ABS_V = ABS_H = 0; - - unBinarizeFrom(bin_file); - - //initializing STACKED_IMAGE array - this->STACKED_IMAGE = new uint8 *[DEPTH]; // Giulio_CV new CvMat*[DEPTH]; - for(uint32 z=0; zSTACKED_IMAGE[z] = 0; -} - -StackRaw::~StackRaw(void) -{ - /**/iim::debug(iim::LEV3, strprintf("ROW_INDEX=%d, COL_INDEX=%d", ROW_INDEX, COL_INDEX).c_str(), __iim__current__function__); - - for(uint32 z=0; z entries_lev3; - list::iterator entry_k; - string entry; - - //building filenames_list - char abs_path[STATIC_STRINGS_SIZE]; - sprintf(abs_path,"%s/%s", CONTAINER->getROOT_DIR(), DIR_NAME); - cur_dir_lev3 = opendir(abs_path); - if (!cur_dir_lev3) - { - char errMsg[STATIC_STRINGS_SIZE]; - sprintf(errMsg, "in StackRaw::init(): can't open directory \"%s\"", abs_path); - throw IOException(errMsg); - } - // 2015-04-14 Alessandro. @FIXED folder image scan: Only .raw/.RAW/.v3draw/.V3DRAW files have to be included in the image list. - //scanning third level of hierarchy which entries need to be ordered alphabetically. This is done using STL. - while ((entry_lev3=readdir(cur_dir_lev3))) - { - tmp = entry_lev3->d_name; - if(tmp.compare(".") != 0 && tmp.compare("..") != 0 && - (tmp.find(".raw") != string::npos || tmp.find(".RAW") != string::npos || tmp.find(".v3draw") != string::npos || tmp.find(".V3DRAW") != string::npos)) // 2015-06-12 Giulio. f@FIXED bad parenthesis position - entries_lev3.push_back(tmp); - } - entries_lev3.sort(); - DEPTH = (int)entries_lev3.size(); - - //----- Alessandro added on August 12, 2013 - //----- Bug fixed: exceeding the maximum number of directories opened at the same time - closedir(cur_dir_lev3); - - //checking if current stack is not empty - if(DEPTH == 0) - throw IOException(iim::strprintf("in StackRaw::init(): cannot find .raw/.RAW/.v3draw/.V3DRAW files within folder \"%s\"", abs_path)); - - //converting filenames_list (STL list of C-strings) into FILENAMES (1-D array of C-strings) - FILENAMES = new char*[DEPTH]; - for(uint32 z=0; zSTACKED_IMAGE = new uint8 *[DEPTH]; // Giulio_CV new CvMat*[DEPTH]; - for(uint32 z=0; zSTACKED_IMAGE[z] = NULL; - - //extracting HEIGHT and WIDTH attributes from first slice - char slice_fullpath[STATIC_STRINGS_SIZE]; - sprintf(slice_fullpath, "%s/%s/%s", CONTAINER->getROOT_DIR(), DIR_NAME, FILENAMES[0]); - - //IplImage *img_tmp = cvLoadImage(slice_fullpath, CV_LOAD_IMAGE_GRAYSCALE); - - // get file attributes - char *err_rawfmt; - void *fhandle; - V3DLONG *sz = 0; - int datatype; - int b_swap; - int header_len; - - if ( (err_rawfmt = loadRaw2Metadata(slice_fullpath,sz,datatype,b_swap,fhandle,header_len)) != 0 ) { - if ( sz ) delete[] sz; - char msg[STATIC_STRINGS_SIZE]; - sprintf(msg,"in StackRaw[%d,%d]::init(): unable to open image \"%s\". Wrong path or format (%s)", - ROW_INDEX, COL_INDEX, slice_fullpath,err_rawfmt); - throw IOException(msg); - } - closeRawFile((FILE *)fhandle); - - // I should check that sz[2] is 1 - - HEIGHT = (int)sz[1]; - WIDTH = (int)sz[0]; - //cvReleaseImage(&img_tmp); - - delete[] sz; -} - -//PRINT method -void StackRaw::print() -{ - printf("\t |\t[%d,%d]\n", ROW_INDEX, COL_INDEX); - printf("\t |\tDirectory:\t\t%s\n", DIR_NAME); - printf("\t |\tDimensions:\t\t%d(V) x %d(H) x %d(D)\n", HEIGHT, WIDTH, DEPTH); - printf("\t |\tAbsolute position:\t%d(V) x %d(H) x %d(D)\n", ABS_V, ABS_H, 0); - /*printf("\t |\tFilenames:\t\n"); - for(int z=0; zgetROOT_DIR(), DIR_NAME, FILENAMES[file_i]); - - //loading image - temp slice_img_i = cvLoadImage(slice_fullpath, CV_LOAD_IMAGE_GRAYSCALE | CV_LOAD_IMAGE_ANYDEPTH); - if(!slice_img_i) - { - char msg[1000]; - sprintf(msg,"in StackRaw[%d,%d]::loadStack(%d,%d): unable to open image \"%s\". Wrong path or format.\nSupported formats are BMP, DIB, JPEG, JPG, JPE, PNG, PBM, PGM, PPM, SR, RAS, TIFF, TIF", - ROW_INDEX, COL_INDEX, first_file, last_file, slice_fullpath); - throw IOException(msg); - } - - //allocating CvMat - STACKED_IMAGE[file_i] = cvCreateMat(HEIGHT, WIDTH, CV_32FC1); - - //rescaling into 'data[sample_i]', i.e. after rescaling values are between 0.0 and 1.0 - cvConvertScale(cvGetMat(slice_img_i,mat_buffer),STACKED_IMAGE[file_i],slice_img_i->depth == IPL_DEPTH_16U ? scale_factor_16b : scale_factor_8b); - - //releasing image - cvReleaseImage(&slice_img_i); - } - } - cvReleaseMat(&mat_buffer); - - */ -} - -//releases images of current stack (from 'first_file' to 'last_file' extremes included, if not specified loads entire stack) -void StackRaw::releaseStack(int first_file, int last_file) -{ - /**/iim::debug(iim::LEV3, strprintf("ROW_INDEX=%d, COL_INDEX=%d, first_file=%d, last_file=%d", ROW_INDEX, COL_INDEX, first_file, last_file).c_str(), __iim__current__function__); - - //initializations - first_file = (first_file == -1 ? 0 : first_file); - last_file = (last_file == -1 ? DEPTH-1 : last_file); - - //memory deallocation - for(int file_i = first_file; file_i <= last_file; file_i++) - { - if(STACKED_IMAGE[file_i]) - { - delete []STACKED_IMAGE[file_i]; // Giulio_CV cvReleaseMat(&(STACKED_IMAGE[file_i])); - STACKED_IMAGE[file_i] = NULL; - } - } -} - - -//returns a pointer to the intersection rectangle if the given area intersects current stack, otherwise returns NULL -Rect_t* StackRaw::Intersects(const Rect_t& area) -{ - //first determining if intersection occurs - bool intersects = ( area.H0 < (int)(ABS_H + WIDTH) && - area.H1 > ABS_H && - area.V0 < (int)(ABS_V + HEIGHT) && - area.V1 > ABS_V ); - - //if intersection occurs, computing intersection area, otherwise returning NULL - if(intersects) - { - Rect_t *intersect_rect = new Rect_t; - intersect_rect->H0 = MAX(ABS_H, area.H0); - intersect_rect->V0 = MAX(ABS_V, area.V0); - intersect_rect->H1 = MIN((int)(ABS_H + WIDTH), area.H1); - intersect_rect->V1 = MIN((int)(ABS_V + HEIGHT), area.V1); - - return intersect_rect; - } - else - return 0; -} diff --git a/v3d_main/terafly/src/core/imagemanager/StackRaw.h b/v3d_main/terafly/src/core/imagemanager/StackRaw.h deleted file mode 100644 index c4342064b0..0000000000 --- a/v3d_main/terafly/src/core/imagemanager/StackRaw.h +++ /dev/null @@ -1,103 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -#ifndef _STACK_RAW_H -#define _STACK_RAW_H - -#include -#include "IM_config.h" -#include "VirtualVolume.h" - -//FORWARD-DECLARATIONS -// Giulio_CV struct CvMat; - -//class iim::VirtualVolume; -/* modified (iannello) - * abstract class VirtualVolume has been substituted to derived class StackedVolume - * since class Stack can be used to manage also volumes stored simply as a sequence of images - * in one directory - */ - -//TYPE DEFINITIONS -//typedef struct {int V0, V1, H0, H1;} Rect_t; - -class StackRaw -{ - private: - - //*********** OBJECT ATTRIBUTES *********** - iim::VirtualVolume* CONTAINER; //pointer to object that contains the current object - /* Giulio_CV CvMat** */ iim::uint8 **STACKED_IMAGE; //1-D dinamic array of pointers. Every stores a single 2-D image - char** FILENAMES; //1-D dinamic array of pointers to images filanames - iim::uint32 HEIGHT, WIDTH, DEPTH; //VHD (Vertical, Horizontal, Depth) dimensions of current stack - int ROW_INDEX, COL_INDEX; //row and col index relative to stack matrix - int ABS_V, ABS_H; //absolute VH voxel coordinates of current stack - char* DIR_NAME; //string containing current stack directory - - //******** OBJECT PRIVATE METHODS ********* - StackRaw(void); - - //Initializes all object's members given DIR_NAME - void init(); - - public: - - StackRaw(iim::VirtualVolume* _CONTAINER, int _ROW_INDEX, int _COL_INDEX, FILE* bin_file) throw (iim::IOException); - StackRaw(iim::VirtualVolume* _CONTAINER, int _ROW_INDEX, int _COL_INDEX, char* _DIR_NAME) throw (iim::IOException); - ~StackRaw(void); - - //GET methods - char* getDIR_NAME() {return DIR_NAME;} - int getROW_INDEX() {return ROW_INDEX;} - int getCOL_INDEX() {return COL_INDEX;} - iim::uint32 getHEIGHT() {return HEIGHT;} - iim::uint32 getWIDTH() {return WIDTH;} - iim::uint32 getDEPTH() {return DEPTH;} - int getABS_V() {return ABS_V;} - int getABS_H() {return ABS_H;} - char** getFILENAMES() {return FILENAMES;} - /* Giulio_CV CvMat** */ iim::uint8 **getSTACKED_IMAGE() {return STACKED_IMAGE;} - - //SET methods - void setROW_INDEX(int _ROW_INDEX){ROW_INDEX = _ROW_INDEX;} - void setCOL_INDEX(int _COL_INDEX){COL_INDEX = _COL_INDEX;} - void setABS_V (int _ABS_V) {ABS_V = _ABS_V; } - void setABS_H (int _ABS_H) {ABS_H = _ABS_H; } - - //PRINT method - void print(); - - //binarizing-unbinarizing methods - void binarizeInto(FILE* file); - void unBinarizeFrom(FILE* file) throw (iim::IOException); - - //loads/releases images of current stack (from 'first_file' to 'last_file' extremes included, if not specified loads entire stack) - void loadStack (int first_file=-1, int last_file=-1); - void releaseStack(int first_file=-1, int last_file=-1); - - //returns a pointer to the intersection rectangle if the given area intersects current stack, otherwise returns NULL - Rect_t* Intersects(const Rect_t& area); -}; - -#endif //_STACK_H diff --git a/v3d_main/terafly/src/core/imagemanager/StackedVolume.cpp b/v3d_main/terafly/src/core/imagemanager/StackedVolume.cpp deleted file mode 100644 index 6dcd44ee74..0000000000 --- a/v3d_main/terafly/src/core/imagemanager/StackedVolume.cpp +++ /dev/null @@ -1,1178 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -* 2015-04-15. Alessandro. @ADDED definition for default constructor. -* 2015-04-06. Giulio. @CHANGED Modified prunt method: printing stacks information is now off by default -* 2015-03-03. Giulio. @ADDED check that ioplugin interleaves channels in loadSubvolume_to_UINT8. -* 2015-03-03. Giulio. @CHANGED the order of how RGB images are copied in the subvol buffer in loadSubvolume_to_UINT8. -* 2015-03-03. Giulio. @ADDED selection of IO plugin in the constructors if not provided. -* 2015-02-27. Alessandro. @ADDED automated selection of IO plugin if not provided. -* 2014-11-27 Giulio. @FIXED eliminated part of the dipendences from OpenCV and restored the corresponding code -* 2014-11-22 Giulio. @CHANGED code using OpenCV has been commente. It can be found searching comments containing 'Giulio_CV' -*/ - -#include -#include -#include "StackedVolume.h" -#include "Stack.h" -#include "RawFmtMngr.h" -#include "Tiff3DMngr.h" - -#ifdef _WIN32 -#include "dirent_win.h" -#else -#include -#endif -// Giulio_CV #include -// Giulio_CV #include -// Giulio_CV #include -#include -#include -#include "ProgressBar.h" - -#include "IOPluginAPI.h" // 2014-11-26. Giulio. - -using namespace std; -using namespace iim; - -// 2015-04-15. Alessandro. @ADDED definition for default constructor. -StackedVolume::StackedVolume(void) : VirtualVolume() -{ - /**/iim::debug(iim::LEV3, 0, __iim__current__function__); - - N_ROWS = N_COLS = 0; - reference_system.first = reference_system.second = reference_system.third = iim::axis_invalid; - VXL_1 = VXL_2 = VXL_3 = 0.0f; - STACKS = 0; -} - -StackedVolume::StackedVolume(const char* _root_dir) throw (IOException) -: VirtualVolume(_root_dir) // iannello ADDED -{ - /**/iim::debug(iim::LEV3, strprintf("_root_dir = \"%s\"", _root_dir).c_str(), __iim__current__function__); - - //throw IOException("in StackedVolume::StackedVolume(...): disabled to remove dependence from openCV"); // Giulio_CV - - // 2015-03-03. Giulio. @ADDED selection of IO plugin if not provided. - if(iom::IMIN_PLUGIN.compare("empty") == 0) - { - iom::IMIN_PLUGIN = "tiff2D"; - } - - //DIM_V = DIM_H = DIM_D = 0; - VXL_1 = VXL_2 = VXL_3 = 0; - N_ROWS = N_COLS = 0; - STACKS = NULL; - reference_system.first = reference_system.second = reference_system.third = axis_invalid; - - //without any configuration parameter, volume import must be done from the metadata file stored in the root directory, if it exists - char mdata_filepath[STATIC_STRINGS_SIZE]; - sprintf(mdata_filepath, "%s/%s", root_dir, iim::MDATA_BIN_FILE_NAME.c_str()); - if(iim::isFile(mdata_filepath)) - { - load(mdata_filepath); - initChannels(); - } - else - { - char errMsg[STATIC_STRINGS_SIZE]; - sprintf(errMsg, "in StackedVolume::StackedVolume(...): unable to find metadata file at %s", mdata_filepath); - throw IOException(errMsg); - } -} - -StackedVolume::StackedVolume(const char* _root_dir, ref_sys _reference_system, float _VXL_1, float _VXL_2, float _VXL_3, bool overwrite_mdata, bool save_mdata) throw (IOException) -: VirtualVolume(_root_dir) // iannello ADDED -{ - /**/iim::debug(iim::LEV3, strprintf("_root_dir=%s, ref_sys reference_system={%d,%d,%d}, VXL_1=%.4f, VXL_2=%.4f, VXL_3=%.4f", - _root_dir, _reference_system.first, _reference_system.second, _reference_system.third, _VXL_1, _VXL_2, _VXL_3).c_str(), __iim__current__function__); - - //throw IOException("in StackedVolume::StackedVolume(...): disabled to remove dependence from openCV"); // Giulio_CV - - // 2015-03-03. Giulio. @ADDED selection of IO plugin if not provided. - if(iom::IMIN_PLUGIN.compare("empty") == 0) - { - iom::IMIN_PLUGIN = "tiff2D"; - } - - //DIM_V = DIM_H = DIM_D = 0; - VXL_1 = VXL_2 = VXL_3 = 0; - N_ROWS = N_COLS = 0; - STACKS = NULL; - reference_system.first = reference_system.second = reference_system.third = axis_invalid; - - //trying to unserialize an already existing metadata file, if it doesn't exist the full initialization procedure is performed and metadata is saved - char mdata_filepath[STATIC_STRINGS_SIZE]; - sprintf(mdata_filepath, "%s/%s", root_dir, iim::MDATA_BIN_FILE_NAME.c_str()); - if(iim::isFile(mdata_filepath) && !overwrite_mdata) - load(mdata_filepath); - else - { - if(_reference_system.first == axis_invalid || _reference_system.second == axis_invalid || - _reference_system.third == axis_invalid || _VXL_1 == 0 || _VXL_2 == 0 || _VXL_3 == 0) - throw IOException("in StackedVolume::StackedVolume(...): invalid importing parameters"); - - reference_system.first = _reference_system.first; - reference_system.second = _reference_system.second; - reference_system.third = _reference_system.third; - VXL_1 = _VXL_1; - VXL_2 = _VXL_2; - VXL_3 = _VXL_3; - init(); - if(save_mdata) - save(mdata_filepath); - } - initChannels(); -} - -StackedVolume::~StackedVolume(void) -{ - /**/iim::debug(iim::LEV3, 0, __iim__current__function__); - - if(STACKS) - { - for(int row=0; rowgetHEIGHT();} -int StackedVolume::getStacksWidth(){return STACKS[0][0]->getWIDTH();} - -void StackedVolume::save(char* metadata_filepath) throw (IOException) -{ - /**/iim::debug(iim::LEV3, strprintf("metadata_filepath = \"%s\"", metadata_filepath).c_str(), __iim__current__function__); - - FILE *file = fopen(metadata_filepath, "wb"); - - // --- Alessandro 2013-04-23: added exception when file can't be opened in write mode - if(!file) - { - char errMsg[STATIC_STRINGS_SIZE]; - sprintf(errMsg, "in StackedVolume::save(): cannot write metadata binary file at \"%s\".\n\nPlease check write permissions on this storage.", metadata_filepath); - throw IOException(errMsg); - } - - float mdata_version = static_cast(iim::MDATA_BIN_FILE_VERSION); - fwrite(&mdata_version, sizeof(float), 1, file); // --- Alessandro 2012-12-31: added field for metadata file version - //str_size = (uint16)(strlen(root_dir) + 1); // --- Alessandro 2012-12-31: absolute filepaths in mdata.bin eliminated - //fwrite(&str_size, sizeof(uint16), 1, file); // --- Alessandro 2012-12-31: absolute filepaths in mdata.bin eliminated - //fwrite(root_dir, str_size, 1, file); // --- Alessandro 2012-12-31: absolute filepaths in mdata.bin eliminated - fwrite(&reference_system.first, sizeof(axis), 1, file); - fwrite(&reference_system.second, sizeof(axis), 1, file); // iannello CORRECTED - fwrite(&reference_system.third, sizeof(axis), 1, file); // iannello CORRECTED - fwrite(&VXL_1, sizeof(float), 1, file); - fwrite(&VXL_2, sizeof(float), 1, file); - fwrite(&VXL_3, sizeof(float), 1, file); - fwrite(&VXL_V, sizeof(float), 1, file); - fwrite(&VXL_H, sizeof(float), 1, file); - fwrite(&VXL_D, sizeof(float), 1, file); - fwrite(&ORG_V, sizeof(float), 1, file); - fwrite(&ORG_H, sizeof(float), 1, file); - fwrite(&ORG_D, sizeof(float), 1, file); - fwrite(&DIM_V, sizeof(uint32), 1, file); - fwrite(&DIM_H, sizeof(uint32), 1, file); - fwrite(&DIM_D, sizeof(uint32), 1, file); - fwrite(&N_ROWS, sizeof(uint16), 1, file); - fwrite(&N_COLS, sizeof(uint16), 1, file); - - for(int i = 0; i < N_ROWS; i++) - for(int j = 0; j < N_COLS; j++) - STACKS[i][j]->binarizeInto(file); - - fclose(file); -} - -void StackedVolume::load(char* metadata_filepath) throw (IOException) -{ - /**/iim::debug(iim::LEV3, strprintf("metadata_filepath = \"%s\"", metadata_filepath).c_str(), __iim__current__function__); - - // 2015-02-27. Alessandro. @ADDED automated selection of IO plugin if not provided. - // Currently, this class does not use the IO plugins, but directly calls functions in Tiff3DMngr.cpp. - // This should be changed if a different policy will be used in the future. - if(iom::IMIN_PLUGIN.compare("empty") == 0) - iom::IMIN_PLUGIN = "tiff2D"; - - //LOCAL VARIABLES - FILE *file; - int i,j; - size_t fread_return_val; - - file = fopen(metadata_filepath, "rb"); - - // --- Alessandro 2013-04-23: added exception when file can't be opened in read mode - if(!file) - { - char errMsg[STATIC_STRINGS_SIZE]; - sprintf(errMsg, "in StackedVolume::load(): cannot read metadata binary file at \"%s\".\n\nPlease check read permissions on this storage.", metadata_filepath); - throw IOException(errMsg); - } - - // --- Alessandro 2012-12-31: added field for metadata file version - float mdata_version_read = 0; - float mdata_version = static_cast(iim::MDATA_BIN_FILE_VERSION); - fread_return_val = fread(&mdata_version_read, sizeof(float), 1, file); - if(fread_return_val != 1 || mdata_version_read != mdata_version) - { - // --- Alessandro 2013-01-06: instead of throwing an exception, it is better to mantain compatibility -// char errMsg[STATIC_STRINGS_SIZE]; -// sprintf(errMsg, "in StackedVolume::unBinarizeFrom(...): metadata file version (%.2f) is different from the supported one (%.2f). " -// "Please re-import the current volume.", mdata_version_read, mdata_version); -// throw iim::IOException(errMsg); - - fclose(file); - file = fopen(metadata_filepath, "rb"); - uint16 str_size; - fread_return_val = fread(&str_size, sizeof(uint16), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in StackedVolume::unBinarizeFrom(...): error while reading binary metadata file"); - } - char stored_root_dir[STATIC_STRINGS_SIZE]; - fread_return_val = fread(stored_root_dir, str_size, 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in StackedVolume::unBinarizeFrom(...): error while reading binary metadata file"); - } - } - - - - fread_return_val = fread(&reference_system.first, sizeof(axis), 1, file); - //printf("\nreference_system.first = %d\n", reference_system.first); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in StackedVolume::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&reference_system.second, sizeof(axis), 1, file); - //printf("\nreference_system.first = %d\n", reference_system.second); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in StackedVolume::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&reference_system.third, sizeof(axis), 1, file); - //printf("\nreference_system.first = %d\n", reference_system.third); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in StackedVolume::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&VXL_1, sizeof(float), 1, file); - //printf("\nVXL_1 = %.3f\n", VXL_1); - - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in StackedVolume::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&VXL_2, sizeof(float), 1, file); - //printf("\nVXL_2 = %.3f\n", VXL_2); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in StackedVolume::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&VXL_3, sizeof(float), 1, file); - //printf("\nVXL_3 = %.3f\n", VXL_3); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in StackedVolume::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&VXL_V, sizeof(float), 1, file); - //printf("\nVXL_V = %.3f\n", VXL_V); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in StackedVolume::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&VXL_H, sizeof(float), 1, file); - //printf("\nVXL_H = %.3f\n", VXL_H); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in StackedVolume::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&VXL_D, sizeof(float), 1, file); - //printf("\nVXL_D = %.3f\n", VXL_D); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in StackedVolume::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&ORG_V, sizeof(float), 1, file); - //printf("\nORG_V = %.3f\n", ORG_V); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in StackedVolume::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&ORG_H, sizeof(float), 1, file); - //printf("\nORG_H = %.3f\n", ORG_H); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in StackedVolume::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&ORG_D, sizeof(float), 1, file); - //printf("\nORG_D = %.3f\n", ORG_D); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in StackedVolume::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&DIM_V, sizeof(uint32), 1, file); - //printf("\nDIM_V = %d\n", DIM_V); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in StackedVolume::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&DIM_H, sizeof(uint32), 1, file); - //printf("\nDIM_H = %d\n", DIM_H); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in StackedVolume::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&DIM_D, sizeof(uint32), 1, file); - //printf("\nDIM_D = %d\n", DIM_D); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in StackedVolume::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&N_ROWS, sizeof(uint16), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in StackedVolume::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&N_COLS, sizeof(uint16), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in StackedVolume::unBinarizeFrom(...): error while reading binary metadata file"); - } - - - STACKS = new Stack **[N_ROWS]; - for(i = 0; i < N_ROWS; i++) - { - STACKS[i] = new Stack *[N_COLS]; - for(j = 0; j < N_COLS; j++) - STACKS[i][j] = new Stack(this, i, j, file); - } - - fclose(file); -} - -void StackedVolume::init() throw (IOException) -{ - /**/iim::debug(iim::LEV3, 0, __iim__current__function__); - - // 2015-02-27. Alessandro. @ADDED automated selection of IO plugin if not provided. - // Currently, this class does not use the IO plugins, but directly calls functions in Tiff3DMngr.cpp. - // This should be changed if a different policy will be used in the future. - if(iom::IMIN_PLUGIN.compare("empty") == 0) - iom::IMIN_PLUGIN = "tiff2D"; - - /************************* 1) LOADING STRUCTURE ************************* - *************************************************************************/ - - //LOCAL VARIABLES - string tmp_path; //string that contains temp paths during computation - string tmp; //string that contains temp data during computation - DIR *cur_dir_lev1; //pointer to DIR, the data structure that represents a DIRECTORY (level 1 of hierarchical structure) - DIR *cur_dir_lev2; //pointer to DIR, the data structure that represents a DIRECTORY (level 2 of hierarchical structure) - dirent *entry_lev1; //pointer to DIRENT, the data structure that represents a DIRECTORY ENTRY inside a directory (level 1) - dirent *entry_lev2; //pointer to DIRENT, the data structure that represents a DIRECTORY ENTRY inside a directory (level 2) - int i=0,j=0; //for counting of N_ROWS, N_COLS - list stacks_list; //each stack found in the hierarchy is pushed into this list - list entries_lev1; //list of entries of first level of hierarchy - list::iterator entry_i; //iterator for list 'entries_lev1' - list entries_lev2; //list of entries of second level of hierarchy - list::iterator entry_j; //iterator for list 'entries_lev2' - char stack_i_j_path[STATIC_STRINGS_SIZE]; - - //obtaining DIR pointer to root_dir (=NULL if directory doesn't exist) - if (!(cur_dir_lev1=opendir(root_dir))) - { - char msg[STATIC_STRINGS_SIZE]; - sprintf(msg,"in StackedVolume::init(...): Unable to open directory \"%s\"", root_dir); - throw IOException(msg); - } - - //scanning first level of hierarchy which entries need to be ordered alphabetically. This is done using STL. - while ((entry_lev1=readdir(cur_dir_lev1))) - { - tmp=entry_lev1->d_name; - if(tmp.find(".") == string::npos && tmp.find(" ") == string::npos) - entries_lev1.push_front(entry_lev1->d_name); - } - closedir(cur_dir_lev1); - entries_lev1.sort(); - N_ROWS = (uint16) entries_lev1.size(); - N_COLS = 0; - - //for each entry of first level, scanning second level - for(entry_i = entries_lev1.begin(), i=0; entry_i!= entries_lev1.end(); entry_i++, i++) - { - //building absolute path of first level entry to be used for "opendir(...)" - tmp_path=root_dir; - tmp_path.append("/"); - tmp_path.append(*entry_i); - cur_dir_lev2 = opendir(tmp_path.c_str()); - if (!cur_dir_lev2) - throw IOException("in StackedVolume::init(...): A problem occurred during scanning of subdirectories"); - - //scanning second level of hierarchy which entries need to be ordered alphabetically. This is done using STL. - while ((entry_lev2=readdir(cur_dir_lev2))) - { - tmp=entry_lev2->d_name; - if(tmp.find(".") == string::npos && tmp.find(" ") == string::npos) - entries_lev2.push_back(entry_lev2->d_name); - } - closedir(cur_dir_lev2); - entries_lev2.sort(); - - //for each entry of the second level, allocating a new Stack - for(entry_j = entries_lev2.begin(), j=0; entry_j!= entries_lev2.end(); entry_j++, j++) - { - //allocating new stack - sprintf(stack_i_j_path,"%s/%s",(*entry_i).c_str(), (*entry_j).c_str()); - Stack *new_stk = new Stack(this,i,j,stack_i_j_path); - stacks_list.push_back(new_stk); - } - entries_lev2.clear(); - if(N_COLS == 0) - N_COLS = j; - else if(j != N_COLS) - throw IOException("in StackedVolume::init(...): Number of second-level directories is not the same for all first-level directories!"); - } - entries_lev1.clear(); - - //intermediate check - if(N_ROWS == 0 || N_COLS == 0) - throw IOException("in StackedVolume::init(...): Unable to find stacks in the given directory"); - - //converting stacks_list (STL list of Stack*) into STACKS (2-D array of Stack*) - STACKS = new Stack**[N_ROWS]; - for(int row=0; row < N_ROWS; row++) - STACKS[row] = new Stack*[N_COLS]; - for(list::iterator i = stacks_list.begin(); i != stacks_list.end(); i++) - STACKS[(*i)->getROW_INDEX()][(*i)->getCOL_INDEX()] = (*i); - - /******************* 2) SETTING THE REFERENCE SYSTEM ******************** - The entire application uses a vertical-horizontal reference system, so - it is necessary to fit the original reference system into the new one. - *************************************************************************/ - - //adjusting possible sign mismatch betwwen reference system and VXL - //in these cases VXL is adjusted to match with reference system - if(sgn(reference_system.first) != sgn(VXL_1)) - VXL_1*=-1.0f; - if(sgn(reference_system.second) != sgn(VXL_2)) - VXL_2*=-1.0f; - if(sgn(reference_system.third) != sgn(VXL_3)) - VXL_3*=-1.0f; - - //HVD --> VHD - if (abs(reference_system.first)==2 && abs(reference_system.second)==1 && reference_system.third==3) - { - this->rotate(90); - this->mirror(axis(2)); - - if(reference_system.first == -2) - this->mirror(axis(2)); - if(reference_system.second == -1) - this->mirror(axis(1)); - - int computed_ORG_1, computed_ORG_2, computed_ORG_3; - extractCoordinates(STACKS[0][0], 0, &computed_ORG_1, &computed_ORG_2, &computed_ORG_3); - ORG_V = computed_ORG_2/10000.0F; - ORG_H = computed_ORG_1/10000.0F; - ORG_D = computed_ORG_3/10000.0F; - VXL_V = VXL_2 ; - VXL_H = VXL_1 ; - VXL_D = VXL_3 ; - } - //VHD --> VHD - else if (abs(reference_system.first)==1 && abs(reference_system.second)==2 && reference_system.third==3) - { - if(reference_system.first == -1) - this->mirror(axis(1)); - if(reference_system.second == -2) - this->mirror(axis(2)); - - int computed_ORG_1, computed_ORG_2, computed_ORG_3; - extractCoordinates(STACKS[0][0], 0, &computed_ORG_1, &computed_ORG_2, &computed_ORG_3); - ORG_V = computed_ORG_1/10000.0F; - ORG_H = computed_ORG_2/10000.0F; - ORG_D = computed_ORG_3/10000.0F; - VXL_V = VXL_1; - VXL_H = VXL_2; - VXL_D = VXL_3; - } - //unsupported reference system - else - { - char msg[STATIC_STRINGS_SIZE]; - sprintf(msg, "in StackedVolume::init(...): the reference system {%d,%d,%d} is not supported.", - reference_system.first, reference_system.second, reference_system.third); - throw IOException(msg); - } - - // GI_140628: this adjustment should not be performed by the converter since it operates on volumes already adjusted - //some little adjustments of the origin - //if(VXL_V < 0) - // ORG_V -= (STACKS[0][0]->getHEIGHT()-1)* VXL_V/1000.0f; - - //if(VXL_H < 0) - // ORG_H -= (STACKS[0][0]->getWIDTH() -1)* VXL_H/1000.0f; - - /******************** 3) COMPUTING VOLUME DIMENSIONS ******************** - *************************************************************************/ - for(int row=0; row < N_ROWS; row++) - for(int col=0; col < N_COLS; col++) - { - if(row==0) - DIM_H+=STACKS[row][col]->getWIDTH(); - if(col==0) - DIM_V+=STACKS[row][col]->getHEIGHT(); - DIM_D = STACKS[row][col]->getDEPTH() > DIM_D ? STACKS[row][col]->getDEPTH() : DIM_D; - } - - /**************** 4) COMPUTING STACKS ABSOLUTE POSITIONS **************** - *************************************************************************/ - for(int row=0; row < N_ROWS; row++) - for(int col=0; col < N_COLS; col++) - { - if(row) - STACKS[row][col]->setABS_V(STACKS[row-1][col]->getABS_V()+STACKS[row-1][col]->getHEIGHT()); - else - STACKS[row][col]->setABS_V(0); - - if(col) - STACKS[row][col]->setABS_H(STACKS[row][col-1]->getABS_H()+STACKS[row][col-1]->getWIDTH()); - else - STACKS[row][col]->setABS_H(0); - } -} - -void StackedVolume::initChannels ( ) throw (IOException) -{ - /**/iim::debug(iim::LEV3, 0, __iim__current__function__); - - char slice_fullpath[STATIC_STRINGS_SIZE]; - int img_width; - int img_height; - std::string params; - - sprintf(slice_fullpath, "%s/%s/%s", root_dir, STACKS[0][0]->getDIR_NAME(), STACKS[0][0]->getFILENAMES()[0]); - - // Giulio_CVIplImage* slice = cvLoadImage(slice_fullpath, CV_LOAD_IMAGE_ANYCOLOR); // 2014-10-03. Alessandro. @FIXED: eliminated CV_LOAD_IMAGE_ANYDEPTH flag since we want 16 bit images to be automatically converted to 8 bit. - try - { - iomanager::IOPluginFactory::getPlugin2D(iom::IMIN_PLUGIN)->readMetadata(slice_fullpath, img_width, img_height, BYTESxCHAN, DIM_C, params); - } - catch (iom::exception & ex) - { - throw iim::IOException(ex.what()); - } - - /* Giulio_CV - - if(!slice) - throw IOException(std::string("Unable to load slice at \"").append(slice_fullpath).append("\"").c_str()); - DIM_C = slice->nChannels; - - if ( depth == 8 ) - BYTESxCHAN = 1; - else if ( depth == 16 ) - BYTESxCHAN = 2; - else if ( depth == 32 ) - BYTESxCHAN = 4; - else { - char msg[STATIC_STRINGS_SIZE]; - sprintf(msg,"in SimpleVolume::initChannels: unknown color depth"); - throw IOException(msg); - } - - */ - - n_active = DIM_C; - active = new uint32[n_active]; - for ( int c=0; cprint(); - } - printf("\n*** END printing StakedVolume object...\n\n"); -} - -//rotate stacks matrix around D axis (accepted values are theta=0,90,180,270) -void StackedVolume::rotate(int theta) -{ - /**/iim::debug(iim::LEV3, strprintf("theta=%d", theta).c_str(), __iim__current__function__); - - //PRECONDITIONS: - // 1) current StackedVolume object has been initialized (init() method has been called) - // 2) accepted values for 'theta' are 0,90,180,270 - - //POSTCONDITIONS: - // 1) a new 2D-array of Stack* objects is created considering a rotation of 'theta' angle of current StackedVolume object - - Stack*** new_STACK_2D_ARRAY = NULL; - int new_N_ROWS = 0, new_N_COLS = 0; - - switch(theta) - { - case(0): break; - - case(90): - { - new_N_COLS = N_ROWS; - new_N_ROWS = N_COLS; - - //allocating new_STACK_2D_ARRAY - new_STACK_2D_ARRAY = new Stack**[new_N_ROWS]; - for(int i=0; isetROW_INDEX(i); - new_STACK_2D_ARRAY[i][j]->setCOL_INDEX(j); - } - break; - } - case(180): - { - new_N_COLS=N_COLS; - new_N_ROWS=N_ROWS; - - //allocating new_STACK_2D_ARRAY - new_STACK_2D_ARRAY = new Stack**[new_N_ROWS]; - for(int i=0; isetROW_INDEX(i); - new_STACK_2D_ARRAY[i][j]->setCOL_INDEX(j); - } - break; - } - case(270): - { - new_N_COLS=N_ROWS; - new_N_ROWS=N_COLS; - - //allocating new_STACK_2D_ARRAY - new_STACK_2D_ARRAY = new Stack**[new_N_ROWS]; - for(int i=0; isetROW_INDEX(i); - new_STACK_2D_ARRAY[i][j]->setCOL_INDEX(j); - } - break; - } - } - - - //deallocating current STACK_2DARRAY object - for(int row=0; rowsetROW_INDEX(i); - new_STACK_2D_ARRAY[i][j]->setCOL_INDEX(j); - } - break; - } - case(2): - { - //allocating new_STACK_2D_ARRAY - new_STACK_2D_ARRAY = new Stack**[N_ROWS]; - for(int i=0; isetROW_INDEX(i); - new_STACK_2D_ARRAY[i][j]->setCOL_INDEX(j); - } - break; - } - default: break; - } - - //deallocating current STACK_2DARRAY object - for(int row=0; rowgetDIR_NAME()[0])); - pch = strtok (buffer,"/_"); - pch = strtok (NULL, "/_"); - - while (pch != NULL) - { - if(!found_ABS_X) - { - if(sscanf(pch, "%d", crd_1) == 1) - found_ABS_X=true; - } - else if(!found_ABS_Y) - { - if(sscanf(pch, "%d", crd_2) == 1) - found_ABS_Y=true; - } - else - break; - - pch = strtok (NULL, "/_"); - } - - if(!found_ABS_X || !found_ABS_Y) - { - char msg[200]; - sprintf(msg,"in StackedVolume::extractCoordinates(directory_name=\"%s\"): format 000000_000000 or X_000000_X_000000 not found", stk->getDIR_NAME()); - throw msg; - } - - //loading estimation for absolute Z stack position - if(crd_3!= NULL) - { - char* first_file_name = stk->getFILENAMES()[z]; - - char * pch; - char lastTokenized[100]; - char buffer[500]; - strcpy(buffer,&(first_file_name[0])); - - pch = strtok (buffer,"_"); - while (pch != NULL) - { - strcpy(lastTokenized,pch); - pch = strtok (NULL, "_"); - } - - pch = strtok (lastTokenized,"."); - strcpy(lastTokenized,pch); - - if(sscanf(lastTokenized, "%d", crd_3) != 1) - { - char msg[200]; - sprintf(msg,"in StackedVolume::extractCoordinates(...): unable to extract Z position from filename %s", first_file_name); - throw msg; - } - } -} - -//loads given subvolume in a 1-D array of float -real32* StackedVolume::loadSubvolume(int V0,int V1, int H0, int H1, int D0, int D1, list *involved_stacks, bool release_stacks) throw (IOException) -{ - /**/iim::debug(iim::LEV3, strprintf("V0=%d, V1=%d, H0=%d, H1=%d, D0=%d, D1=%d%s", V0, V1, H0, H1, D0, D1, (involved_stacks? ", involved_stacks" : "")).c_str(), __iim__current__function__); - - throw IOException("in StackedVolume::loadSubvolume(...): disabled to remove dependence from openCV"); // Giulio_CV - - //checking for non implemented features - if( this->BYTESxCHAN != 1 ) { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"StackedVolume::loadSubvolume: invalid number of bytes per channel (%d)",this->BYTESxCHAN); - throw IOException(err_msg); - } - - //initializations - V0 = (V0 == -1 ? 0 : V0); - V1 = (V1 == -1 ? DIM_V : V1); - H0 = (H0 == -1 ? 0 : H0); - H1 = (H1 == -1 ? DIM_H : H1); - D0 = (D0 == -1 ? 0 : D0); - D1 = (D1 == -1 ? DIM_D : D1); - - //allocation - sint64 sbv_height = V1 - V0; - sint64 sbv_width = H1 - H0; - sint64 sbv_depth = D1 - D0; - real32 *subvol = new real32[sbv_height * sbv_width * sbv_depth]; - - //scanning of stacks matrix for data loading and storing into subvol - Rect_t subvol_area; - subvol_area.H0 = H0; - subvol_area.V0 = V0; - subvol_area.H1 = H1; - subvol_area.V1 = V1; - - /* Giulio_CV - - for(int row=0; rowIntersects(subvol_area); - if(intersect_area) - { - //printf("\t\t\t\tin StackedVolume::loadSubvolume(): using STACK[%d,%d] for area %d-%d(V) x %d-%d(H)\n", row, col, intersect_area->V0-V0, intersect_area->V1-V0, intersect_area->H0-H0, intersect_area->H1-H0); - - STACKS[row][col]->loadStack(D0, D1-1); - if(involved_stacks) - involved_stacks->push_back(STACKS[row][col]); - - for(int k=0; kgetSTACKED_IMAGE()[D0+k]; - int step = slice->step/sizeof(float); - float *data = slice->data.fl; - int ABS_V_stk = STACKS[row][col]->getABS_V(); - int ABS_H_stk = STACKS[row][col]->getABS_H(); - - for(int i=intersect_area->V0-V0; iV1-V0; i++) - for(int j=intersect_area->H0-H0; jH1-H0; j++) - subvol[k*sbv_height*sbv_width + i*sbv_width + j] = (data+(i-ABS_V_stk+V0)*step)[j-ABS_H_stk+H0]; - } - - if(release_stacks) - STACKS[row][col]->releaseStack(); - } - } - - */ - - return subvol; -} - -//loads given subvolume in a 1-D array of uint8 while releasing stacks slices memory when they are no longer needed -//---03 nov 2011: added color support -uint8* StackedVolume::loadSubvolume_to_UINT8(int V0,int V1, int H0, int H1, int D0, int D1, int *channels, int ret_type) throw (IOException) -{ - /**/iim::debug(iim::LEV3, strprintf("V0=%d, V1=%d, H0=%d, H1=%d, D0=%d, D1=%d, *channels=%d, ret_type=%d", V0, V1, H0, H1, D0, D1, channels ? *channels : -1, ret_type).c_str(), __iim__current__function__); - - //throw IOException("in StackedVolume::loadSubvolume_to_UINT8(...): disabled to remove dependence from openCV"); // Giulio_CV - - //checking for non implemented features - //if( this->BYTESxCHAN != 1 ) { - // char err_msg[STATIC_STRINGS_SIZE]; - // sprintf(err_msg,"StackedVolume::loadSubvolume_to_UINT8: invalid number of bytes per channel (%d)",this->BYTESxCHAN); - // throw iim::IOException(err_msg); - //} - - //if ( (ret_type == iim::DEF_IMG_DEPTH) && ((8 * this->BYTESxCHAN) != iim::DEF_IMG_DEPTH) ) { - // does not support depth conversion: - // return type is 8 bits, but native depth is not 8 bits - if ( (ret_type != iim::NATIVE_RTYPE) && (ret_type != iim::DEF_IMG_DEPTH) ) { - // return type should be converted, but not to 8 bits per channel - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"RawVolume::loadSubvolume_to_UINT8: non supported return type (%d bits) - native type is %d bits",ret_type, 8*this->BYTESxCHAN); - throw IOException(err_msg); - } - - // reduction factor to be applied to the loaded buffer - int red_factor = (ret_type == iim::NATIVE_RTYPE) ? 1 : ((8 * this->BYTESxCHAN) / ret_type); - - //initializations - V0 = V0 < 0 ? 0 : V0; - H0 = H0 < 0 ? 0 : H0; - D0 = D0 < 0 ? 0 : D0; - V1 = (V1 < 0 || V1 > (int)DIM_V) ? DIM_V : V1; // iannello MODIFIED - H1 = (H1 < 0 || H1 > (int)DIM_H) ? DIM_H : H1; // iannello MODIFIED - D1 = (D1 < 0 || D1 > (int)DIM_D) ? DIM_D : D1; // iannello MODIFIED - uint8 *subvol = 0; - - //checking that the interval is valid - if(V1-V0 <=0 || H1-H0 <= 0 || D1-D0 <= 0) - throw IOException("in StackedVolume::loadSubvolume_to_UINT8: invalid subvolume intervals"); - - //computing dimensions - sint64 sbv_height = V1 - V0; - sint64 sbv_width = H1 - H0; - sint64 sbv_depth = D1 - D0; - - //initializing the number of channels with an undefined value (it will be detected from the first slice read) - sint64 sbv_channels = -1; - - //scanning of stacks matrix for data loading and storing into subvol - Rect_t subvol_area; - subvol_area.H0 = H0; - subvol_area.V0 = V0; - subvol_area.H1 = H1; - subvol_area.V1 = V1; - char slice_fullpath[STATIC_STRINGS_SIZE]; - bool first_time = true; - - for(int row=0; rowIntersects(subvol_area); - if(intersect_area) - { - //printf("\t\t\t\tin StackedVolume::loadSubvolume_to_UINT8(): using STACK[%d,%d] for area %d-%d(V) x %d-%d(H)\n", row, col, intersect_area->V0-V0, intersect_area->V1-V0, intersect_area->H0-H0, intersect_area->H1-H0); - - for(int k=0; kgetDIR_NAME(), STACKS[row][col]->getFILENAMES()[D0+k]); - //IplImage* slice = cvLoadImage(slice_fullpath, CV_LOAD_IMAGE_ANYCOLOR); // 2014-10-03. Alessandro. @FIXED: eliminated CV_LOAD_IMAGE_ANYDEPTH flag since we want 16 bit images to be automatically converted to 8 bit. - - char *err_Tiff3Dfmt; - - unsigned int rows; - unsigned int cols; - unsigned int n_slices; - unsigned int chans; - int bytes_x_chan; - int swap; - void *dummy; - int dummy_len; - - if ( (err_Tiff3Dfmt = loadTiff3D2Metadata((char *)slice_fullpath,cols,rows,n_slices,chans,bytes_x_chan,swap,dummy,dummy_len)) != 0 ) { - throw iom::exception(iom::strprintf("unable to read tiff file (%s)",err_Tiff3Dfmt), __iom__current__function__); - } - closeTiff3DFile(dummy); - uint8 *slice = new uint8[rows * cols * chans * bytes_x_chan]; - if ( (err_Tiff3Dfmt = readTiff3DFile2Buffer((char *)slice_fullpath,slice,cols,rows,0,0)) != 0 ) { - throw iom::exception(iom::strprintf("unable to read tiff file (%s)",err_Tiff3Dfmt), __iom__current__function__); - } - - //if(!slice) - // throw IOException(std::string("Unable to load slice at \"").append(slice_fullpath).append("\"").c_str()); - - //if this is the first time a slice is loaded, detecting the number of channels and safely allocating memory for data - if(first_time) - { - first_time = false; - sbv_channels = DIM_C; // Giulio_CV slice->nChannels; - - if(sbv_channels != 1 && sbv_channels != 3) - throw IOException(std::string("Unsupported number of channels at \"").append(slice_fullpath).append("\". Only 1 and 3-channels images are supported").c_str()); - - if ( sbv_channels >1 && !(iom::IOPluginFactory::getPlugin2D(iom::IMIN_PLUGIN)->isChansInterleaved()) ) { - throw iom::exception("the plugin do not store channels in interleaved mode: more than one channel not supported yet."); - } - - try - { - subvol = new uint8[sbv_height * sbv_width * sbv_depth * sbv_channels]; - } - catch(...){throw IOException("in StackedVolume::loadSubvolume_to_UINT8: unable to allocate memory");} - } - //otherwise checking that all the other slices have the same bitdepth of the first one - else if (chans != sbv_channels || bytes_x_chan != BYTESxCHAN ) - throw iom::exception( - iom::strprintf(std::string("Image channels/bytes_x_chans mismatch at slice \"").append(slice_fullpath).append("\" (%d-%d / %d-%d): all slices must have the same bitdepth").c_str(), - chans,sbv_channels,bytes_x_chan,BYTESxCHAN), __iom__current__function__); - //throw IOException(std::string("Image channels/width/height mismatch at slice \"").append(slice_fullpath).append("\" (%d-%d / %d-%d / %d-%d): all slices must have the same bitdepth").c_str()); - - - //computing offsets - int slice_step = cols * bytes_x_chan * chans; // Giulio_CV slice->widthStep / sizeof(uint8); - int ABS_V_offset = V0 - STACKS[row][col]->getABS_V(); - int ABS_H_offset = (H0 - STACKS[row][col]->getABS_H())*((int)sbv_channels); - - //different procedures for 1 and 3 channels images - int istart, iend, jstart, jend; - istart = intersect_area->V0-V0; - iend = intersect_area->V1-V0; - jstart = intersect_area->H0-H0; - jend = intersect_area->H1-H0; - if(sbv_channels == 1) - { - sint64 k_offset = k*sbv_height*sbv_width; - for(int i = istart; i < iend; i++) - { - uint8* slice_row = slice + (i+ABS_V_offset)*slice_step; - for(int j = jstart; j < jend; j++) - subvol[k_offset + i*sbv_width + j] = slice_row[j+ABS_H_offset]; - } - } - else if(sbv_channels == 3) - { - - sint64 offset1 = k*sbv_height*sbv_width; - sint64 offset2 = sbv_height*sbv_width*sbv_depth + offset1; - sint64 offset3 = 2*sbv_height*sbv_width*sbv_depth + k*sbv_height*sbv_width; - for(int i = istart; i < iend; i++) - { - uint8* slice_row = slice + (i+ABS_V_offset)*slice_step; - for(int j1 = jstart, j2 = jstart*3; j1 < jend; j1++, j2+=3) - { - // next code assumes that channels are inteleaved as R-G-B - subvol[offset1 + i*sbv_width + j1] = slice_row[j2 + ABS_H_offset]; - subvol[offset2 + i*sbv_width + j1] = slice_row[j2 + ABS_H_offset + 1]; - subvol[offset3 + i*sbv_width + j1] = slice_row[j2 + ABS_H_offset + 2]; - - // next code assumes that channels are inteleaved as B-G-R - //subvol[offset1 + i*sbv_width + j1] = slice_row[j2 + ABS_H_offset + 2]; - //subvol[offset2 + i*sbv_width + j1] = slice_row[j2 + ABS_H_offset + 1]; - //subvol[offset3 + i*sbv_width + j1] = slice_row[j2 + ABS_H_offset]; - } - } - } - else - throw IOException(std::string("Unsupported number of channels at \"").append(slice_fullpath).append("\". Only 1 and 3-channels images are supported").c_str()); - - delete []slice; // Giulio_CV cvReleaseImage(&slice); - } - } - } - - //returning outputs - if(channels) - *channels = (int)sbv_channels; - - if ( red_factor > 1 ) { // the buffer has to be reduced - char *err_rawfmt; - if ( (err_rawfmt = convert2depth8bits(red_factor,(sbv_height*sbv_width*sbv_depth),sbv_channels,subvol)) != 0 ) { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"StackedVolume::loadSubvolume_to_UINT8: %s", err_rawfmt); - throw IOException(err_msg); - } - } - - return subvol; -} - -//releases allocated memory of stacks -void StackedVolume::releaseStacks(int first_file, int last_file) -{ - /**/iim::debug(iim::LEV3, strprintf("first_file = %d, last_file = %d", first_file, last_file).c_str(), __iim__current__function__); - - first_file = (first_file == -1 ? 0 : first_file); - last_file = (last_file == -1 ? DIM_D : last_file); - for(int row_index=0; row_indexreleaseStack(first_file,last_file); -} diff --git a/v3d_main/terafly/src/core/imagemanager/StackedVolume.h b/v3d_main/terafly/src/core/imagemanager/StackedVolume.h deleted file mode 100644 index 6cf1feff90..0000000000 --- a/v3d_main/terafly/src/core/imagemanager/StackedVolume.h +++ /dev/null @@ -1,144 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -2015-04-06. Giulio. @CHANGED Modified prunt method: printing stacks information is now off by default -*/ - -#ifndef _IIM_STACKED_VOLUME_H -#define _IIM_STACKED_VOLUME_H - -#include "VirtualVolume.h" // ADDED -#include -#include -#include "Stack.h" - -//FORWARD-DECLARATIONS -//class Stack; - -//every object of this class has the default (1,2,3) reference system -class iim::StackedVolume : public iim::VirtualVolume -{ - private: - -/* - iannello ATTRBUTES OF BASE ABSTRACT CLASS - - char* stacks_dir; //C-string that contains the directory path of stacks matrix - float VXL_V, VXL_H, VXL_D; //voxel dimensions (in microns) along V(Vertical), H(horizontal) and D(Depth) axes - float ORG_V, ORG_H, ORG_D; //origin spatial coordinates (in millimeters) along VHD axes - iim::uint32 DIM_V, DIM_H, DIM_D; //volume dimensions (in voxels) along VHD axes -*/ - - //******OBJECT ATTRIBUTES****** - iim::uint16 N_ROWS, N_COLS; //dimensions (in stacks) of stacks matrix along VH axes - Stack ***STACKS; //2-D array of - iim::ref_sys reference_system; //reference system of the stored volume - float VXL_1, VXL_2, VXL_3; //voxel dimensions of the stored volume - - //***OBJECT PRIVATE METHODS**** - StackedVolume(void); - - //Given the reference system, initializes all object's members using stack's directories hierarchy - void init() throw (iim::IOException); - - //rotate stacks matrix around D axis (accepted values are theta=0,90,180,270) - void rotate(int theta); - - //mirror stacks matrix along mrr_axis (accepted values are mrr_axis=1,2,3) - void mirror(iim::axis mrr_axis); - - //extract spatial coordinates (in millimeters) of given Stack object reading directory and filenames as spatial coordinates - void extractCoordinates(Stack* stk, int z, int* crd_1, int* crd_2, int* crd_3); - - // iannello returns the number of channels of images composing the volume - void initChannels ( ) throw (iim::IOException); - - public: - - //CONSTRUCTORS-DECONSTRUCTOR - StackedVolume(const char* _root_dir) throw (iim::IOException); - StackedVolume(const char* _root_dir, iim::ref_sys _reference_system, - float _VXL_1, float _VXL_2, float _VXL_3, - bool overwrite_mdata = false, bool save_mdata=true) throw (iim::IOException); - ~StackedVolume(void); - - //GET methods - // iannello char* getSTACKS_DIR(){return stacks_dir;} - Stack*** getSTACKS(){return STACKS;} - // iannello iim::uint32 getDIM_V(){return DIM_V;} - // iannello iim::uint32 getDIM_H(){return DIM_H;} - // iannello iim::uint32 getDIM_D(){return DIM_D;} - iim::uint16 getN_ROWS(){return N_ROWS;} - iim::uint16 getN_COLS(){return N_COLS;} - // iannello float getVXL_V(){return VXL_V;} - // iannello float getVXL_H(){return VXL_H;} - // iannello float getVXL_D(){return VXL_D;} - // iannello float getORG_V(){return ORG_V;} - // iannello float getORG_H(){return ORG_H;} - // iannello float getORG_D(){return ORG_D;} - int getStacksHeight(); - int getStacksWidth(); - float getVXL_1(){return VXL_1;} - float getVXL_2(){return VXL_2;} - float getVXL_3(){return VXL_3;} - iim::axis getAXS_1(){return reference_system.first;} - iim::axis getAXS_2(){return reference_system.second;} - iim::axis getAXS_3(){return reference_system.third;} - - // returns a unique ID that identifies the volume format - std::string getPrintableFormat(){return iim::STACKED_FORMAT;} - - - //PRINT method - void print( bool print_stacks = false ); - - //saving-loading methods to/from metadata binary file - void save(char* metadata_filepath) throw (iim::IOException); - void load(char* metadata_filepath) throw (iim::IOException); - - //loads given subvolume in a 1-D array of iim::real32 while releasing stacks slices memory when they are no longer needed - inline iim::real32 *loadSubvolume_to_real32(int V0=-1,int V1=-1, int H0=-1, int H1=-1, int D0=-1, int D1=-1) throw (iim::IOException) { - return loadSubvolume(V0,V1,H0,H1,D0,D1,0,true); - } - - //loads given subvolume in a 1-D array and puts used Stacks into 'involved_stacks' iff not null - iim::real32 *loadSubvolume(int V0=-1,int V1=-1, int H0=-1, int H1=-1, int D0=-1, int D1=-1, - std::list *involved_stacks = 0, bool release_stacks = false) throw (iim::IOException); - - //loads given subvolume in a 1-D array of iim::uint8 while releasing stacks slices memory when they are no longer needed - iim::uint8 *loadSubvolume_to_UINT8(int V0=-1,int V1=-1, int H0=-1, int H1=-1, int D0=-1, int D1=-1, - int *channels=0, int ret_type=iim::DEF_IMG_DEPTH) throw (iim::IOException); - - - //releases allocated memory of stacks - void releaseStacks(int first_file=-1, int last_file=-1); - - friend class iim::VirtualVolume; - -}; - -#endif //_STACKED_VOLUME_H diff --git a/v3d_main/terafly/src/core/imagemanager/Tiff3DMngr.cpp b/v3d_main/terafly/src/core/imagemanager/Tiff3DMngr.cpp deleted file mode 100644 index 82de54bd89..0000000000 --- a/v3d_main/terafly/src/core/imagemanager/Tiff3DMngr.cpp +++ /dev/null @@ -1,554 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -******************* -* 2015-03-03. Giulio. @FIXED RGB photometric interprettion has to be set when there is more than one channel -* 2015-02-06. Giulio. @ADDED append operation that assume an already open and positioned file -* 2015-02-06. Giulio. @ADDED open operation -* 2015-01-30. Alessandro. @ADDED performance (time) measurement in all most time-consuming methods. -* 2014-12-10. Giulio. @ADDED added management of mismatch between machine/image endian -* 2014-12-06. Giulio. @FIXED input file should NOT be closed at the end of 'loadTiff3D2Metadata' -* 2014-12-05. Giulio. @ADDED input file should be closed at the end of 'loadTiff3D2Metadata' -*/ - -#include "Tiff3DMngr.h" -#include // needed by clang: defines size_t -#include -#include "tiffio.h" - -#ifdef _VAA3D_TERAFLY_PLUGIN_MODE -#include -#include "PLog.h" -#include "COperation.h" -#endif - - - - -static -void swap2bytes(void *targetp) -{ - unsigned char * tp = (unsigned char *)targetp; - unsigned char a = *tp; - *tp = *(tp+1); - *(tp+1) = a; -} - -static -void swap4bytes(void *targetp) -{ - unsigned char * tp = (unsigned char *)targetp; - unsigned char a = *tp; - *tp = *(tp+3); - *(tp+3) = a; - a = *(tp+1); - *(tp+1) = *(tp+2); - *(tp+2) = a; -} - - -char *loadTiff3D2Metadata ( char * filename, unsigned int &sz0, unsigned int &sz1, unsigned int &sz2, unsigned int &sz3, int &datatype, int &b_swap, void * &fhandle, int &header_len ) { - - // 2015-01-30. Alessandro. @ADDED performance (time) measurement in all most time-consuming methods. - #ifdef _VAA3D_TERAFLY_PLUGIN_MODE - TERAFLY_TIME_START(TiffLoadMetadata) - #endif - - uint32 XSIZE; - uint32 YSIZE; - uint16 bpp; - uint16 spp; - uint16 Cpage; - uint16 Npages; - TIFF *input; - int check; - - //disable warning handler to avoid messages on unrecognized tags - TIFFSetWarningHandler(0); - - input=TIFFOpen(filename,"r"); - if (!input) - { - //throw iim::IOException(strprintf("in IOManager::readTiffMultipage(...): Cannot open the file %s",finName).c_str()); - return ((char *) "Cannot open the file."); - } - - check=TIFFGetField(input, TIFFTAG_IMAGEWIDTH, &XSIZE); - if (!check) - { - TIFFClose(input); - //throw iim::IOException(strprintf("in IOManager::readTiffMultipage(...): Image length of %s undefined\n", finName).c_str()); - return ((char *) "Image width of undefined."); - } - - check=TIFFGetField(input, TIFFTAG_IMAGELENGTH, &YSIZE); - if (!check) - { - TIFFClose(input); - //throw iim::IOException(strprintf("in IOManager::readTiffMultipage(...): Image length of %s undefined\n", finName).c_str()); - return ((char *) "Image length of undefined."); - } - - check=TIFFGetField(input, TIFFTAG_BITSPERSAMPLE, &bpp); - if (!check) - { - TIFFClose(input); - //throw iim::IOException(strprintf("in IOManager::readTiffMultipage(...): Undefined bits per sample in %s \n", finName).c_str()); - return ((char *) "Undefined bits per sample."); - } - - check=TIFFGetField(input, TIFFTAG_SAMPLESPERPIXEL, &spp); - if (!check) - { - TIFFClose(input); - //throw iim::IOException(strprintf("in IOManager::readTiffMultipage(...): Undefined bits per sample in %s \n", finName).c_str()); - return ((char *) "Undefined samples per pixel."); - } - - // Onofri - check=TIFFGetField(input, TIFFTAG_PAGENUMBER, &Cpage, &Npages); - if (!check || Npages==0) { // the tag has not been read correctly - // Add warning? - Npages = 0; - do { - Npages++; - } while ( TIFFReadDirectory(input) ); - } - - sz0 = XSIZE; - sz1 = YSIZE; - sz2 = Npages; - sz3 = spp; - datatype = bpp/8; - - //b_swap = 0; - b_swap=TIFFIsByteSwapped(input); - fhandle = (void *) input; - header_len = -1; - - // the file must non be closed (it is responsibility of the caller) - //TIFFClose(input); - - // 2015-01-30. Alessandro. @ADDED performance (time) measurement in all most time-consuming methods. - #ifdef _VAA3D_TERAFLY_PLUGIN_MODE - TERAFLY_TIME_STOP(TiffLoadMetadata, itm::IO, itm::strprintf("successfully loaded metadata from file \"%s\"", filename)) - #endif - - return ((char *) 0); -} - -char *openTiff3DFile ( char *filename, char *mode, void *&fhandle ) { - char *completeFilename = (char *) 0; - int fname_len = (int) strlen(filename); - char *suffix = strstr(filename,".tif"); - while ( suffix && (fname_len - (suffix-filename) > 5) ) - suffix = strstr(suffix+4,".tif"); - //if ( (suffix != 0) && (fname_len - (suffix-filename) <= 5) ) { // a substring ".tif is already at the end of the filename - if ( suffix ) { // a substring ".tif is already at the very end of the filename - completeFilename = new char[fname_len+1]; - strcpy(completeFilename,filename); - } - else { - completeFilename = new char[fname_len+4+1]; - strcpy(completeFilename,filename); - strcat(completeFilename,"."); - strcat(completeFilename,TIFF3D_SUFFIX); - } - - //disable warning handler to avoid messages on unrecognized tags - TIFFSetWarningHandler(0); - - fhandle = TIFFOpen(completeFilename,mode); - if (!fhandle) - { - return ((char *) "Cannot open the file."); - } - return ((char *) 0); -} - -void closeTiff3DFile ( void *fhandle ) { - TIFFClose((TIFF *) fhandle); -} - -char *initTiff3DFile ( char *filename, unsigned int sz0, unsigned int sz1, unsigned int sz2, unsigned int sz3, int datatype ) { -//int initTiff3DFile ( char *filename, uint32 XSIZE, uint32 YSIZE, uint16 spp, uint16 Npages, int datatype){ - - // 2015-01-30. Alessandro. @ADDED performance (time) measurement in all most time-consuming methods. - #ifdef _VAA3D_TERAFLY_PLUGIN_MODE - TERAFLY_TIME_START(TiffInitData) - #endif - - uint32 XSIZE = sz0; - uint32 YSIZE = sz1; - uint16 Npages = sz2; - uint16 spp = sz3; - - uint16 bpp=8 * datatype; - unsigned char *fakeData=new unsigned char[XSIZE * YSIZE]; - - int check; - - if ( sz3 == 1 ) - spp = sz3; - else if ( sz3 < 4 ) - spp = 3; - else - return ((char *) "More than 3 channels in Tiff files."); - - char *completeFilename = (char *) 0; - int fname_len = (int) strlen(filename); - char *suffix = strstr(filename,".tif"); - while ( suffix && (fname_len - (suffix-filename) > 5) ) - suffix = strstr(suffix+4,".tif"); - //if ( (suffix != 0) && (fname_len - (suffix-filename) <= 5) ) { // a substring ".tif is already at the end of the filename - if ( suffix ) { // a substring ".tif is already at the very end of the filename - completeFilename = new char[fname_len+1]; - strcpy(completeFilename,filename); - } - else { - completeFilename = new char[fname_len+4+1]; - strcpy(completeFilename,filename); - strcat(completeFilename,"."); - strcat(completeFilename,TIFF3D_SUFFIX); - } - - // 2015-01-30. Alessandro. @ADDED performance (time) measurement in all most time-consuming methods. - #ifdef _VAA3D_TERAFLY_PLUGIN_MODE - TERAFLY_TIME_STOP(TiffInitData, itm::CPU, itm::strprintf("generated fake data for 3D tiff \"%s\"", completeFilename)) - TERAFLY_TIME_RESTART(TiffInitData) - #endif - - //disable warning handler to avoid messages on unrecognized tags - TIFFSetWarningHandler(0); - - TIFF *output; - output = TIFFOpen(completeFilename,"w"); - if (!output) { - return ((char *) "Cannot open the file."); - } - - check = TIFFSetField(output, TIFFTAG_IMAGEWIDTH, XSIZE); - if (!check) { - return ((char *) "Cannot set the image width."); - } - - check = TIFFSetField(output, TIFFTAG_IMAGELENGTH, YSIZE); - if (!check) { - return ((char *) "Cannot set the image width."); - } - - check = TIFFSetField(output, TIFFTAG_BITSPERSAMPLE, bpp); - if (!check) { - return ((char *) "Cannot set the image width."); - } - - check = TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, spp); - if (!check) { - return ((char *) "Cannot set the image width."); - } - - check = TIFFSetField(output, TIFFTAG_ROWSPERSTRIP, YSIZE); // one page per strip - if (!check) { - return ((char *) "Cannot set the image height."); - } - - check = TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_LZW); - if (!check) { - return ((char *) "Cannot set the compression tag."); - } - - check = TIFFSetField(output, TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG); - if (!check) { - return ((char *) "Cannot set the planarconfig tag."); - } - - if ( spp == 1 ) - check = TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK); - else // spp == 3 - check = TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB); - if (!check) { - return ((char *) "Cannot set the photometric tag."); - } - - /* We are writing single page of the multipage file */ - check = TIFFSetField(output, TIFFTAG_SUBFILETYPE, FILETYPE_PAGE); - if (!check) { - return ((char *) "Cannot set the subfiletype tag."); - } - - check = TIFFSetField(output, TIFFTAG_PAGENUMBER, 0, Npages); - if (!check) { - return ((char *) "Cannot set the page number."); - } - - - check = (int)TIFFWriteEncodedStrip(output, 0, fakeData, XSIZE * YSIZE); - if (!check) { - return ((char *) "Cannot write encoded strip to file."); - } - - delete[] fakeData; - delete []completeFilename; - - check = TIFFWriteDirectory(output); - if (!check) { - return ((char *) "Cannot write a new directory."); - } - - TIFFClose(output); - - // 2015-01-30. Alessandro. @ADDED performance (time) measurement in all most time-consuming methods. - #ifdef _VAA3D_TERAFLY_PLUGIN_MODE - TERAFLY_TIME_STOP(TiffInitData, itm::IO, itm::strprintf("written initialized 3D tiff \"%s\"", completeFilename)) - #endif - - return (char *) 0; -} - -char *appendSlice2Tiff3DFile ( char *filename, int slice, unsigned char *img, unsigned int img_width, unsigned int img_height ) { - // 2015-01-30. Alessandro. @ADDED performance (time) measurement in all most time-consuming methods. - #ifdef _VAA3D_TERAFLY_PLUGIN_MODE - TERAFLY_TIME_START(TiffAppendData) - #endif - - TIFF *output; - uint16 spp, bpp, NPages, pg0; - - //disable warning handler to avoid messages on unrecognized tags - TIFFSetWarningHandler(0); - - output=TIFFOpen(filename,"r"); - TIFFGetField(output, TIFFTAG_BITSPERSAMPLE, &bpp); - TIFFGetField(output, TIFFTAG_SAMPLESPERPIXEL, &spp); - TIFFGetField(output, TIFFTAG_PAGENUMBER, &pg0, &NPages); - TIFFClose(output); - // since we are - output = (slice==0)? TIFFOpen(filename,"w") : TIFFOpen(filename,"a"); - - TIFFSetDirectory(output,slice); // WARNING: slice must be the first page after the last, otherwise the file can be corrupted - - TIFFSetField(output, TIFFTAG_IMAGEWIDTH, img_width); - TIFFSetField(output, TIFFTAG_IMAGELENGTH, img_height); - TIFFSetField(output, TIFFTAG_BITSPERSAMPLE, bpp); - TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, spp); - TIFFSetField(output, TIFFTAG_ROWSPERSTRIP, img_height); - TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_LZW); - //TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_NONE); - TIFFSetField(output, TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG); - TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK); - //TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB); - // We are writing single page of the multipage file - TIFFSetField(output, TIFFTAG_SUBFILETYPE, FILETYPE_PAGE); - TIFFSetField(output, TIFFTAG_PAGENUMBER, (uint16)slice, NPages); - - TIFFWriteEncodedStrip(output, 0, img, img_width * img_height * spp * (bpp/8)); - //img += img_width * img_height; - - TIFFWriteDirectory(output); - - TIFFClose(output); - - // 2015-01-30. Alessandro. @ADDED performance (time) measurement in all most time-consuming methods. - #ifdef _VAA3D_TERAFLY_PLUGIN_MODE - TERAFLY_TIME_STOP(TiffAppendData, itm::IO, itm::strprintf("appended slice %d x %d to 3D tiff \"%s\"", img_width, img_height, filename)) - #endif - - return (char *) 0; -} - -char *appendSlice2Tiff3DFile ( void *fhandler, int slice, unsigned char *img, unsigned int img_width, unsigned int img_height, int spp, int bpp, int NPages ) { - TIFF *output = (TIFF *) fhandler; - - TIFFSetDirectory(output,slice); // WARNING: slice must be the first page after the last, otherwise the file can be corrupted - - TIFFSetField(output, TIFFTAG_IMAGEWIDTH, img_width); - TIFFSetField(output, TIFFTAG_IMAGELENGTH, img_height); - TIFFSetField(output, TIFFTAG_BITSPERSAMPLE, (uint16)bpp); - TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, (uint16)spp); - TIFFSetField(output, TIFFTAG_ROWSPERSTRIP, img_height); - TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_LZW); - //TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_NONE); - TIFFSetField(output, TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG); - TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK); - //TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB); - // We are writing single page of the multipage file - TIFFSetField(output, TIFFTAG_SUBFILETYPE, FILETYPE_PAGE); - TIFFSetField(output, TIFFTAG_PAGENUMBER, (uint16)slice, (uint16)NPages); - - TIFFWriteEncodedStrip(output, 0, img, img_width * img_height * spp * (bpp/8)); - //img += img_width * img_height; - - TIFFWriteDirectory(output); - - return (char *) 0; -} - -char *readTiff3DFile2Buffer ( char *filename, unsigned char *img, unsigned int img_width, unsigned int img_height, unsigned int first, unsigned int last ) { - - // 2015-01-30. Alessandro. @ADDED performance (time) measurement in all most time-consuming methods. - #ifdef _VAA3D_TERAFLY_PLUGIN_MODE - TERAFLY_TIME_START(TiffLoadData) - #endif - - TIFF *input; - - //disable warning handler to avoid messages on unrecognized tags - TIFFSetWarningHandler(0); - - input=TIFFOpen(filename,"r"); - if (!input) - { - //throw iim::IOException(strprintf("in IOManager::readTiffMultipage(...): Cannot open the file %s",finName).c_str()); - return ((char *) "Cannot open the file."); - } - - int b_swap=TIFFIsByteSwapped(input); - char *err_msg = readTiff3DFile2Buffer(input,img,img_width,img_height,first,last,b_swap); - - TIFFClose(input); - - // 2015-01-30. Alessandro. @ADDED performance (time) measurement in all most time-consuming methods. - #ifdef _VAA3D_TERAFLY_PLUGIN_MODE - TERAFLY_TIME_STOP(TiffLoadData, itm::IO, itm::strprintf("loaded block x(%d), y(%d), z(%d-%d) from 3D tiff \"%s\"", img_width, img_height, first, last, filename)) - #endif - - return err_msg; -} - -char *readTiff3DFile2Buffer ( void *fhandler, unsigned char *img, unsigned int img_width, unsigned int img_height, unsigned int first, unsigned int last, int b_swap ) { - uint32 rps; - uint16 spp, bpp, photo, comp, planar_config; - int check, StripsPerImage,LastStripSize; - - TIFF *input = (TIFF *) fhandler; - - check=TIFFGetField(input, TIFFTAG_ROWSPERSTRIP, &rps); - if (!check) - { - return ((char *) "Image length of undefined."); - } - //rps=600; - - check=TIFFGetField(input, TIFFTAG_BITSPERSAMPLE, &bpp); - if (!check) - { - return ((char *) "Undefined bits per sample."); - } - - check=TIFFGetField(input, TIFFTAG_SAMPLESPERPIXEL, &spp); - if (!check) - { - return ((char *) "Undefined samples per pixel."); - } - - check=TIFFGetField(input, TIFFTAG_PHOTOMETRIC, &photo); - if (!check) - { - return ((char *) "Cannot determine photometric interpretation."); - } - - check=TIFFGetField(input, TIFFTAG_COMPRESSION, &comp); - if (!check) - { - return ((char *) "Cannot determine compression technique."); - } - - check=TIFFGetField(input, TIFFTAG_PLANARCONFIG, &planar_config); - if (!check) - { - return ((char *) "Cannot determine planar configuration."); - } - - - StripsPerImage = (img_height + rps - 1) / rps; - LastStripSize = img_height % rps; - if (LastStripSize==0) - LastStripSize=rps; - - check=TIFFSetDirectory(input, first); - if (!check) - { - return ((char *) "Cannot open the requested first strip."); - } - - unsigned char *buf = img; - int page=0; - do{ - - for (int i=0; i < StripsPerImage-1; i++){ - if (comp==1) { - TIFFReadRawStrip(input, i, buf, spp * rps * img_width * (bpp/8)); - buf = buf + spp * rps * img_width * (bpp/8); - } - else{ - TIFFReadEncodedStrip(input, i, buf, spp * rps * img_width * (bpp/8)); - buf = buf + spp * rps * img_width * (bpp/8); - } - } - - if (comp==1) { - TIFFReadRawStrip(input, StripsPerImage-1, buf, spp * LastStripSize * img_width * (bpp/8)); - } - else{ - TIFFReadEncodedStrip(input, StripsPerImage-1, buf, spp * LastStripSize * img_width * (bpp/8)); - } - buf = buf + spp * LastStripSize * img_width * (bpp/8); - - page++; - - }while ( page < static_cast(last-first+1) && TIFFReadDirectory(input));//while (TIFFReadDirectory(input)); - - // input file is assumedo ti be already open and it is provided as an handler; the file should be closed by caller - //TIFFClose(input); - - if ( page < static_cast(last-first+1) ){ - return ((char *) "Cannot read all the pages."); - } - - // swap the data bytes if necessary - if (b_swap) - { - int i; - size_t total = img_width * img_height * spp * (last-first+1); - if (bpp/8 == 2) - { - for (i=0;i -#include -#include "TiledMCVolume.h" -#include "imBlock.h" -#include "RawFmtMngr.h" - -#ifdef _WIN32 -#include "dirent_win.h" -#else -#include -#endif -//#include -//#include -//#include -#include -#include -#include "ProgressBar.h" - -using namespace std; -using namespace iim; - -// 2015-04-15. Alessandro. @ADDED definition for default constructor. -TiledMCVolume::TiledMCVolume(void) : VirtualVolume() -{ - /**/iim::debug(iim::LEV3, 0, __iim__current__function__); - - N_ROWS = N_COLS = 0; - reference_system.first = reference_system.second = reference_system.third = iim::axis_invalid; - VXL_1 = VXL_2 = VXL_3 = 0.0f; - CHDIRNAMES = 0; - vol_ch = 0; -} - -TiledMCVolume::TiledMCVolume(const char* _root_dir) throw (IOException) -: VirtualVolume(_root_dir) // iannello ADDED -{ - /**/iim::debug(iim::LEV3, strprintf("_root_dir=%s", _root_dir).c_str(), __iim__current__function__); - - //DIM_V = DIM_H = DIM_D = 0; - VXL_1 = VXL_2 = VXL_3 = 0; - N_ROWS = N_COLS = 0; - reference_system.first = reference_system.second = reference_system.third = axis_invalid; - vol_ch = (TiledVolume **)0; - active = (uint32 *)0; - n_active = 0; - - - //without any configuration parameter, volume import must be done from the metadata file stored in the root directory, if it exists - char mdata_filepath[STATIC_STRINGS_SIZE]; - sprintf(mdata_filepath, "%s/%s", root_dir, MC_MDATA_BIN_FILE_NAME.c_str()); - if(iim::isFile(mdata_filepath)) - { - load(mdata_filepath); - initChannels(); - } - else - { - char errMsg[STATIC_STRINGS_SIZE]; - sprintf(errMsg, "in TiledMCVolume::TiledMCVolume(...): unable to find metadata file at %s", mdata_filepath); - throw IOException(errMsg); - } -} - -TiledMCVolume::TiledMCVolume(const char* _root_dir, ref_sys _reference_system, float _VXL_1, float _VXL_2, float _VXL_3, bool overwrite_mdata, bool save_mdata) throw (IOException) -: VirtualVolume(_root_dir) // iannello ADDED -{ - /**/iim::debug(iim::LEV3, strprintf("_root_dir=%s, ref_sys reference_system={%d,%d,%d}, VXL_1=%.4f, VXL_2=%.4f, VXL_3=%.4f", - _root_dir, _reference_system.first, _reference_system.second, _reference_system.third, _VXL_1, _VXL_2, _VXL_3).c_str(), __iim__current__function__); - - //DIM_V = DIM_H = DIM_D = 0; - VXL_1 = VXL_2 = VXL_3 = 0; - N_ROWS = N_COLS = 0; - reference_system.first = reference_system.second = reference_system.third = axis_invalid; - vol_ch = (TiledVolume **)0; - active = (uint32 *)0; - n_active = 0; - - //trying to unserialize an already existing metadata file, if it doesn't exist the full initialization procedure is performed and metadata is saved - char mdata_filepath[STATIC_STRINGS_SIZE]; - sprintf(mdata_filepath, "%s/%s", root_dir, MC_MDATA_BIN_FILE_NAME.c_str()); - if(iim::isFile(mdata_filepath) && !overwrite_mdata) - { - load(mdata_filepath); - } - else - { - if(_reference_system.first == axis_invalid || _reference_system.second == axis_invalid || - _reference_system.third == axis_invalid || _VXL_1 == 0 || _VXL_2 == 0 || _VXL_3 == 0) - throw IOException("in TiledMCVolume::TiledMCVolume(...): invalid importing parameters"); - - reference_system.first = _reference_system.first; - reference_system.second = _reference_system.second; - reference_system.third = _reference_system.third; - VXL_1 = _VXL_1; - VXL_2 = _VXL_2; - VXL_3 = _VXL_3; - init(); - if(save_mdata) - save(mdata_filepath); - } - initChannels(); -} - -TiledMCVolume::~TiledMCVolume(void) -{ - /**/iim::debug(iim::LEV3, 0, __iim__current__function__); - - if ( CHDIRNAMES ) - delete[] CHDIRNAMES; - if ( vol_ch ) { - for ( int c=0; c(iim::MDATA_BIN_FILE_VERSION); - fwrite(&mdata_version, sizeof(float), 1, file); // --- Alessandro 2012-12-31: added field for metadata file version - fwrite(&reference_system.first, sizeof(axis), 1, file); - fwrite(&reference_system.second, sizeof(axis), 1, file); // iannello CORRECTED - fwrite(&reference_system.third, sizeof(axis), 1, file); // iannello CORRECTED - fwrite(&VXL_1, sizeof(float), 1, file); - fwrite(&VXL_2, sizeof(float), 1, file); - fwrite(&VXL_3, sizeof(float), 1, file); - fwrite(&VXL_V, sizeof(float), 1, file); - fwrite(&VXL_H, sizeof(float), 1, file); - fwrite(&VXL_D, sizeof(float), 1, file); - fwrite(&ORG_V, sizeof(float), 1, file); - fwrite(&ORG_H, sizeof(float), 1, file); - fwrite(&ORG_D, sizeof(float), 1, file); - fwrite(&DIM_V, sizeof(uint32), 1, file); - fwrite(&DIM_H, sizeof(uint32), 1, file); - fwrite(&DIM_D, sizeof(uint32), 1, file); - fwrite(&N_ROWS, sizeof(uint16), 1, file); - fwrite(&N_COLS, sizeof(uint16), 1, file); - - fwrite(&DIM_C, sizeof(int), 1, file); - - // save channel directories names - int n_digits = 1; - int _channels = DIM_C / 10; - while ( _channels ) { - n_digits++; - _channels /= 10; - } - for ( int c=0; c(iim::MDATA_BIN_FILE_VERSION); - fread_return_val = fread(&mdata_version_read, sizeof(float), 1, file); - if(fread_return_val != 1 || mdata_version_read != mdata_version) - { - // --- Alessandro 2013-01-06: instead of throwing an exception, it is better to mantain compatibility -// char errMsg[STATIC_STRINGS_SIZE]; -// sprintf(errMsg, "in TiledMCVolume::unBinarizeFrom(...): metadata file version (%.2f) is different from the supported one (%.2f). " -// "Please re-import the current volume.", mdata_version_read, mdata_version); -// throw iim::IOException(errMsg); - - fclose(file); - file = fopen(metadata_filepath, "rb"); - uint16 str_size; - fread_return_val = fread(&str_size, sizeof(uint16), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in TiledMCVolume::unBinarizeFrom(...): error while reading binary metadata file"); - } - char stored_root_dir[STATIC_STRINGS_SIZE]; - fread_return_val = fread(stored_root_dir, str_size, 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in TiledMCVolume::unBinarizeFrom(...): error while reading binary metadata file"); - } - } - - fread_return_val = fread(&reference_system.first, sizeof(axis), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in TiledMCVolume::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&reference_system.second, sizeof(axis), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in TiledMCVolume::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&reference_system.third, sizeof(axis), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in TiledMCVolume::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&VXL_1, sizeof(float), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in TiledMCVolume::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&VXL_2, sizeof(float), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in TiledMCVolume::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&VXL_3, sizeof(float), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in TiledMCVolume::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&VXL_V, sizeof(float), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in TiledMCVolume::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&VXL_H, sizeof(float), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in TiledMCVolume::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&VXL_D, sizeof(float), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in TiledMCVolume::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&ORG_V, sizeof(float), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in TiledMCVolume::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&ORG_H, sizeof(float), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in TiledMCVolume::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&ORG_D, sizeof(float), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in TiledMCVolume::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&DIM_V, sizeof(uint32), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in TiledMCVolume::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&DIM_H, sizeof(uint32), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in TiledMCVolume::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&DIM_D, sizeof(uint32), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in TiledMCVolume::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&N_ROWS, sizeof(uint16), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in TiledMCVolume::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&N_COLS, sizeof(uint16), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in TiledMCVolume::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&DIM_C, sizeof(int), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in TiledMCVolume::unBinarizeFrom(...): error while reading binary metadata file"); - } - - n_active = DIM_C; - active = new uint32[n_active]; - for ( int c=0; c entries_lev1; //list of entries of first level of hierarchy - list::iterator entry_i; //iterator for list 'entries_lev1' - //char channel_c_path[STATIC_STRINGS_SIZE]; - - //obtaining DIR pointer to root_dir (=NULL if directory doesn't exist) - if (!(cur_dir_lev1=opendir(root_dir))) - { - char msg[STATIC_STRINGS_SIZE]; - sprintf(msg,"in TiledMCVolume::init(...): Unable to open directory \"%s\"", root_dir); - throw IOException(msg); - } - - //scanning first level of hierarchy which entries need to be ordered alphabetically. This is done using STL. - while ((entry_lev1=readdir(cur_dir_lev1))) - { - tmp=entry_lev1->d_name; - if(tmp.find(".") == string::npos && tmp.find(" ") == string::npos) - entries_lev1.push_front(entry_lev1->d_name); - } - closedir(cur_dir_lev1); - entries_lev1.sort(); - DIM_C = (uint16) entries_lev1.size(); - n_active = DIM_C; - active = new uint32[n_active]; - for ( c=0; cgetN_ROWS(); - else if (vol_ch[c]->getN_ROWS() != N_ROWS) - throw IOException("in TiledMCVolume::init(...): Number of tiles is not the same for all channels!"); - - if (N_COLS == 0) - N_COLS = vol_ch[c]->getN_COLS(); - else if (vol_ch[c]->getN_COLS() != N_COLS) - throw IOException("in TiledMCVolume::init(...): Number of tiles is not the same for all channels!"); - } - - CHDIRNAMES = new char*[DIM_C]; - for(c=0; c VHD - if (abs(reference_system.first)==2 && abs(reference_system.second)==1 && reference_system.third==3) - { - this->rotate(90); - this->mirror(axis(2)); - - if(reference_system.first == -2) - this->mirror(axis(2)); - if(reference_system.second == -1) - this->mirror(axis(1)); - - //int computed_ORG_1, computed_ORG_2, computed_ORG_3; - //extractCoordinates(BLOCKS[0][0], 0, &computed_ORG_1, &computed_ORG_2, &computed_ORG_3); - - ORG_V = vol_ch[0]->getORG_V(); // WARNING: also in this case coordinates have to be the same of channel volumes - ORG_H = vol_ch[0]->getORG_H(); - ORG_D = vol_ch[0]->getORG_D(); - VXL_V = VXL_2 ; - VXL_H = VXL_1 ; - VXL_D = VXL_3 ; - } - //VHD --> VHD - else if (abs(reference_system.first)==1 && abs(reference_system.second)==2 && reference_system.third==3) - { - if(reference_system.first == -1) - this->mirror(axis(1)); - if(reference_system.second == -2) - this->mirror(axis(2)); - - //int computed_ORG_1, computed_ORG_2, computed_ORG_3; - //extractCoordinates(BLOCKS[0][0], 0, &computed_ORG_1, &computed_ORG_2, &computed_ORG_3); - - ORG_V = vol_ch[0]->getORG_V(); - ORG_H = vol_ch[0]->getORG_H(); - ORG_D = vol_ch[0]->getORG_D(); - VXL_V = VXL_1; - VXL_H = VXL_2; - VXL_D = VXL_3; - } - //unsupported reference system - else - { - char msg[STATIC_STRINGS_SIZE]; - sprintf(msg, "in TiledMCVolume::init(...): the reference system {%d,%d,%d} is not supported.", - reference_system.first, reference_system.second, reference_system.third); - throw IOException(msg); - } - - // WARNINIG: following code should not be executed - //some little adjustments of the origin - //if(VXL_V < 0) - // ORG_V -= (BLOCKS[0][0]->getHEIGHT()-1)* VXL_V/1000.0f; - - //if(VXL_H < 0) - // ORG_H -= (BLOCKS[0][0]->getWIDTH() -1)* VXL_H/1000.0f; - - /******************** 3) COMPUTING VOLUME DIMENSIONS ******************** - *************************************************************************/ - - DIM_V = vol_ch[0]->getDIM_V(); - DIM_H = vol_ch[0]->getDIM_H(); - DIM_D = vol_ch[0]->getDIM_D(); - - //for(int row=0; row < N_ROWS; row++) { - // for(int col=0; col < N_COLS; col++) - // { - // if(row==0) - // DIM_H+=BLOCKS[row][col]->getWIDTH(); - // if(col==0) - // DIM_V+=BLOCKS[row][col]->getHEIGHT(); - // DIM_D = BLOCKS[row][col]->getDEPTH() > DIM_D ? BLOCKS[row][col]->getDEPTH() : DIM_D; - // } - //} - - /**************** 4) COMPUTING STACKS ABSOLUTE POSITIONS **************** - *************************************************************************/ - //for(int row=0; row < N_ROWS; row++) { - // for(int col=0; col < N_COLS; col++) - // { - // if(row) - // BLOCKS[row][col]->setABS_V(BLOCKS[row-1][col]->getABS_V()+BLOCKS[row-1][col]->getHEIGHT()); - // else - // BLOCKS[row][col]->setABS_V(0); - - // if(col) - // BLOCKS[row][col]->setABS_H(BLOCKS[row][col-1]->getABS_H()+BLOCKS[row][col-1]->getWIDTH()); - // else - // BLOCKS[row][col]->setABS_H(0); - // } - //} -} - -void TiledMCVolume::initChannels ( ) throw (IOException) -{ - /**/iim::debug(iim::LEV3, 0, __iim__current__function__); - - BYTESxCHAN = vol_ch[0]->getBYTESxCHAN(); -} - -//PRINT method -void TiledMCVolume::print( bool print_stacks ) -{ - printf("*** Begin printing TiledMCVolume object...\n\n"); - printf("\tDirectory:\t%s\n", root_dir); - printf("\tDimensions:\t\t%d(V) x %d(H) x %d(D)\n", DIM_V, DIM_H, DIM_D); - printf("\tVoxels:\t\t\t%.4f(V) x %.4f(H) x %.4f(D)\n", VXL_V, VXL_H, VXL_D); - printf("\tOrigin:\t\t\t%.4f(V) x %.4f(H) x %.4f(D)\n", ORG_V, ORG_H, ORG_D); - printf("\tChannels:\t\t%d\n", DIM_C); - printf("\tBytes per channel:\t%d\n", BYTESxCHAN); - printf("\tReference system:\tref1=%d, ref2=%d, ref3=%d\n",reference_system.first,reference_system.second,reference_system.third); - printf("\tChannels:\n"); - for ( int c=0; cprint(print_stacks); - } - printf("\n*** END printing TiledMCVolume object...\n\n"); -} - -//rotate stacks matrix around D axis (accepted values are theta=0,90,180,270) -void TiledMCVolume::rotate(int theta) -{ - /**/iim::debug(iim::LEV3, strprintf("theta=%d", theta).c_str(), __iim__current__function__); - - char msg[STATIC_STRINGS_SIZE]; - sprintf(msg,"in TiledMCVolume::rotate: not implemented yet"); - throw IOException(msg); - -// //PRECONDITIONS: -// // 1) current TiledMCVolume object has been initialized (init() method has been called) -// // 2) accepted values for 'theta' are 0,90,180,270 -// -// //POSTCONDITIONS: -// // 1) a new 2D-array of Stack* objects is created considering a rotation of 'theta' angle of current TiledMCVolume object -// -// Stack*** new_STACK_2D_ARRAY = NULL; -// int new_N_ROWS = 0, new_N_COLS = 0; -// - switch(theta) - { - case(0): break; - - case(90): -// { -// new_N_COLS = N_ROWS; -// new_N_ROWS = N_COLS; -// -// //allocating new_STACK_2D_ARRAY -// new_STACK_2D_ARRAY = new Stack**[new_N_ROWS]; -// for(int i=0; isetROW_INDEX(i); -// new_STACK_2D_ARRAY[i][j]->setCOL_INDEX(j); -// } - break; -// } - case(180): -// { -// new_N_COLS=N_COLS; -// new_N_ROWS=N_ROWS; -// -// //allocating new_STACK_2D_ARRAY -// new_STACK_2D_ARRAY = new Stack**[new_N_ROWS]; -// for(int i=0; isetROW_INDEX(i); -// new_STACK_2D_ARRAY[i][j]->setCOL_INDEX(j); -// } - break; -// } - case(270): -// { -// new_N_COLS=N_ROWS; -// new_N_ROWS=N_COLS; -// -// //allocating new_STACK_2D_ARRAY -// new_STACK_2D_ARRAY = new Stack**[new_N_ROWS]; -// for(int i=0; isetROW_INDEX(i); -// new_STACK_2D_ARRAY[i][j]->setCOL_INDEX(j); -// } - break; -// } - } -// -// -// //deallocating current STACK_2DARRAY object -// for(int row=0; rowsetROW_INDEX(i); -// new_STACK_2D_ARRAY[i][j]->setCOL_INDEX(j); -// } - break; -// } - case(2): -// { -// //allocating new_STACK_2D_ARRAY -// new_STACK_2D_ARRAY = new Stack**[N_ROWS]; -// for(int i=0; isetROW_INDEX(i); -// new_STACK_2D_ARRAY[i][j]->setCOL_INDEX(j); -// } - break; -// } - default: break; - } -// -// //deallocating current STACK_2DARRAY object -// for(int row=0; row *involved_blocks, bool release_blocks) throw (IOException) -{ - /**/iim::debug(iim::LEV3, strprintf("V0=%d, V1=%d, H0=%d, H1=%d, D0=%d, D1=%d, %s", V0, V1, H0, H1, D0, D1, (involved_blocks? ", involved_stacks" : "")).c_str(), __iim__current__function__); - - char msg[STATIC_STRINGS_SIZE]; - sprintf(msg,"in TiledMCVolume::loadSubvolume: not completed yet"); - throw IOException(msg); - - //initializations - V0 = (V0 == -1 ? 0 : V0); - V1 = (V1 == -1 ? DIM_V : V1); - H0 = (H0 == -1 ? 0 : H0); - H1 = (H1 == -1 ? DIM_H : H1); - D0 = (D0 == -1 ? 0 : D0); - D1 = (D1 == -1 ? DIM_D : D1); - - //allocation - sint64 sbv_height = V1 - V0; - sint64 sbv_width = H1 - H0; - sint64 sbv_depth = D1 - D0; - real32 *subvol = new real32[sbv_height * sbv_width * sbv_depth]; - - //scanning of stacks matrix for data loading and storing into subvol - Rect_t subvol_area; - subvol_area.H0 = H0; - subvol_area.V0 = V0; - subvol_area.H1 = H1; - subvol_area.V1 = V1; - - return subvol; -} - -//loads given subvolume in a 1-D array of uint8 while releasing stacks slices memory when they are no longer needed -//---03 nov 2011: added color support -uint8* TiledMCVolume::loadSubvolume_to_UINT8(int V0,int V1, int H0, int H1, int D0, int D1, int *channels, int ret_type) throw (IOException) -{ - /**/iim::debug(iim::LEV3, strprintf("V0=%d, V1=%d, H0=%d, H1=%d, D0=%d, D1=%d, *channels=%d, ret_type=%d", V0, V1, H0, H1, D0, D1, channels ? *channels : -1, ret_type).c_str(), __iim__current__function__); - - //checking for non implemented features - //if( this->BYTESxCHAN != 1 ) { - // char err_msg[STATIC_STRINGS_SIZE]; - // sprintf(err_msg,"TiledMCVolume::loadSubvolume_to_UINT8: invalid number of bytes per channel (%d)",this->BYTESxCHAN); - // throw iim::IOException(err_msg); - //} - - //if ( (ret_type == iim::DEF_IMG_DEPTH) && ((8 * this->BYTESxCHAN) != iim::DEF_IMG_DEPTH) ) { - // does not support depth conversion: - // return type is 8 bits, but native depth is not 8 bits - if ( (ret_type != iim::NATIVE_RTYPE) && (ret_type != iim::DEF_IMG_DEPTH) ) { - // return type should be converted, but not to 8 bits per channel - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"RawVolume::loadSubvolume_to_UINT8: non supported return type (%d bits) - native type is %d bits",ret_type, 8*this->BYTESxCHAN); - throw IOException(err_msg); - } - - //char *err_rawfmt; - - //initializations - V0 = V0 < 0 ? 0 : V0; - H0 = H0 < 0 ? 0 : H0; - D0 = D0 < 0 ? 0 : D0; - V1 = (V1 < 0 || V1 > (int)DIM_V) ? DIM_V : V1; // iannello MODIFIED - H1 = (H1 < 0 || H1 > (int)DIM_H) ? DIM_H : H1; // iannello MODIFIED - D1 = (D1 < 0 || D1 > (int)DIM_D) ? DIM_D : D1; // iannello MODIFIED - - //checking that the interval is valid - if(V1-V0 <=0 || H1-H0 <= 0 || D1-D0 <= 0) - throw IOException("in TiledMCVolume::loadSubvolume_to_UINT8: invalid subvolume intervals"); - - //computing dimensions - sint64 sbv_height = V1 - V0; - sint64 sbv_width = H1 - H0; - sint64 sbv_depth = D1 - D0; - - sint64 sbv_ch_dim = sbv_height * sbv_width * sbv_depth; - - int dummy_ch; - uint8 *subvol = new uint8[n_active*sbv_ch_dim]; - uint8 *subvol_ch; - - for ( int c=0; cloadSubvolume_to_UINT8(V0,V1,H0,H1,D0,D1,&dummy_ch,ret_type); - memcpy(subvol + c*sbv_ch_dim, subvol_ch, sbv_ch_dim*sizeof(uint8)); - delete[] subvol_ch; - } - - //returning outputs - if(channels) - *channels = (int)n_active; - - return subvol; -} - -// moved to VirtualVolume.cpp by Alessandro on 2014-02-20 -//void TiledMCVolume::setActiveChannels ( uint32 *_active, int _n_active ) -//{ -// /**/iim::debug(iim::LEV3, 0, __iim__current__function__); - -// if ( active ) -// delete[] active; -// active = _active; -// n_active = _n_active; -//} - - -// OPERATIONS FOR STREAMED SUBVOLUME LOAD - -struct stream_MC_descr_t { - sint64 sbv_ch_dim; - void **descr_list; -}; - -void *TiledMCVolume::streamedLoadSubvolume_open ( int steps, uint8 *buf, int V0,int V1, int H0, int H1, int D0, int D1 ) -{ - /**/iim::debug(iim::LEV3, strprintf("steps=%d, V0=%d, V1=%d, H0=%d, H1=%d, D0=%d, D1=%d", steps, V0, V1, H0, H1, D0, D1).c_str(), __iim__current__function__); - - //checking for non implemented features - if( this->BYTESxCHAN != 1 ) { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"TiledMCVolume::streamedLoadSubvolume_open: invalid number of bytes per channel (%d)",this->BYTESxCHAN); - throw IOException(err_msg); - } - - //checks - if ( V0>=V1 || H0>=H1 || D0>=D1 || V0<0 || H0<0 || D0<0 || V1>(int)DIM_V || H1>(int)DIM_H || D1>(int)DIM_D ) { - char msg[1000]; - sprintf(msg,"in TiledMCVolume::streamedLoadSubvolume_open: invalid sub-block vertices"); - throw IOException(msg); - } - - sint64 sbv_height = V1 - V0; - sint64 sbv_width = H1 - H0; - sint64 sbv_depth = D1 - D0; - - stream_MC_descr_t *stream_descr = new stream_MC_descr_t; - stream_descr->sbv_ch_dim = sbv_height * sbv_width * sbv_depth; - stream_descr->descr_list = new void *[n_active]; - - for ( int c=0; cdescr_list[c] = - vol_ch[active[c]]->streamedLoadSubvolume_open(steps,(buf + c*(stream_descr->sbv_ch_dim)),V0,V1,H0,H1,D0,D1); - } - - return stream_descr; -} - -uint8 *TiledMCVolume::streamedLoadSubvolume_dostep ( void *stream_descr, unsigned char *buffer2 ) -{ - /**/iim::debug(iim::LEV3, 0, __iim__current__function__); - - uint8 *dummy; - uint8 *buf = vol_ch[active[0]]->streamedLoadSubvolume_dostep( - ((stream_MC_descr_t *)stream_descr)->descr_list[0], - buffer2 - ); - for ( int c=1; cstreamedLoadSubvolume_dostep( - ((stream_MC_descr_t *)stream_descr)->descr_list[c], - (buffer2) ? (buffer2 + c*(((stream_MC_descr_t *)stream_descr)->sbv_ch_dim)) : 0 - ); - } - - return buf; -} - -void TiledMCVolume::streamedLoadSubvolume_cpydata ( void *stream_descr, unsigned char *buffer, unsigned char *buffer2 ) -{ - /**/iim::debug(iim::LEV3, 0, __iim__current__function__); - - for ( int c=0; cstreamedLoadSubvolume_cpydata( - ((stream_MC_descr_t *)stream_descr)->descr_list[c], - (buffer + c*(((stream_MC_descr_t *)stream_descr)->sbv_ch_dim)), - (buffer2) ? (buffer2 + c*(((stream_MC_descr_t *)stream_descr)->sbv_ch_dim)) : 0 - ); - } -} - -uint8 *TiledMCVolume::streamedLoadSubvolume_close ( void *stream_descr, bool return_buffer ) -{ - /**/iim::debug(iim::LEV3, 0, __iim__current__function__); - - uint8 *dummy; - uint8 *temp = vol_ch[0]->streamedLoadSubvolume_close(((stream_MC_descr_t *)stream_descr)->descr_list[0],true); - - for ( int c=1; cstreamedLoadSubvolume_close(((stream_MC_descr_t *)stream_descr)->descr_list[c],true); - } - - delete[] ((stream_MC_descr_t *)stream_descr)->descr_list; - delete ((stream_MC_descr_t *)stream_descr); - - if ( return_buffer ) - return temp; - else { - delete[] temp; - return 0; - } -} diff --git a/v3d_main/terafly/src/core/imagemanager/TiledMCVolume.h b/v3d_main/terafly/src/core/imagemanager/TiledMCVolume.h deleted file mode 100644 index 7d232ba4f5..0000000000 --- a/v3d_main/terafly/src/core/imagemanager/TiledMCVolume.h +++ /dev/null @@ -1,158 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -2015-04-06. Giulio. @CHANGED Modified prunt method: printing stacks information is now off by default -*/ - -#ifndef _TILED_MC_VOLUME_H -#define _TILED_MC_VOLUME_H - -#include "VirtualVolume.h" -#include "TiledVolume.h" -#include -#include - -//every object of this class has the default (1,2,3) reference system -class TiledMCVolume : public iim::VirtualVolume -{ - private: - //******OBJECT ATTRIBUTES****** - iim::uint16 N_ROWS, N_COLS; //dimensions (in stacks) of stacks matrix along VH axes - //Block ***BLOCKS; //2-D array of - iim::ref_sys reference_system; //reference system of the stored volume - float VXL_1, VXL_2, VXL_3; //voxel dimensions of the stored volume - - char **CHDIRNAMES; //1-D dinamic array of pointers to channels directory names - TiledVolume **vol_ch; -// iim::uint32 *active; // @MOVED to "VirtualVolume" by Alessandro on 2014-02-20 -// int n_active; // @MOVED to "VirtualVolume" by Alessandro on 2014-02-20 - - //***OBJECT PRIVATE METHODS**** - TiledMCVolume(void); - - //Given the reference system, initializes all object's members using stack's directories hierarchy - void init() throw (iim::IOException); - - //rotate stacks matrix around D axis (accepted values are theta=0,90,180,270) - void rotate(int theta); - - //mirror stacks matrix along mrr_axis (accepted values are mrr_axis=1,2,3) - void mirror(iim::axis mrr_axis); - - // iannello returns the number of channels of images composing the volume - void initChannels ( ) throw (iim::IOException); - - public: - //CONSTRUCTORS-DECONSTRUCTOR - TiledMCVolume(const char* _root_dir) throw (iim::IOException); - TiledMCVolume(const char* _root_dir, iim::ref_sys _reference_system, - float _VXL_1, float _VXL_2, float _VXL_3, - bool overwrite_mdata = false, bool save_mdata=true) throw (iim::IOException); - - ~TiledMCVolume(void); - - //GET methods - iim::uint16 getN_ROWS(){return N_ROWS;} - iim::uint16 getN_COLS(){return N_COLS;} - float getVXL_1(){return VXL_1;} - float getVXL_2(){return VXL_2;} - float getVXL_3(){return VXL_3;} - iim::axis getAXS_1(){return reference_system.first;} - iim::axis getAXS_2(){return reference_system.second;} - iim::axis getAXS_3(){return reference_system.third;} - TiledVolume** getVolumes(){return vol_ch;} - - // returns a unique ID that identifies the volume format - std::string getPrintableFormat(){return iim::TILED_MC_FORMAT;} - - - //PRINT method - void print( bool print_stacks = false ); - - //saving-loading methods to/from metadata binary file - void save(char* metadata_filepath) throw (iim::IOException); - void load(char* metadata_filepath) throw (iim::IOException); - - //loads given subvolume in a 1-D array of iim::real32 while releasing stacks slices memory when they are no longer needed - inline iim::real32 *loadSubvolume_to_real32(int V0=-1,int V1=-1, int H0=-1, int H1=-1, int D0=-1, int D1=-1) throw (iim::IOException) { - return loadSubvolume(V0,V1,H0,H1,D0,D1,0,true); - } - - //loads given subvolume in a 1-D array and puts used Stacks into 'involved_stacks' iff not null - iim::real32 *loadSubvolume(int V0=-1,int V1=-1, int H0=-1, int H1=-1, int D0=-1, int D1=-1, - std::list *involved_blocks = 0, bool release_blocks = false) throw (iim::IOException); - - //loads given subvolume in a 1-D array of iim::uint8 while releasing stacks slices memory when they are no longer needed - iim::uint8 *loadSubvolume_to_UINT8(int V0=-1,int V1=-1, int H0=-1, int H1=-1, int D0=-1, int D1=-1, - int *channels=0, int ret_type=iim::DEF_IMG_DEPTH) throw (iim::IOException); - - // moved to VirtualVolume.h by Alessandro on 2014-02-20 -// //sets active channels -// void setActiveChannels ( iim::uint32 *_active, int _n_active ); - - - // OPERATIONS FOR STREAMED SUBVOLUME LOAD - - /* start a streamed load operation: returns an opaque descriptor of the streamed operation - * buf is a dynamically allocated, initialized buffer that should not be neither manipulated - * nor deallocated by the caller until the operation terminates - * (see close operations for details) - */ - void *streamedLoadSubvolume_open ( int steps, iim::uint8 *buf, int V0=-1,int V1=-1, int H0=-1, int H1=-1, int D0=-1, int D1=-1 ); - - /* perform one step of a streamed operation: returns a pointer to a read-only buffer - * with updated data; the returned buffer should not be deallocated; - * the optional parameter buffer2 is an initialized buffer of the same dimensions of - * the returned buffer with reference data to be used to check that the updated positions - * of the returned buffer contain exactly the same data contained in buffer2 at those positions - * no check is performed if the default value of buffer2 (null pointer) is passed - */ - iim::uint8 *streamedLoadSubvolume_dostep ( void *stream_descr, unsigned char *buffer2=0 ); - - /* copies the last data read from files to a user provided buffer - * positions to which data are copied are depend on which data have been read in - * the last step - * the user provided buffer can be freely accessed by the caller after the operation is terminated; - * the optional parameter buffer2 is an initialized buffer of the same dimensions of - * the user provided buffer with reference data to be used to check that the updated positions - * of the user provided buffer contain exactly the same data contained in buffer2 at those positions - * no check is performed if the default value of buffer2 (null pointer) is passed - */ - void streamedLoadSubvolume_cpydata ( void *stream_descr, unsigned char *buffer, unsigned char *buffer2=0 ); - - /* close a streamed load operation: by default return the initial buffer that can be - * freely used and must be deallocated by the caller - * if return_buffer is set to false, the initial buffer is deallocated, it cannot be - * reused by the caller and the operation returns a null pointer - */ - iim::uint8 *streamedLoadSubvolume_close ( void *stream_descr, bool return_buffer=true ); - - friend class iim::VirtualVolume; - -}; - -#endif //_TILED_MC_VOLUME_H diff --git a/v3d_main/terafly/src/core/imagemanager/TiledVolume.cpp b/v3d_main/terafly/src/core/imagemanager/TiledVolume.cpp deleted file mode 100644 index dcb5c7d560..0000000000 --- a/v3d_main/terafly/src/core/imagemanager/TiledVolume.cpp +++ /dev/null @@ -1,1369 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -* 2015-04-15. Alessandro. @FIXED bad/missing exception handling in loadSubvolume_to_UINT8. -* 2015-04-15. Alessandro. @ADDED definition for default constructor. -* 2015-04-06. Giulio. @CHANGED Modified prunt method: printing stacks information is now off by default -* 2015-03-03. Giulio. @ADDED check that ioplugin interleaves channels in loadSubvolume_to_UINT8. -* 2015-03-03. Giulio. @ADDED selection of IO plugin in the constructors if not provided. -* 2015-02-27. Alessandro. @ADDED automated selection of IO plugin if not provided. -* 2014-11-22 Giulio. @CHANGED code using OpenCV has been commente. It can be found searching comments containing 'Giulio_CV' -*/ - -#include -#include -#include "TiledVolume.h" -#include "imBlock.h" -#include "VirtualFmtMngr.h" -#include "Tiff3DMngr.h" -#include "RawFmtMngr.h" -#include "iomanager.config.h" - -#ifdef _WIN32 -#include "dirent_win.h" -#else -#include -#endif - -// Giulio_CV #include -// Giulio_CV #include -// Giulio_CV #include - -#include -#include -#include "ProgressBar.h" - -#include "IOPluginAPI.h" // 2015-03-03. Giulio. - -using namespace std; -using namespace iim; - -// 2015-04-15. Alessandro. @ADDED definition for default constructor. -TiledVolume::TiledVolume(void) : VirtualVolume() -{ - /**/iim::debug(iim::LEV3, 0, __iim__current__function__); - - N_ROWS = N_COLS = 0; - BLOCKS = 0; - reference_system.first = reference_system.second = reference_system.third = iim::axis_invalid; - VXL_1 = VXL_2 = VXL_3 = 0.0f; - fmtMngr = 0; -} - -TiledVolume::TiledVolume(const char* _root_dir) throw (IOException) -: VirtualVolume(_root_dir) // iannello ADDED -{ - /**/iim::debug(iim::LEV3, strprintf("_root_dir=%s", _root_dir).c_str(), __iim__current__function__); - - // 2015-03-03. Giulio. @ADDED selection of IO plugin if not provided. - iom::IMIN_PLUGIN = "tiff3D"; - - //DIM_V = DIM_H = DIM_D = 0; - VXL_1 = VXL_2 = VXL_3 = 0; - N_ROWS = N_COLS = 0; - BLOCKS = NULL; - reference_system.first = reference_system.second = reference_system.third = axis_invalid; - - ffmt = ""; - fmtMngr = 0; - - //without any configuration parameter, volume import must be done from the metadata file stored in the root directory, if it exists - char mdata_filepath[STATIC_STRINGS_SIZE]; - sprintf(mdata_filepath, "%s/%s", root_dir, iim::MDATA_BIN_FILE_NAME.c_str()); - if(iim::isFile(mdata_filepath)) - { - load(mdata_filepath); - initChannels(); - } - else - { - char errMsg[STATIC_STRINGS_SIZE]; - sprintf(errMsg, "in TiledVolume::TiledVolume(...): unable to find metadata file at %s", mdata_filepath); - throw IOException(errMsg); - } -} - -TiledVolume::TiledVolume(const char* _root_dir, ref_sys _reference_system, float _VXL_1, float _VXL_2, float _VXL_3, bool overwrite_mdata, bool save_mdata) throw (IOException) -: VirtualVolume(_root_dir) // iannello ADDED -{ - /**/iim::debug(iim::LEV3, strprintf("_root_dir=%s, ref_sys reference_system={%d,%d,%d}, VXL_1=%.4f, VXL_2=%.4f, VXL_3=%.4f", - _root_dir, _reference_system.first, _reference_system.second, _reference_system.third, _VXL_1, _VXL_2, _VXL_3).c_str(), __iim__current__function__); - - // 2015-03-03. Giulio. @ADDED selection of IO plugin if not provided. - iom::IMIN_PLUGIN = "tiff3D"; - - //DIM_V = DIM_H = DIM_D = 0; - VXL_1 = VXL_2 = VXL_3 = 0; - N_ROWS = N_COLS = 0; - BLOCKS = NULL; - reference_system.first = reference_system.second = reference_system.third = axis_invalid; - - ffmt = ""; - fmtMngr = 0; - - //trying to unserialize an already existing metadata file, if it doesn't exist the full initialization procedure is performed and metadata is saved - char mdata_filepath[STATIC_STRINGS_SIZE]; - sprintf(mdata_filepath, "%s/%s", root_dir, iim::MDATA_BIN_FILE_NAME.c_str()); - if(iim::isFile(mdata_filepath) && !overwrite_mdata) - load(mdata_filepath); - else - { - if(_reference_system.first == axis_invalid || _reference_system.second == axis_invalid || - _reference_system.third == axis_invalid || _VXL_1 == 0 || _VXL_2 == 0 || _VXL_3 == 0) - throw IOException("in TiledVolume::TiledVolume(...): invalid importing parameters"); - - reference_system.first = _reference_system.first; - reference_system.second = _reference_system.second; - reference_system.third = _reference_system.third; - VXL_1 = _VXL_1; - VXL_2 = _VXL_2; - VXL_3 = _VXL_3; - init(); - if(save_mdata) - save(mdata_filepath); - } - initChannels(); -} - -TiledVolume::~TiledVolume(void) -{ - /**/iim::debug(iim::LEV3, 0, __iim__current__function__); - - // iannello if(root_dir) - // iannello delete[] root_dir; - - if(BLOCKS) - { - for(int row=0; rowgetHEIGHT();} -int TiledVolume::getStacksWidth(){return BLOCKS[0][0]->getWIDTH();} - -void TiledVolume::save(char* metadata_filepath) throw (IOException) -{ - /**/iim::debug(iim::LEV3, strprintf("metadata_filepath=%s", metadata_filepath).c_str(), __iim__current__function__); - - //LOCAL VARIABLES - FILE *file; - int i,j; - - file = fopen(metadata_filepath, "wb"); - - // --- Alessandro 2013-04-23: added exception when file can't be opened in write mode - if(!file) - { - char errMsg[STATIC_STRINGS_SIZE]; - sprintf(errMsg, "in TiledVolume::save(): cannot write metadata binary file at \"%s\".\n\nPlease check write permissions on this storage.", metadata_filepath); - throw IOException(errMsg); - } - - float mdata_version = static_cast(iim::MDATA_BIN_FILE_VERSION); - fwrite(&mdata_version, sizeof(float), 1, file); // --- Alessandro 2012-12-31: added field for metadata file version - fwrite(&reference_system.first, sizeof(axis), 1, file); - fwrite(&reference_system.second, sizeof(axis), 1, file); // iannello CORRECTED - fwrite(&reference_system.third, sizeof(axis), 1, file); // iannello CORRECTED - fwrite(&VXL_1, sizeof(float), 1, file); - fwrite(&VXL_2, sizeof(float), 1, file); - fwrite(&VXL_3, sizeof(float), 1, file); - fwrite(&VXL_V, sizeof(float), 1, file); - fwrite(&VXL_H, sizeof(float), 1, file); - fwrite(&VXL_D, sizeof(float), 1, file); - fwrite(&ORG_V, sizeof(float), 1, file); - fwrite(&ORG_H, sizeof(float), 1, file); - fwrite(&ORG_D, sizeof(float), 1, file); - fwrite(&DIM_V, sizeof(iim::uint32), 1, file); - fwrite(&DIM_H, sizeof(iim::uint32), 1, file); - fwrite(&DIM_D, sizeof(iim::uint32), 1, file); - fwrite(&N_ROWS, sizeof(iim::uint16), 1, file); - fwrite(&N_COLS, sizeof(iim::uint16), 1, file); - - for(i = 0; i < N_ROWS; i++) - for(j = 0; j < N_COLS; j++) - BLOCKS[i][j]->binarizeInto(file); - - fclose(file); -} - -void TiledVolume::load(char* metadata_filepath) throw (IOException) -{ - /**/iim::debug(iim::LEV3, strprintf("metadata_filepath=%s", metadata_filepath).c_str(), __iim__current__function__); - - //LOCAL VARIABLES - FILE *file; - int i,j; - size_t fread_return_val; - - file = fopen(metadata_filepath, "rb"); - - // --- Alessandro 2013-04-23: added exception when file can't be opened in read mode - if(!file) - { - char errMsg[STATIC_STRINGS_SIZE]; - sprintf(errMsg, "in TiledVolume::load(): cannot read metadata binary file at \"%s\".\n\nPlease check read permissions on this storage.", metadata_filepath); - throw IOException(errMsg); - } - - // --- Alessandro 2012-12-31: added field for metadata file version - float mdata_version_read = 0; - float mdata_version = static_cast(iim::MDATA_BIN_FILE_VERSION); - fread_return_val = fread(&mdata_version_read, sizeof(float), 1, file); - if(fread_return_val != 1 || mdata_version_read != mdata_version) - { - // --- Alessandro 2013-01-06: instead of throwing an exception, it is better to mantain compatibility -// char errMsg[STATIC_STRINGS_SIZE]; -// sprintf(errMsg, "in Block::unBinarizeFrom(...): metadata file version (%.2f) is different from the supported one (%.2f). " -// "Please re-import the current volume.", mdata_version_read, mdata_version); -// throw iim::IOException(errMsg); - - fclose(file); - file = fopen(metadata_filepath, "rb"); - iim::uint16 str_size; - fread_return_val = fread(&str_size, sizeof(iim::uint16), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in Block::unBinarizeFrom(...): error while reading binary metadata file"); - } - char stored_root_dir[STATIC_STRINGS_SIZE]; - fread_return_val = fread(stored_root_dir, str_size, 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in Block::unBinarizeFrom(...): error while reading binary metadata file"); - } - } - - fread_return_val = fread(&reference_system.first, sizeof(axis), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in Block::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&reference_system.second, sizeof(axis), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in Block::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&reference_system.third, sizeof(axis), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in Block::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&VXL_1, sizeof(float), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in Block::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&VXL_2, sizeof(float), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in Block::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&VXL_3, sizeof(float), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in Block::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&VXL_V, sizeof(float), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in Block::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&VXL_H, sizeof(float), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in Block::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&VXL_D, sizeof(float), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in Block::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&ORG_V, sizeof(float), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in Block::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&ORG_H, sizeof(float), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in Block::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&ORG_D, sizeof(float), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in Block::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&DIM_V, sizeof(iim::uint32), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in Block::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&DIM_H, sizeof(iim::uint32), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in Block::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&DIM_D, sizeof(iim::uint32), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in Block::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&N_ROWS, sizeof(iim::uint16), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in Block::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&N_COLS, sizeof(iim::uint16), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw IOException("in Block::unBinarizeFrom(...): error while reading binary metadata file"); - } - - - BLOCKS = new Block **[N_ROWS]; - for(i = 0; i < N_ROWS; i++) - { - BLOCKS[i] = new Block *[N_COLS]; - for(j = 0; j < N_COLS; j++) - BLOCKS[i][j] = new Block(this, i, j, file); - } - - // get the file format of the blocks - ffmt = BLOCKS[0][0]->getFMT(); - if ( ffmt == "Tiff3D" ) - { - // 2015-02-27. Alessandro. @ADDED automated selection of IO plugin if not provided. - if(iom::IMIN_PLUGIN.compare("empty") == 0) - iom::IMIN_PLUGIN = "tiff3D"; - fmtMngr = new Tiff3DFmtMngr(); - } - else if ( ffmt == "Vaa3DRaw" ) - { - fmtMngr = new Vaa3DRawFmtMngr(); - } - else { - char msg[STATIC_STRINGS_SIZE]; - sprintf(msg,"in TiledVolume::unBinarizeFrom(...): Unknown file format \"%s\"", ffmt.c_str()); - throw IOException(msg); - } - - fclose(file); -} - -void TiledVolume::init() throw (IOException) -{ - /**/iim::debug(iim::LEV3, 0, __iim__current__function__); - - /************************* 1) LOADING STRUCTURE ************************* - *************************************************************************/ - - //LOCAL VARIABLES - string tmp_path; //string that contains temp paths during computation - string tmp; //string that contains temp data during computation - DIR *cur_dir_lev1; //pointer to DIR, the data structure that represents a DIRECTORY (level 1 of hierarchical structure) - DIR *cur_dir_lev2; //pointer to DIR, the data structure that represents a DIRECTORY (level 2 of hierarchical structure) - dirent *entry_lev1; //pointer to DIRENT, the data structure that represents a DIRECTORY ENTRY inside a directory (level 1) - dirent *entry_lev2; //pointer to DIRENT, the data structure that represents a DIRECTORY ENTRY inside a directory (level 2) - int i=0,j=0; //for counting of N_ROWS, N_COLS - list blocks_list; //each stack found in the hierarchy is pushed into this list - list entries_lev1; //list of entries of first level of hierarchy - list::iterator entry_i; //iterator for list 'entries_lev1' - list entries_lev2; //list of entries of second level of hierarchy - list::iterator entry_j; //iterator for list 'entries_lev2' - char block_i_j_path[STATIC_STRINGS_SIZE]; - - //obtaining DIR pointer to root_dir (=NULL if directory doesn't exist) - if (!(cur_dir_lev1=opendir(root_dir))) - { - char msg[STATIC_STRINGS_SIZE]; - sprintf(msg,"in TiledVolume::init(...): Unable to open directory \"%s\"", root_dir); - throw IOException(msg); - } - - //scanning first level of hierarchy which entries need to be ordered alphabetically. This is done using STL. - while ((entry_lev1=readdir(cur_dir_lev1))) - { - tmp=entry_lev1->d_name; - if(tmp.find(".") == string::npos && tmp.find(" ") == string::npos) - entries_lev1.push_front(entry_lev1->d_name); - } - closedir(cur_dir_lev1); - entries_lev1.sort(); - N_ROWS = (iim::uint16) entries_lev1.size(); - N_COLS = 0; - - //for each entry of first level, scanning second level - for(entry_i = entries_lev1.begin(), i=0; entry_i!= entries_lev1.end(); entry_i++, i++) - { - //building absolute path of first level entry to be used for "opendir(...)" - tmp_path=root_dir; - tmp_path.append("/"); - tmp_path.append(*entry_i); - cur_dir_lev2 = opendir(tmp_path.c_str()); - if (!cur_dir_lev2) - throw IOException("in TiledVolume::init(...): A problem occurred during scanning of subdirectories"); - - //scanning second level of hierarchy which entries need to be ordered alphabetically. This is done using STL. - while ((entry_lev2=readdir(cur_dir_lev2))) - { - tmp=entry_lev2->d_name; - if(tmp.find(".") == string::npos && tmp.find(" ") == string::npos) - entries_lev2.push_back(entry_lev2->d_name); - } - closedir(cur_dir_lev2); - entries_lev2.sort(); - - //for each entry of the second level, allocating a new Block - for(entry_j = entries_lev2.begin(), j=0; entry_j!= entries_lev2.end(); entry_j++, j++) - { - //allocating new stack - sprintf(block_i_j_path,"%s/%s",(*entry_i).c_str(), (*entry_j).c_str()); - Block *new_stk = new Block(this,i,j,block_i_j_path); - blocks_list.push_back(new_stk); - } - entries_lev2.clear(); - if (N_COLS == 0) - N_COLS = j; - else if (j != N_COLS) - throw IOException("in TiledVolume::init(...): Number of second-level directories is not the same for all first-level directories!"); - } - entries_lev1.clear(); - - //intermediate check - if(N_ROWS == 0 || N_COLS == 0) - throw IOException("in TiledVolume::init(...): Unable to find stacks in the given directory"); - - //converting stacks_list (STL list of Block*) into BLOCKS (2-D array of Block*) - BLOCKS = new Block**[N_ROWS]; - for(int row=0; row < N_ROWS; row++) - BLOCKS[row] = new Block*[N_COLS]; - for(list::iterator i = blocks_list.begin(); i != blocks_list.end(); i++) - BLOCKS[(*i)->getROW_INDEX()][(*i)->getCOL_INDEX()] = (*i); - - // get the file format of the blocks - ffmt = BLOCKS[0][0]->getFMT(); - if ( ffmt == "Tiff3D" ) - { - // 2015-02-27. Alessandro. @ADDED automated selection of IO plugin if not provided. - if(iom::IMIN_PLUGIN.compare("empty") == 0) - iom::IMIN_PLUGIN = "tiff3D"; - fmtMngr = new Tiff3DFmtMngr(); - } - else if ( ffmt == "Vaa3DRaw" ) - fmtMngr = new Vaa3DRawFmtMngr(); - else { - char msg[STATIC_STRINGS_SIZE]; - sprintf(msg,"in TiledVolume::init(...): Unknown file format \"%s\"", ffmt.c_str()); - throw IOException(msg); - } - - - /******************* 2) SETTING THE REFERENCE SYSTEM ******************** - The entire application uses a vertical-horizontal reference system, so - it is necessary to fit the original reference system into the new one. - *************************************************************************/ - - //adjusting possible sign mismatch betwwen reference system and VXL - //in these cases VXL is adjusted to match with reference system - if(sgn(reference_system.first) != sgn(VXL_1)) - VXL_1*=-1.0f; - if(sgn(reference_system.second) != sgn(VXL_2)) - VXL_2*=-1.0f; - if(sgn(reference_system.third) != sgn(VXL_3)) - VXL_3*=-1.0f; - - //HVD --> VHD - if (abs(reference_system.first)==2 && abs(reference_system.second)==1 && reference_system.third==3) - { - this->rotate(90); - this->mirror(axis(2)); - - if(reference_system.first == -2) - this->mirror(axis(2)); - if(reference_system.second == -1) - this->mirror(axis(1)); - - int computed_ORG_1, computed_ORG_2, computed_ORG_3; - extractCoordinates(BLOCKS[0][0], 0, &computed_ORG_1, &computed_ORG_2, &computed_ORG_3); - ORG_V = computed_ORG_2/10000.0F; - ORG_H = computed_ORG_1/10000.0F; - ORG_D = computed_ORG_3/10000.0F; - VXL_V = VXL_2 ; - VXL_H = VXL_1 ; - VXL_D = VXL_3 ; - } - //VHD --> VHD - else if (abs(reference_system.first)==1 && abs(reference_system.second)==2 && reference_system.third==3) - { - if(reference_system.first == -1) - this->mirror(axis(1)); - if(reference_system.second == -2) - this->mirror(axis(2)); - - int computed_ORG_1, computed_ORG_2, computed_ORG_3; - extractCoordinates(BLOCKS[0][0], 0, &computed_ORG_1, &computed_ORG_2, &computed_ORG_3); - ORG_V = computed_ORG_1/10000.0F; - ORG_H = computed_ORG_2/10000.0F; - ORG_D = computed_ORG_3/10000.0F; - VXL_V = VXL_1; - VXL_H = VXL_2; - VXL_D = VXL_3; - } - //unsupported reference system - else - { - char msg[STATIC_STRINGS_SIZE]; - sprintf(msg, "in TiledVolume::init(...): the reference system {%d,%d,%d} is not supported.", - reference_system.first, reference_system.second, reference_system.third); - throw IOException(msg); - } - - // GI_140628: this adjustment should not be performed by the converter since it operates on volumes already adjusted - //some little adjustments of the origin - //if(VXL_V < 0) - // ORG_V -= (BLOCKS[0][0]->getHEIGHT()-1)* VXL_V/1000.0f; - - //if(VXL_H < 0) - // ORG_H -= (BLOCKS[0][0]->getWIDTH() -1)* VXL_H/1000.0f; - - /******************** 3) COMPUTING VOLUME DIMENSIONS ******************** - *************************************************************************/ - for(int row=0; row < N_ROWS; row++) { - for(int col=0; col < N_COLS; col++) - { - if(row==0) - DIM_H+=BLOCKS[row][col]->getWIDTH(); - if(col==0) - DIM_V+=BLOCKS[row][col]->getHEIGHT(); - DIM_D = BLOCKS[row][col]->getDEPTH() > DIM_D ? BLOCKS[row][col]->getDEPTH() : DIM_D; - } - } - - /**************** 4) COMPUTING STACKS ABSOLUTE POSITIONS **************** - *************************************************************************/ - for(int row=0; row < N_ROWS; row++) { - for(int col=0; col < N_COLS; col++) - { - if(row) - BLOCKS[row][col]->setABS_V(BLOCKS[row-1][col]->getABS_V()+BLOCKS[row-1][col]->getHEIGHT()); - else - BLOCKS[row][col]->setABS_V(0); - - if(col) - BLOCKS[row][col]->setABS_H(BLOCKS[row][col-1]->getABS_H()+BLOCKS[row][col-1]->getWIDTH()); - else - BLOCKS[row][col]->setABS_H(0); - } - } -} - -void TiledVolume::initChannels ( ) throw (IOException) -{ - /**/iim::debug(iim::LEV3, 0, __iim__current__function__); - - DIM_C = BLOCKS[0][0]->getN_CHANS(); - BYTESxCHAN = (int)BLOCKS[0][0]->getN_BYTESxCHAN(); - - n_active = DIM_C; - active = new iim::uint32[n_active]; - for ( int c=0; cprint(); - } - printf("\n*** END printing TiledVolume object...\n\n"); -} - -//rotate stacks matrix around D axis (accepted values are theta=0,90,180,270) -void TiledVolume::rotate(int theta) -{ - /**/iim::debug(iim::LEV3, strprintf("theta=%d", theta).c_str(), __iim__current__function__); - - //PRECONDITIONS: - // 1) current TiledVolume object has been initialized (init() method has been called) - // 2) accepted values for 'theta' are 0,90,180,270 - - //POSTCONDITIONS: - // 1) a new 2D-array of Block* objects is created considering a rotation of 'theta' angle of current TiledVolume object - - Block*** new_Block_2D_ARRAY = NULL; - int new_N_ROWS = 0, new_N_COLS = 0; - - switch(theta) - { - case(0): break; - - case(90): - { - new_N_COLS = N_ROWS; - new_N_ROWS = N_COLS; - - //allocating new_Block_2D_ARRAY - new_Block_2D_ARRAY = new Block**[new_N_ROWS]; - for(int i=0; isetROW_INDEX(i); - new_Block_2D_ARRAY[i][j]->setCOL_INDEX(j); - } - break; - } - case(180): - { - new_N_COLS=N_COLS; - new_N_ROWS=N_ROWS; - - //allocating new_Block_2D_ARRAY - new_Block_2D_ARRAY = new Block**[new_N_ROWS]; - for(int i=0; isetROW_INDEX(i); - new_Block_2D_ARRAY[i][j]->setCOL_INDEX(j); - } - break; - } - case(270): - { - new_N_COLS=N_ROWS; - new_N_ROWS=N_COLS; - - //allocating new_Block_2D_ARRAY - new_Block_2D_ARRAY = new Block**[new_N_ROWS]; - for(int i=0; isetROW_INDEX(i); - new_Block_2D_ARRAY[i][j]->setCOL_INDEX(j); - } - break; - } - } - - - //deallocating current Block_2DARRAY object - for(int row=0; rowsetROW_INDEX(i); - new_BLOCK_2D_ARRAY[i][j]->setCOL_INDEX(j); - } - break; - } - case(2): - { - //allocating new_STACK_2D_ARRAY - new_BLOCK_2D_ARRAY = new Block**[N_ROWS]; - for(int i=0; isetROW_INDEX(i); - new_BLOCK_2D_ARRAY[i][j]->setCOL_INDEX(j); - } - break; - } - default: break; - } - - //deallocating current STACK_2DARRAY object - for(int row=0; rowgetDIR_NAME()[0])); - pch = strtok (buffer,"/_"); - pch = strtok (NULL, "/_"); - - while (pch != NULL) - { - if(!found_ABS_X) - { - if(sscanf(pch, "%d", crd_1) == 1) - found_ABS_X=true; - } - else if(!found_ABS_Y) - { - if(sscanf(pch, "%d", crd_2) == 1) - found_ABS_Y=true; - } - else - break; - - pch = strtok (NULL, "/_"); - } - - if(!found_ABS_X || !found_ABS_Y) - { - char msg[200]; - sprintf(msg,"in TiledVolume::extractCoordinates(directory_name=\"%s\"): format 000000_000000 or X_000000_X_000000 not found", blk->getDIR_NAME()); - throw msg; - } - - //loading estimation for absolute Z stack position - if(crd_3!= NULL) - { - char* first_file_name = blk->getFILENAMES()[z]; - - char * pch; - char lastTokenized[100]; - char buffer[500]; - strcpy(buffer,&(first_file_name[0])); - - pch = strtok (buffer,"_"); - while (pch != NULL) - { - strcpy(lastTokenized,pch); - pch = strtok (NULL, "_"); - } - - pch = strtok (lastTokenized,"."); - strcpy(lastTokenized,pch); - - if(sscanf(lastTokenized, "%d", crd_3) != 1) - { - char msg[200]; - sprintf(msg,"in TiledVolume::extractCoordinates(...): unable to extract Z position from filename %s", first_file_name); - throw msg; - } - } -} - -//loads given subvolume in a 1-D array of float -real32* TiledVolume::loadSubvolume(int V0,int V1, int H0, int H1, int D0, int D1, list *involved_blocks, bool release_blocks) throw (IOException) -{ - /**/iim::debug(iim::LEV3, strprintf("V0=%d, V1=%d, H0=%d, H1=%d, D0=%d, D1=%d, %s", V0, V1, H0, H1, D0, D1, (involved_blocks? ", involved_stacks" : "")).c_str(), __iim__current__function__); - - // char msg[STATIC_STRINGS_SIZE]; - //sprintf(msg,"in TiledVolume::loadSubvolume: not completed yet"); - // throw IOException(msg); - - int channels; - float scale_factor; - - //initializations - V0 = V0 < 0 ? 0 : V0; - H0 = H0 < 0 ? 0 : H0; - D0 = D0 < 0 ? 0 : D0; - V1 = (V1 < 0 || V1 > (int)DIM_V) ? DIM_V : V1; // iannello MODIFIED - H1 = (H1 < 0 || H1 > (int)DIM_H) ? DIM_H : H1; // iannello MODIFIED - D1 = (D1 < 0 || D1 > (int)DIM_D) ? DIM_D : D1; // iannello MODIFIED - - iim::uint8 *data = loadSubvolume_to_UINT8(V0,V1,H0,H1,D0,D1,&channels,BYTESxCHAN*8); - - //conversion from unsigned char to iom::real_t - - if (DIM_C == 2 || DIM_C > 3) // only monocromatic or RGB images are supported - { - char errMsg[2000]; - sprintf(errMsg, "in TiledVolume::loadSubvolume(...): %d channels are not supported.", DIM_C); - throw IOException(errMsg); - } - - if ( BYTESxCHAN == 1) - scale_factor = 255.0F; - else if (BYTESxCHAN == 2) - scale_factor = 65535.0F; - else - { - char errMsg[2000]; - sprintf(errMsg, "in TiledVolume::loadSubvolume(...): Too many bytes per channel (%d).", BYTESxCHAN); - throw IOException(errMsg); - } - - real32 *subvol = new real32[(V1-V0) * (H1-H0) * (D1-D0)]; // this image is an intensity image (only one channel) - - int offset; - - if ( DIM_C == 1 ) { - for(int i = 0; i < ((V1-V0) * (H1-H0) * (D1-D0)); i++) - subvol[i] = (real32) data[i]/scale_factor; - } - else { // conversion to an intensity image - if ( iim::CHANNEL_SELECTION == iim::ALL ) { - char errMsg[2000]; - sprintf(errMsg, "in TiledVolume::loadSubvolume(...): conversion from multi-channel to intensity images not supported."); - throw IOException(errMsg); - } - else if ( iim::CHANNEL_SELECTION == iim::R ) { - offset = 0; - } - else if ( iim::CHANNEL_SELECTION == iim::G ) { - offset = 1; - } - else if ( iim::CHANNEL_SELECTION == iim::B ) { - offset = 2; - } - else { - char errMsg[2000]; - sprintf(errMsg, "in TiledVolume::loadSubvolume(...): wrong value for parameter iom::CHANNEL_SELECTION."); - throw IOException(errMsg); - } - for(int i = 0; i < ((V1-V0) * (H1-H0) * (D1-D0)); i++) - subvol[i] = (real32) data[3*i + offset]/scale_factor; - } - - delete [] data; - - - return subvol; -} - -//loads given subvolume in a 1-D array of iim::uint8 while releasing stacks slices memory when they are no longer needed -//---03 nov 2011: added color support -iim::uint8* TiledVolume::loadSubvolume_to_UINT8(int V0,int V1, int H0, int H1, int D0, int D1, int *channels, int ret_type ) throw (IOException) -{ - /**/iim::debug(iim::LEV3, strprintf("V0=%d, V1=%d, H0=%d, H1=%d, D0=%d, D1=%d, *channels=%d, ret_type=%d", V0, V1, H0, H1, D0, D1, channels ? *channels : -1, ret_type).c_str(), __iim__current__function__); - - //checking for non implemented features - //if( this->BYTESxCHAN != 1 ) { - // char err_msg[STATIC_STRINGS_SIZE]; - // sprintf(err_msg,"TiledVolume::loadSubvolume_to_UINT8: invalid number of bytes per channel (%d)",this->BYTESxCHAN); - // throw iim::IOException(err_msg); - //} - - //if ( (ret_type == iim::DEF_IMG_DEPTH) && ((8 * this->BYTESxCHAN) != iim::DEF_IMG_DEPTH) ) { - // does not support depth conversion: - // return type is 8 bits, but native depth is not 8 bits - if ( (ret_type != iim::NATIVE_RTYPE) && (ret_type != iim::DEF_IMG_DEPTH) ) { - // return type should be converted, but not to 8 bits per channel - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"RawVolume::loadSubvolume_to_UINT8: non supported return type (%d bits) - native type is %d bits",ret_type, 8*this->BYTESxCHAN); - throw IOException(err_msg); - } - - // reduction factor to be applied to the loaded buffer - int red_factor = (ret_type == iim::NATIVE_RTYPE) ? 1 : ((8 * this->BYTESxCHAN) / ret_type); - - char *err_rawfmt; - - //initializations - V0 = V0 < 0 ? 0 : V0; - H0 = H0 < 0 ? 0 : H0; - D0 = D0 < 0 ? 0 : D0; - V1 = (V1 < 0 || V1 > (int)DIM_V) ? DIM_V : V1; // iannello MODIFIED - H1 = (H1 < 0 || H1 > (int)DIM_H) ? DIM_H : H1; // iannello MODIFIED - D1 = (D1 < 0 || D1 > (int)DIM_D) ? DIM_D : D1; // iannello MODIFIED - iim::uint8 *subvol = 0; - - //checking that the interval is valid - if(V1-V0 <=0 || H1-H0 <= 0 || D1-D0 <= 0) - throw IOException("in TiledVolume::loadSubvolume_to_UINT8: invalid subvolume intervals"); - - //computing dimensions - iim::sint64 sbv_height = V1 - V0; - iim::sint64 sbv_width = H1 - H0; - iim::sint64 sbv_depth = D1 - D0; - - //initializing the number of channels with an undefined value (it will be detected from the first slice read) - iim::sint64 sbv_channels = -1; - iim::sint64 sbv_bytes_chan = -1; - - //scanning of stacks matrix for data loading and storing into subvol - Rect_t subvol_area; - subvol_area.H0 = H0; - subvol_area.V0 = V0; - subvol_area.H1 = H1; - subvol_area.V1 = V1; - - char slice_fullpath[STATIC_STRINGS_SIZE]; - bool first_time = true; - - Segm_t *intersect_segm = BLOCKS[0][0]->Intersects(D0,D1); - - if (intersect_segm) // there is intersection - { - for(int row=0; rowIntersects(subvol_area); - if(intersect_area) // there is intersection - { - //printf("\t\t\t\tin TiledVolume::loadSubvolume_to_UINT8(): using STACK[%d,%d] for area %d-%d(V) x %d-%d(H)\n", row, col, intersect_area->V0-V0, intersect_area->V1-V0, intersect_area->H0-H0, intersect_area->H1-H0); - - for(int k=intersect_segm->ind0; k<=intersect_segm->ind1; k++) - { - //if this is the first time a block is loaded: safely allocating memory for data - if(first_time) - { - first_time = false; - sbv_channels = this->DIM_C; - sbv_bytes_chan = this->BYTESxCHAN; - - // 2015-04-15. Alessandro. @FIXED bad/missing exception handling in loadSubvolume_to_UINT8. - try - { - if ( sbv_channels >1 && !(iom::IOPluginFactory::getPlugin3D(iom::IMIN_PLUGIN)->isChansInterleaved()) ) { - throw iim::IOException("the plugin do not store channels in interleaved mode: more than one channel not supported yet."); - } - } - catch(iom::exception &ex) - { - throw iim::IOException(ex.what()); - } - - try - { - subvol = new iim::uint8[sbv_height * sbv_width * sbv_depth * sbv_channels * sbv_bytes_chan]; - //if ( !subvol ) - // throw iim::IOException("in TiledVolume::loadSubvolume_to_UINT8: unable to allocate memory"); - } - catch(...){throw IOException("in TiledVolume::loadSubvolume_to_UINT8: unable to allocate memory");} - } - //loading region - sprintf(slice_fullpath, "%s/%s/%s", root_dir, BLOCKS[row][col]->getDIR_NAME(), BLOCKS[row][col]->getFILENAMES()[k]); - - /* rationale (for V dimension, the same for H) - * - * V0, ABS_V are the first indices, V1 is the last index + 1 - * - * case V0intersect_V1 - * - * indices (V0 - ABS_V) SIZE - * | | - * ABS_V | ABS_V+SIZE - * source (file) |----------| - * |------| - * buffer |------|---| - * V0 | V1 - * | | - * intesect_V0 intersect_V1 - * | | - * indices 0 (intersect_V1 - V0) - */ - - // vertices of file block - int sV0 = (V0V0) ? 0 : (V0 - BLOCKS[row][col]->getABS_V()); - int sV1 = (V1>intersect_area->V1) ? BLOCKS[row][col]->getHEIGHT() : (V1 - BLOCKS[row][col]->getABS_V()); - int sH0 = (H0H0) ? 0 : (H0 - BLOCKS[row][col]->getABS_H()); - int sH1 = (H1>intersect_area->H1) ? BLOCKS[row][col]->getWIDTH() : (H1 - BLOCKS[row][col]->getABS_H()); - int sD0 = (D0getBLOCK_ABS_D()[k]) ? 0 : (D0 - BLOCKS[row][col]->getBLOCK_ABS_D()[k]); - int sD1 = (D1>(int)(BLOCKS[row][col]->getBLOCK_ABS_D()[k]+BLOCKS[row][col]->getBLOCK_SIZE()[k])) ? (int)BLOCKS[row][col]->getBLOCK_SIZE()[k] : (int)(D1 - BLOCKS[row][col]->getBLOCK_ABS_D()[k]); - - // vertices of buffer block - int bV0 = (V0>intersect_area->V0) ? 0 : (int)(intersect_area->V0 - V0); - //int bV1 = (V1V1) ? (int)sbv_height : (intersect_area->V1 - V0); // unused - int bH0 = (H0>intersect_area->H0) ? 0 : (intersect_area->H0 - H0); - //int bH1 = (H1H1) ? (int)sbv_width : (int)(intersect_area->H1 - H0); // unused - int bD0 = (D0>BLOCKS[row][col]->getBLOCK_ABS_D()[k]) ? 0 : (BLOCKS[row][col]->getBLOCK_ABS_D()[k] - D0); - //int bD1 = (D1<(int)(BLOCKS[row][col]->getBLOCK_ABS_D()[k]+BLOCKS[row][col]->getBLOCK_SIZE()[k])) ? (int)sbv_depth : (BLOCKS[row][col]->getBLOCK_ABS_D()[k]+BLOCKS[row][col]->getBLOCK_SIZE()[k] - D0); // unused - - if ( (err_rawfmt = fmtMngr->copyFileBlock2Buffer( - slice_fullpath, - sV0,sV1,sH0,sH1,sD0,sD1, - (unsigned char *)subvol, - (int)sbv_bytes_chan, // this is native rtype, it has substituted sizeof(iim::uint8) - bH0+bV0*sbv_width+bD0*sbv_width*sbv_height, - sbv_width, - sbv_width*sbv_height, - sbv_width*sbv_height*sbv_depth) ) != 0 ) - { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg, - "TiledVolume::loadSubvolume_to_UINT8: error in extracting a block from file %s (%s)", - BLOCKS[row][col]->getFILENAMES()[k], err_rawfmt); - throw IOException(err_msg); - } - } - delete intersect_area; - } - } - } - delete intersect_segm; - } - else - throw IOException("in TiledVolume::loadSubvolume_to_UINT8: depth interval out of range"); - - //returning outputs - if(channels) - *channels = (int)sbv_channels; - - if ( red_factor > 1 ) { // the buffer has to be reduced - - if ( (err_rawfmt = convert2depth8bits(red_factor,(sbv_height*sbv_width*sbv_depth),sbv_channels,subvol)) != 0 ) { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"TiledVolume::loadSubvolume_to_UINT8: %s", err_rawfmt); - throw IOException(err_msg); - } - - //int c, i, j, p; - //iim::sint64 totalUnits = sbv_height * sbv_width * sbv_depth * sbv_channels; - //iim::sint64 totalBlockSize = sbv_height * sbv_width * sbv_depth; - - //char endianCodeMachine = checkMachineEndian(); - //if ( endianCodeMachine == 'L' ) { - // j = red_factor - 1; // MSB is the last - //} - //else if ( endianCodeMachine == 'B' ) { - // j = 0; // MSB is the first - //} - //else { - // char err_msg[STATIC_STRINGS_SIZE]; - // sprintf(err_msg,"TiledVolume::loadSubvolume_to_UINT8: unknown machine endianess (%c)", endianCodeMachine); - // throw iim::IOException(err_msg); - //} - - //// look for maximum values in each channel and rescale each channel separately - //unsigned short maxVal; - //unsigned short *temp = (unsigned short *) subvol; - //iim::sint64 count; - //for ( c=0; c maxVal ) - // maxVal = temp[i]; - // for ( i=1, p=8*red_factor; i (0.9*maxVal) ) - // // count++; - // temp[i] <<= p; - // } - // printf("\t\t\t\tin TiledVolume::loadSubvolume_to_UINT8: c=%d, maxVal=%d, p=%d, count=%ld\n\n",c,maxVal,p,count); - //} - // - //iim::uint8 *temp_buf = new iim::uint8[totalUnits]; - //memset(temp_buf,0,totalUnits); - //for ( i=0; ireleaseStack(first_file,last_file); -} - - - -// OPERATIONS FOR STREAMED SUBVOLUME LOAD - -void *TiledVolume::streamedLoadSubvolume_open ( int steps, iim::uint8 *buf, int V0,int V1, int H0, int H1, int D0, int D1 ) -{ - /**/iim::debug(iim::LEV3, strprintf("steps=%d, V0=%d, V1=%d, H0=%d, H1=%d, D0=%d, D1=%d", steps, V0, V1, H0, H1, D0, D1).c_str(), __iim__current__function__); - - //checking for non implemented features - if( this->BYTESxCHAN != 1 ) { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"TiledVolume::streamedLoadSubvolume_open: invalid number of bytes per channel (%d)",this->BYTESxCHAN); - throw IOException(err_msg); - } - - //checks - if ( V0>=V1 || H0>=H1 || D0>=D1 || V0<0 || H0<0 || D0<0 || V1>(int)DIM_V || H1>(int)DIM_H || D1>(int)DIM_D ) { - char msg[1000]; - sprintf(msg,"in TiledVolume::streamedLoadSubvolume_open: invalid sub-block vertices"); - throw IOException(msg); - } - - char *err_rawfmt; - - iim::sint64 stridex = H1 - H0; - iim::sint64 stridexy = stridex * (V1 - V0); - iim::sint64 stridexyz = stridexy * (D1 - D0); - Streamer_Descr_t *stream_descr = new Streamer_Descr_t(buf,sizeof(unsigned char),stridex,stridexy,stridexyz,this->DIM_C,steps); - if ( !stream_descr ) { - char msg[1000]; - sprintf(msg,"in TiledVolume::streamedLoadSubvolume_open: Unable to allocate stream descriptor"); - throw IOException(msg); - } - - // iim::sint64 sbv_channels = this->CHANS; // unused - - //scanning of stacks matrix for data loading and storing into subvol - Rect_t subvol_area; - subvol_area.H0 = H0; - subvol_area.V0 = V0; - subvol_area.H1 = H1; - subvol_area.V1 = V1; - - char slice_fullpath[STATIC_STRINGS_SIZE]; - - Segm_t *intersect_segm = BLOCKS[0][0]->Intersects(D0,D1); - - if (intersect_segm) // there is intersection - { - for(int row=0; rowIntersects(subvol_area); - if(intersect_area) // there is intersection - { - //printf("\t\t\t\tin TiledVolume::streamedLoadSubvolume_open: using STACK[%d,%d] for area %d-%d(V) x %d-%d(H)\n", row, col, intersect_area->V0-V0, intersect_area->V1-V0, intersect_area->H0-H0, intersect_area->H1-H0); - - for(int k=intersect_segm->ind0; k<=intersect_segm->ind1; k++) - { - //loading region - sprintf(slice_fullpath, "%s/%s/%s", root_dir, BLOCKS[row][col]->getDIR_NAME(), BLOCKS[row][col]->getFILENAMES()[k]); - - // vertices of file block - int sV0 = (V0V0) ? 0 : (V0 - BLOCKS[row][col]->getABS_V()); - int sV1 = (V1>intersect_area->V1) ? BLOCKS[row][col]->getHEIGHT() : (V1 - BLOCKS[row][col]->getABS_V()); - int sH0 = (H0H0) ? 0 : (H0 - BLOCKS[row][col]->getABS_H()); - int sH1 = (H1>intersect_area->H1) ? BLOCKS[row][col]->getWIDTH() : (H1 - BLOCKS[row][col]->getABS_H()); - int sD0 = (D0getBLOCK_ABS_D()[k]) ? 0 : (D0 - BLOCKS[row][col]->getBLOCK_ABS_D()[k]); - int sD1 = (D1>(int)(BLOCKS[row][col]->getBLOCK_ABS_D()[k]+BLOCKS[row][col]->getBLOCK_SIZE()[k])) ? (int)BLOCKS[row][col]->getBLOCK_SIZE()[k] : (int)(D1 - BLOCKS[row][col]->getBLOCK_ABS_D()[k]); - - // vertices of buffer block - int bV0 = (V0>intersect_area->V0) ? 0 : (int)(intersect_area->V0 - V0); - int bH0 = (H0>intersect_area->H0) ? 0 : (intersect_area->H0 - H0); - int bD0 = (D0>BLOCKS[row][col]->getBLOCK_ABS_D()[k]) ? 0 : (BLOCKS[row][col]->getBLOCK_ABS_D()[k] - D0); - - if ( (err_rawfmt = stream_descr->addSubBlock( - slice_fullpath,bH0+bV0*stridex+bD0*stridexy,sV0,sV1,sH0,sH1,sD0,sD1)) != 0 ) - { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg, - "TiledVolume::streamedLoadSubvolume_open: error in adding the block of file %s (%s)", - BLOCKS[row][col]->getFILENAMES()[k], err_rawfmt); - throw IOException(err_msg); - } - } - delete intersect_area; - } - } - } - delete intersect_segm; - } - - if ( (err_rawfmt = streamer_open(stream_descr)) != 0 ) { - return err_rawfmt; - } - - return stream_descr; -} - -iim::uint8 *TiledVolume::streamedLoadSubvolume_dostep ( void *stream_descr, unsigned char *buffer2 ) -{ - /**/iim::debug(iim::LEV3, 0, __iim__current__function__); - - char *err_rawfmt; - - if ( (err_rawfmt = streamer_dostep((Streamer_Descr_t *)stream_descr,buffer2)) != 0 ) { - char msg[1000]; - sprintf(msg,"in TiledVolume::streamedLoadSubvolume_dostep: Unable to perform next step (%s)",err_rawfmt); - throw IOException(msg); - } - - return ((Streamer_Descr_t *)stream_descr)->buf; -} - -void TiledVolume::streamedLoadSubvolume_cpydata ( void *stream_descr, unsigned char *buffer, unsigned char *buffer2 ) -{ - /**/iim::debug(iim::LEV3, 0, __iim__current__function__); - - char *err_rawfmt; - - if ( (err_rawfmt = streamer_cpydata((Streamer_Descr_t *)stream_descr,buffer,buffer2)) != 0 ) { - char msg[1000]; - sprintf(msg,"in TiledVolume::streamedLoadSubvolume_dostep: Unable to perform next step (%s)",err_rawfmt); - throw IOException(msg); - } -} - -iim::uint8 *TiledVolume::streamedLoadSubvolume_close ( void *stream_descr, bool return_buffer ) -{ - /**/iim::debug(iim::LEV3, 0, __iim__current__function__); - - iim::uint8 *temp = ((Streamer_Descr_t *)stream_descr)->buf; - - streamer_close((Streamer_Descr_t *)stream_descr); - - delete ((Streamer_Descr_t *)stream_descr); - - if ( return_buffer ) - return temp; - else { - delete[] ((Streamer_Descr_t *)stream_descr)->buf; - return 0; - } -} diff --git a/v3d_main/terafly/src/core/imagemanager/TiledVolume.h b/v3d_main/terafly/src/core/imagemanager/TiledVolume.h deleted file mode 100644 index 2d964bfc9e..0000000000 --- a/v3d_main/terafly/src/core/imagemanager/TiledVolume.h +++ /dev/null @@ -1,166 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -2015-04-06. Giulio. @CHANGED Modified prunt method: printing stacks information is now off by default -*/ - -#ifndef _TILED_VOLUME_H -#define _TILED_VOLUME_H - -#include "VirtualVolume.h" // ADDED -#include -#include -#include "imBlock.h" - -//FORWARD-DECLARATIONS -//class Block; - -//every object of this class has the default (1,2,3) reference system -class TiledVolume : public iim::VirtualVolume -{ - private: - //******OBJECT ATTRIBUTES****** - iim::uint16 N_ROWS, N_COLS; //dimensions (in stacks) of stacks matrix along VH axes - iim::Block ***BLOCKS; //2-D array of - iim::ref_sys reference_system; //reference system of the stored volume - float VXL_1, VXL_2, VXL_3; //voxel dimensions of the stored volume - - std::string ffmt; - iim::VirtualFmtMngr *fmtMngr; - - //***OBJECT PRIVATE METHODS**** - TiledVolume(void); - - //Given the reference system, initializes all object's members using stack's directories hierarchy - void init() throw (iim::IOException); - - //rotate stacks matrix around D axis (accepted values are theta=0,90,180,270) - void rotate(int theta); - - //mirror stacks matrix along mrr_axis (accepted values are mrr_axis=1,2,3) - void mirror(iim::axis mrr_axis); - - //extract spatial coordinates (in millimeters) of given Stack object reading directory and filenames as spatial coordinates - void extractCoordinates(iim::Block* stk, int z, int* crd_1, int* crd_2, int* crd_3); - - // iannello returns the number of channels of images composing the volume - void initChannels ( ) throw (iim::IOException); - - public: - //CONSTRUCTORS-DECONSTRUCTOR - TiledVolume(const char* _root_dir) throw (iim::IOException); - TiledVolume(const char* _root_dir, iim::ref_sys _reference_system, - float _VXL_1, float _VXL_2, float _VXL_3, - bool overwrite_mdata = false, bool save_mdata=true) throw (iim::IOException); - - ~TiledVolume(void); - - //GET methods - iim::Block*** getBLOCKS(){return BLOCKS;} - iim::uint16 getN_ROWS(){return N_ROWS;} - iim::uint16 getN_COLS(){return N_COLS;} - int getStacksHeight(); - int getStacksWidth(); - float getVXL_1(){return VXL_1;} - float getVXL_2(){return VXL_2;} - float getVXL_3(){return VXL_3;} - iim::axis getAXS_1(){return reference_system.first;} - iim::axis getAXS_2(){return reference_system.second;} - iim::axis getAXS_3(){return reference_system.third;} - iim::ref_sys getREF_SYS(){return reference_system;} - - // returns a unique ID that identifies the volume format - std::string getPrintableFormat(){return iim::TILED_FORMAT;} - - std::string getFFMT(){return ffmt;} - iim::VirtualFmtMngr *getFMT_MNGR(){return fmtMngr;} - - //PRINT method - void print( bool print_stacks = false ); - - //saving-loading methods to/from metadata binary file - void save(char* metadata_filepath) throw (iim::IOException); - void load(char* metadata_filepath) throw (iim::IOException); - - //loads given subvolume in a 1-D array of iim::real32 while releasing stacks slices memory when they are no longer needed - inline iim::real32 *loadSubvolume_to_real32(int V0=-1,int V1=-1, int H0=-1, int H1=-1, int D0=-1, int D1=-1) throw (iim::IOException) { - return loadSubvolume(V0,V1,H0,H1,D0,D1,0,true); - } - - //loads given subvolume in a 1-D array and puts used Stacks into 'involved_stacks' iff not null - iim::real32 *loadSubvolume(int V0=-1,int V1=-1, int H0=-1, int H1=-1, int D0=-1, int D1=-1, - std::list *involved_blocks = 0, bool release_blocks = false) throw (iim::IOException); - - //loads given subvolume in a 1-D array of iim::uint8 while releasing stacks slices memory when they are no longer needed - iim::uint8 *loadSubvolume_to_UINT8(int V0=-1,int V1=-1, int H0=-1, int H1=-1, int D0=-1, int D1=-1, - int *channels=0, int ret_type=iim::DEF_IMG_DEPTH) throw (iim::IOException); - - //releases allocated memory of stacks - void releaseStacks(int first_file=-1, int last_file=-1); - - - // OPERATIONS FOR STREAMED SUBVOLUME LOAD - - /* start a streamed load operation: returns an opaque descriptor of the streamed operation - * buf is a dynamically allocated, initialized buffer that should not be neither manipulated - * nor deallocated by the caller until the operation terminates - * (see close operations for details) - */ - void *streamedLoadSubvolume_open ( int steps, iim::uint8 *buf, int V0=-1,int V1=-1, int H0=-1, int H1=-1, int D0=-1, int D1=-1 ); - - /* perform one step of a streamed operation: returns a pointer to a read-only buffer - * with updated data; the returned buffer should not be deallocated; - * the optional parameter buffer2 is an initialized buffer of the same dimensions of - * the returned buffer with reference data to be used to check that the updated positions - * of the returned buffer contain exactly the same data contained in buffer2 at those positions - * no check is performed if the default value of buffer2 (null pointer) is passed - */ - iim::uint8 *streamedLoadSubvolume_dostep ( void *stream_descr, unsigned char *buffer2=0 ); - - /* copies the last data read from files to a user provided buffer - * positions to which data are copied are depend on which data have been read in - * the last step - * the user provided buffer can be freely accessed by the caller after the operation is terminated; - * the optional parameter buffer2 is an initialized buffer of the same dimensions of - * the user provided buffer with reference data to be used to check that the updated positions - * of the user provided buffer contain exactly the same data contained in buffer2 at those positions - * no check is performed if the default value of buffer2 (null pointer) is passed - */ - void streamedLoadSubvolume_cpydata ( void *stream_descr, unsigned char *buffer, unsigned char *buffer2=0 ); - - /* close a streamed load operation: by default return the initial buffer that can be - * freely used and must be deallocated by the caller - * if return_buffer is set to false, the initial buffer is deallocated, it cannot be - * reused by the caller and the operation returns a null pointer - */ - iim::uint8 *streamedLoadSubvolume_close ( void *stream_descr, bool return_buffer=true ); - - friend class iim::VirtualVolume; - -}; - -#endif //_TILED_VOLUME_H diff --git a/v3d_main/terafly/src/core/imagemanager/TimeSeries.cpp b/v3d_main/terafly/src/core/imagemanager/TimeSeries.cpp deleted file mode 100644 index 84ce8404f8..0000000000 --- a/v3d_main/terafly/src/core/imagemanager/TimeSeries.cpp +++ /dev/null @@ -1,307 +0,0 @@ -#ifdef _WIN32 -#include "dirent_win.h" -#else -#include -#endif -#include -#include -#include -#include "TimeSeries.h" -#include "ProgressBar.h" - -TimeSeries::TimeSeries(const char *rootDir, std::string frames_format /* = "" */) throw (iim::IOException) : iim::VirtualVolume(rootDir) -{ - /**/iim::debug(iim::LEV2, iim::strprintf("rootDir = %s, frames_format = \"%s\"", root_dir, frames_format.c_str()).c_str(), __iim__current__function__); - - // check condition #1: valid folder - if(!iim::isDirectory(root_dir)) - throw iim::IOException(iim::strprintf("in TimeSeries::TimeSeries(): \"%s\" not a valid folder", rootDir).c_str()); - - // assume hierarchical format for the individual frames if 'format' is not provided - if(frames_format.empty() || VirtualVolume::isHierarchical(frames_format)) - { - // search for valid folders that match the format [CHANNEL_PREFIX][i] - DIR *cur_dir=0; - dirent *entry=0; - std::list entries; - if (!(cur_dir=opendir(root_dir))) - throw iim::IOException(iim::strprintf("in TimeSeries::TimeSeries(): cannot open folder \"%s\"", root_dir).c_str()); - std::string pattern = iim::TIME_FRAME_PREFIX + "%d"; - while ((entry=readdir(cur_dir))) - { - int number = 0; - if(sscanf(entry->d_name, pattern.c_str(), &number) == 1) - entries.push_front(entry->d_name); - } - closedir(cur_dir); - entries.sort(); - - // check condition #2: at least one time frame has been found - if(entries.empty()) - throw iim::IOException(iim::strprintf("in TimeSeries::TimeSeries(): no hierarchical time frames found within \"%s\"", rootDir).c_str()); - - // import each folder as a separate VirtualVolume - // WARNING: all metadata files (if needed by that format) are assumed to be present. Otherwise, that format will be skipped. - for(std::list::iterator it = entries.begin(); it != entries.end(); it++) - { - std::string path = root_dir; - path += "/"; - path += *it; - VirtualVolume* volume = 0; - try{volume = VirtualVolume::instance(path.c_str());} - catch(iim::IOException &ex){iim::warning(iim::strprintf("Cannot import tiled time frame at \"%s\": %s", path.c_str(), ex.what()).c_str(),__iim__current__function__);} - catch(...){iim::warning(iim::strprintf("Cannot import tiled time frame at \"%s\"", path.c_str()).c_str(),__iim__current__function__);} - if(!volume) - throw iim::IOException(iim::strprintf("in TimeSeries::TimeSeries(): cannot import frame \"%s\" in folder \"%s\": invalid or unsupported format", it->c_str(), root_dir).c_str()); - frames.push_back(volume); - } - } - else - { - // search for valid file formats - DIR *cur_dir=0; - dirent *entry=0; - std::list entries; - if (!(cur_dir=opendir(root_dir))) - throw iim::IOException(iim::strprintf("in TimeSeries::TimeSeries(): cannot open folder \"%s\"", root_dir).c_str()); - while ((entry=readdir(cur_dir))) - { - std::string tmp = entry->d_name; - if(tmp.compare(".") != 0 && tmp.compare("..") != 0 && tmp.find(".") != std::string::npos) - entries.push_front(entry->d_name); - } - closedir(cur_dir); - entries.sort(); - - // try to import each file separately - for(std::list::iterator it = entries.begin(); it != entries.end(); it++) - { - std::string path = root_dir; - path += "/"; - path += *it; - VirtualVolume* volume = 0; - try{volume = VirtualVolume::instance(path.c_str(), frames_format);} - catch(iim::IOException &ex){iim::warning(iim::strprintf("Cannot import filed time frame at \"%s\": %s", path.c_str(), ex.what()).c_str(),__iim__current__function__);} - catch(...){iim::warning(iim::strprintf("Cannot import filed time frame at \"%s\"", path.c_str()).c_str(),__iim__current__function__);} - if(volume) - frames.push_back(volume); - } - - // check condition #2: at least one time frame has been found - if(frames.empty()) - throw iim::IOException(iim::strprintf("in TimeSeries::TimeSeries(): no filed time frames found within \"%s\"", rootDir).c_str()); - } - - // check condition #2: all frames must have the same attributes - for(int k=0; kgetDIM_H() != frames[k+1]->getDIM_H()) - throw iim::IOException(iim::strprintf("in TimeSeries::TimeSeries(): frames have different X size in folder \"%s\"", root_dir).c_str()); - - if( frames[k]->getDIM_V() != frames[k+1]->getDIM_V()) - throw iim::IOException(iim::strprintf("in TimeSeries::TimeSeries(): frames have different Y size in folder \"%s\"", root_dir).c_str()); - - if( frames[k]->getDIM_D() != frames[k+1]->getDIM_D()) - throw iim::IOException(iim::strprintf("in TimeSeries::TimeSeries(): frames have different Z size in folder \"%s\"", root_dir).c_str()); - - if( frames[k]->getDIM_C() != frames[k+1]->getDIM_C()) - throw iim::IOException(iim::strprintf("in TimeSeries::TimeSeries(): frames have different channels in folder \"%s\"", root_dir).c_str()); - - if( frames[k]->getBYTESxCHAN() != frames[k+1]->getBYTESxCHAN()) - throw iim::IOException(iim::strprintf("in TimeSeries::TimeSeries(): frames have different bytes per channel in folder \"%s\"", root_dir).c_str()); - } - - // assigning to the attributes of time series the attributes of the first frame - VXL_V = frames[0]->getVXL_V(); - VXL_H = frames[0]->getVXL_H(); - VXL_D = frames[0]->getVXL_D(); - ORG_V = frames[0]->getORG_V(); - ORG_H = frames[0]->getORG_H(); - ORG_D = frames[0]->getORG_D(); - DIM_V = frames[0]->getDIM_V(); - DIM_H = frames[0]->getDIM_H(); - DIM_D = frames[0]->getDIM_D(); - - initChannels(); - - t0 = 0; - t1 = (int)(frames.size()-1); - DIM_T = (int)(frames.size()); -} - -TimeSeries::~TimeSeries(void) throw (iim::IOException) -{ - /**/iim::debug(iim::LEV2, 0, __iim__current__function__); -} - -// pure virtual method inherithed from abstract class -void TimeSeries::initChannels ( ) throw (iim::IOException) -{ - /**/iim::debug(iim::LEV2, 0, __iim__current__function__); - - // check precondition #1: valid time series - if(frames.empty()) - throw iim::IOException("in TimeSeries::initChannels(): empty time series"); - - // call initChannels for each frame - for(int k=0; kinitChannels(); - - // check precondition #2: all frames have the same number of channels - for(int k=0; kgetDIM_C() != frames[k+1]->getDIM_C()) - throw iim::IOException("in TimeSeries::initChannels(): frames have different number of channels"); - - // check precondition #3: all frames have the same bytes per channel - for(int k=0; kgetBYTESxCHAN() != frames[k+1]->getBYTESxCHAN()) - throw iim::IOException("in TimeSeries::initChannels(): frames have different bytes per channel"); - - DIM_C = frames[0]->getDIM_C(); - BYTESxCHAN = static_cast(frames[0]->getBYTESxCHAN()); -} - -// set active channels (@OVERRIDES VirtualVolume.h by Alessandro on 2014-02-23) -void TimeSeries::setActiveChannels ( iim::uint32 *_active, int _n_active ) -{ - /**/iim::debug(iim::LEV3, 0, __iim__current__function__); - - // check precondition #1: valid time series - if(frames.empty()) - throw iim::IOException("in TimeSeries::setActiveChannels(): empty time series"); - - for(int k=0; ksetActiveChannels(_active, _n_active); -} - -// returns only the active frames, i.e. those in the range [t0, t1] -std::vector TimeSeries::getActiveFrames() throw (iim::IOException) -{ - /**/iim::debug(iim::LEV3, 0, __iim__current__function__); - - // check precondition #1: valid time series - if(frames.empty()) - throw iim::IOException("in TimeSeries::getActiveFrames(): empty time series"); - - std::vector activeFrames; - for(int k=0; k= t0 && k <= t1) - activeFrames.push_back(frames[k]); - return activeFrames; -} - -iim::VirtualVolume* TimeSeries::getFrameAt(int t) throw (iim::IOException) -{ - /**/iim::debug(iim::LEV3, iim::strprintf("t = %d", t).c_str(), __iim__current__function__); - - // check precondition #1: valid time series - if(frames.empty()) - throw iim::IOException("in TimeSeries::getFrameAt(): empty time series"); - - // check precondition #2: valid frame selected - if(t < 0 || t >= frames.size()) - throw iim::IOException("in TimeSeries::getFrameAt(): invalid frame selected"); - - return frames[t]; -} - -// pure virtual methods inherithed from abstract class -iim::real32 * TimeSeries::loadSubvolume_to_real32(int V0,int V1, int H0, int H1, int D0, int D1) throw (iim::IOException) -{ - /**/iim::debug(iim::LEV3, iim::strprintf("V0=%d, V1=%d, H0=%d, H1=%d, D0=%d, D1=%d", V0, V1, H0, H1, D0, D1).c_str(), __iim__current__function__); - - - throw iim::IOException("Not yet implemented"); -} - -iim::uint8 * TimeSeries::loadSubvolume_to_UINT8(int V0,int V1, int H0, int H1, int D0, int D1, int *channels /*=0*/, int ret_type /*=iim::DEF_IMG_DEPTH*/) throw (iim::IOException) -{ - /**/iim::debug(iim::LEV3, iim::strprintf("V0=%d, V1=%d, H0=%d, H1=%d, D0=%d, D1=%d, *channels=%d, ret_type=%d, t0 = %d, t1 = %d", V0, V1, H0, H1, D0, D1, channels ? *channels : -1, ret_type, t0, t1).c_str(), __iim__current__function__); - - // initializations - V0 = V0 < 0 ? 0 : V0; - H0 = H0 < 0 ? 0 : H0; - D0 = D0 < 0 ? 0 : D0; - V1 = (V1 < 0 || V1 > (int)DIM_V) ? DIM_V : V1; // iannello MODIFIED - H1 = (H1 < 0 || H1 > (int)DIM_H) ? DIM_H : H1; // iannello MODIFIED - D1 = (D1 < 0 || D1 > (int)DIM_D) ? DIM_D : D1; // iannello MODIFIED - - // check for valid 3D selection - if(V1-V0 <=0 || H1-H0 <= 0 || D1-D0 <= 0) - throw iim::IOException("in TimeSeries::loadSubvolume_to_UINT8: invalid subvolume intervals"); - - // check for valid time frames selection - if(frames.empty()) - throw iim::IOException("in TimeSeries::loadSubvolume_to_UINT8(): empty time series"); - if(t0 < 0 || t0 >= frames.size()) - throw iim::IOException("in TimeSeries::loadSubvolume_to_UINT8(): invalid time frames selection"); - if(t1 < 0 || t1 >= frames.size()) - throw iim::IOException("in TimeSeries::loadSubvolume_to_UINT8(): invalid time frames selection"); - if(t1 - t0 < 0) - throw iim::IOException(iim::strprintf("in TimeSeries::loadSubvolume_to_UINT8(): invalid time frames selection: [%d, %d]", t0, t1).c_str()); - - // check for valid channel selection - for(int k=0; kgetNACtiveChannels() != frames[k+1]->getNACtiveChannels()) - throw iim::IOException("in TimeSeries::loadSubvolume_to_UINT8(): not all frames have the same active channels"); - iim::uint32* channels_k = frames[k]->getActiveChannels(); - iim::uint32* channels_k1 = frames[k+1]->getActiveChannels(); - if(!channels_k || !channels_k1) - throw iim::IOException("in TimeSeries::loadSubvolume_to_UINT8(): frames have invalid channel selections"); - for(int c=0; cgetNACtiveChannels(); c++) - if(channels_k[c] != channels_k1[c]) - throw iim::IOException("in TimeSeries::loadSubvolume_to_UINT8(): not all frames have the same active channels"); - } - - // initialize progress bar - if(t1 - t0 > 0) - { - iim::imProgressBar::getInstance()->start("5D data loading from disk", false); - iim::imProgressBar::getInstance()->update(0,"Initializing..."); - iim::imProgressBar::getInstance()->show(false); - } - - // compute subvol dimension - size_t subvol_frame_size = static_cast(H1-H0) * (V1-V0) * (D1-D0) * (frames[0]->getNACtiveChannels()); - size_t subvol_size = subvol_frame_size * (t1-t0+1); - iim::uint8* subvol_data = 0; - - /**/iim::debug(iim::LEV3, iim::strprintf("allocating memory for X(%d) x Y(%d) x Z(%d) x C(%d) x T(%d)", H1-H0, V1-V0, D1-D0, frames[0]->getNACtiveChannels(), t1-t0+1).c_str(), __iim__current__function__); - - // try to allocate memory - try{ subvol_data = new iim::uint8[subvol_size]; } - catch(...) { throw iim::IOException("in TimeSeries::loadSubvolume_to_UINT8(): failed to allocate memory for image data"); } - - // load data - for ( int t=0; t<=t1-t0; t++ ) - { - if(t1 - t0 > 0) - { - iim::imProgressBar::getInstance()->update( (static_cast(t) / (t1-t0))*100, iim::strprintf("Loading time frame %d/%d", t, t1-t0).c_str()); - iim::imProgressBar::getInstance()->setMessage(1, iim::strprintf("Loading time frame %d/%d", t, t1-t0).c_str()); - iim::imProgressBar::getInstance()->show(false); - } - - iim::uint8* temp_data = frames[t+t0]->loadSubvolume_to_UINT8(V0, V1, H0, H1, D0, D1); - memcpy(subvol_data + t*subvol_frame_size, temp_data, subvol_frame_size*sizeof(iim::uint8)); - delete[] temp_data; - } - - // add gaussian noise - if(iim::ADD_NOISE_TO_TIME_SERIES) - { - for(int t=0; t<=t1-t0; t++) - { - float w = static_cast(t+t0)/(DIM_T-1); - size_t t_stride = t*subvol_frame_size; - for(size_t n=0; n((1-w)*subvol_data[t_stride + n] + w*(rand()%256) +0.5f); - } - } - - return subvol_data; -} diff --git a/v3d_main/terafly/src/core/imagemanager/TimeSeries.h b/v3d_main/terafly/src/core/imagemanager/TimeSeries.h deleted file mode 100644 index 02afab4b98..0000000000 --- a/v3d_main/terafly/src/core/imagemanager/TimeSeries.h +++ /dev/null @@ -1,55 +0,0 @@ -#ifndef TIMESERIES_H -#define TIMESERIES_H - -#include -#include "VirtualVolume.h" - - -class TimeSeries : public iim::VirtualVolume -{ - protected: - - std::vector frames; // each time frame corresponds to a complete volumetric image - - // pure virtual method inherithed from abstract class - void initChannels() throw (iim::IOException); - - public: - - //CONSTRUCTORS-DESTRUCTOR - TimeSeries(void){} - TimeSeries(const char* rootDir, std::string frames_format = "") throw (iim::IOException); - ~TimeSeries(void) throw (iim::IOException); - - // get methods - std::vector getFrames() {return frames;} - std::vector getActiveFrames() throw (iim::IOException); - VirtualVolume* getFrameAt(int t) throw (iim::IOException); - iim::uint32 getNFrames(){return static_cast(frames.size());} - - // returns a unique ID that identifies the volume format - std::string getPrintableFormat(){return iim::TIME_SERIES;} - - // added by Alessandro on 2014-02-18: additional info on the reference system (where available) - float getVXL_1() {return frames.empty() ? 0 : frames[0]->getVXL_1();} - float getVXL_2() {return frames.empty() ? 0 : frames[0]->getVXL_2();} - float getVXL_3() {return frames.empty() ? 0 : frames[0]->getVXL_3();} - iim::axis getAXS_1() {return frames.empty() ? iim::axis_invalid : frames[0]->getAXS_1();} - iim::axis getAXS_2() {return frames.empty() ? iim::axis_invalid : frames[0]->getAXS_2();} - iim::axis getAXS_3() {return frames.empty() ? iim::axis_invalid : frames[0]->getAXS_3();} - - // @OVERRIDE - iim::uint32* getActiveChannels(){ if(!frames.empty()) return frames[0]->getActiveChannels(); else return 0;} - int getNACtiveChannels() { if(!frames.empty()) return frames[0]->getNACtiveChannels(); else return 0;} - - // set active channels (@OVERRIDES VirtualVolume.h by Alessandro on 2014-02-23) - void setActiveChannels ( iim::uint32 *_active, int _n_active ); - - - // pure virtual methods inherithed from abstract class - iim::real32 *loadSubvolume_to_real32(int V0,int V1, int H0, int H1, int D0, int D1) throw (iim::IOException); - iim::uint8 *loadSubvolume_to_UINT8(int V0=-1,int V1=-1, int H0=-1, int H1=-1, int D0=-1, int D1=-1, - int *channels=0, int ret_type=iim::DEF_IMG_DEPTH) throw (iim::IOException); -}; - -#endif // TIMESERIES_H diff --git a/v3d_main/terafly/src/core/imagemanager/UnstitchedVolume.cpp b/v3d_main/terafly/src/core/imagemanager/UnstitchedVolume.cpp deleted file mode 100755 index 39ae2bf2ee..0000000000 --- a/v3d_main/terafly/src/core/imagemanager/UnstitchedVolume.cpp +++ /dev/null @@ -1,605 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -* 2015-03-13. Giulio. @FIXED a bug in 'internal_loadSubvolume_to_real32': MEC must be divided by VXL (and not multiplied) -* 2015-03-13. Giulio. @FIXED a bug in 'internal_loadSubvolume_to_real32': getWIDTH -> getHEIGHT in computing tiles' row indices -* 2015-02-28. Giulio. @ADDED management of multi-channel, multi-bytes per channel images: currently supported up to three channels 8 or 16 bits per channel -* 2015-02-27. Alessandro. @ADDED automated selection of IO plugin if not provided. -* 2015-02-18. Giulio. @CREATED -*/ - -#include -#include -#include "UnstitchedVolume.h" -#include "vmBlockVolume.h" -#include "vmStackedVolume.h" - -#ifdef _WIN32 -#include "dirent_win.h" -#else -#include -#endif - -#include -#include -#include "ProgressBar.h" - -using namespace std; -using namespace iim; - - -UnstitchedVolume::UnstitchedVolume(const char* _root_dir) throw (IOException) -: VirtualVolume(_root_dir) -{ - /**/iim::debug(iim::LEV3, strprintf("_root_dir=%s", _root_dir).c_str(), __iim__current__function__); - - // 2014-09-29. Alessandro. @ADDED automated selection of IO plugin if not provided. - if(iom::IMIN_PLUGIN.compare("empty") == 0) - { - std::string volformat = vm::VirtualVolume::getVolumeFormat(_root_dir); - - if(volformat.compare(vm::StackedVolume::id) == 0) - iom::IMIN_PLUGIN = "tiff2D"; - else if(volformat.compare(vm::BlockVolume::id) == 0) - iom::IMIN_PLUGIN = "tiff3D"; - } - - volume = volumemanager::VirtualVolumeFactory::createFromXML(_root_dir,false); - stitcher = new StackStitcher(volume); - - VXL_V = volume->getVXL_V(); - VXL_H = volume->getVXL_H(); - VXL_D = volume->getVXL_D(); - - ORG_V = volume->getORG_V(); - ORG_H = volume->getORG_H(); - ORG_D = volume->getORG_D(); - - DIM_C = volume->getDIM_C(); - BYTESxCHAN = volume->getBYTESxCHAN(); - - if ( DIM_C > 3 || BYTESxCHAN > 2 ) - throw iim::IOException(iom::strprintf("image not supported by UnstitchedVolume (DIM_C=%d, BYTESxCHAN=%d)", DIM_C, BYTESxCHAN), __iom__current__function__); - - active = (iim::uint32 *) new iim::uint32[DIM_C]; - n_active = DIM_C; - for ( int i=0; icomputeVolumeDims(false); - - DIM_V = stitcher->V1 - stitcher->V0; - DIM_H = stitcher->H1 - stitcher->H0; - DIM_D = stitcher->D1 - stitcher->D0; - - stripesCoords = new stripe_2Dcoords[volume->getN_ROWS()]; - stripesCorners = new stripe_2Dcorners[volume->getN_ROWS()]; -} - -UnstitchedVolume::~UnstitchedVolume(void) -{ - /**/iim::debug(iim::LEV3, 0, __iim__current__function__); - if ( stripesCorners ) { - for ( int i=0; igetN_ROWS(); i++ ) { - stripesCorners[i].ups.clear(); - stripesCorners[i].bottoms.clear(); - stripesCorners[i].merged.clear(); - } - delete []stripesCorners; - } - if ( stripesCoords ) - delete stripesCoords; - if ( volume ) // stitcher does not deallocate its volume - delete volume; - if ( stitcher ) - delete stitcher; -} - - -void UnstitchedVolume::init() -{ - /**/iim::debug(iim::LEV3, 0, __iim__current__function__); -} - -void UnstitchedVolume::initChannels ( ) throw (IOException) -{ - /**/iim::debug(iim::LEV3, 0, __iim__current__function__); -} - -//PRINT method -void UnstitchedVolume::print() -{ -} - -//rotate stacks matrix around D axis (accepted values are theta=0,90,180,270) -void UnstitchedVolume::rotate(int theta) -{ - /**/iim::debug(iim::LEV3, strprintf("theta=%d", theta).c_str(), __iim__current__function__); -} - -//mirror stacks matrix along mrr_axis (accepted values are mrr_axis=1,2,3) -void UnstitchedVolume::mirror(axis mrr_axis) -{ - /**/iim::debug(iim::LEV3, strprintf("mrr_axis=%d", mrr_axis).c_str(), __iim__current__function__); -} - -//extract spatial coordinates (in millimeters) of given Stack object -void UnstitchedVolume::extractCoordinates(Block* blk, int z, int* crd_1, int* crd_2, int* crd_3) -{ -} - -//loads given subvolume in a 1-D array of float -real32* UnstitchedVolume::internal_loadSubvolume_to_real32(int &VV0,int &VV1, int &HH0, int &HH1, int &DD0, int &DD1, int V0,int V1, int H0, int H1, int D0, int D1) throw (IOException) -{ - /**/iim::debug(iim::LEV3, strprintf("V0=%d, V1=%d, H0=%d, H1=%d, D0=%d, D1=%d", V0, V1, H0, H1, D0, D1).c_str(), __iim__current__function__); - - // dummy variabiles - StackRestorer *stk_rst = NULL; - int restore_direction = -1; - - //initializations - V0 = V0 < 0 ? 0 : V0; - H0 = H0 < 0 ? 0 : H0; - D0 = D0 < 0 ? 0 : D0; - V1 = (V1 < 0 || V1 > (int)DIM_V) ? DIM_V : V1; - H1 = (H1 < 0 || H1 > (int)DIM_H) ? DIM_H : H1; - D1 = (D1 < 0 || D1 > (int)DIM_D) ? DIM_D : D1; - - //if (V0 > 0 || V1 < DIM_V || H0 > 0 || H1 < DIM_H ) // // it is not a complete layer - // throw iom::exception(iom::strprintf("only subvolumes corresponding to whole layers can be extracted"), __iom__current__function__); - - // change when subvolumes are enabled - int row_start; - int row_end; - int col_start; - int col_end; - - // change when subvolumes are enabled - //row_start = stitcher->ROW_START; - //row_end = stitcher->ROW_END;; - //col_start = stitcher->COL_START; - //col_end = stitcher->COL_END; - - // compute which tiles have to be loaded - int vxl_i; - - row_start = 0; - vxl_i = (int) floor( volume->getMEC_V() / volume->getVXL_V() ); - while ( vxl_i < V0 ) { - row_start++; - vxl_i += volume->getSTACKS()[row_start][0]->getHEIGHT(); - } - row_end = row_start; - while ( vxl_i < V1 ) { - row_end++; - vxl_i += volume->getSTACKS()[row_end][0]->getHEIGHT(); - } - - col_start = 0; - vxl_i = (int) floor( volume->getMEC_H() / volume->getVXL_H()); - while ( vxl_i < H0 ) { - col_start++; - vxl_i += volume->getSTACKS()[0][col_start]->getWIDTH(); - } - col_end = col_start; - while ( vxl_i < H1 ) { - col_end++; - vxl_i += volume->getSTACKS()[0][col_end]->getWIDTH(); - } - - stitcher->computeVolumeDims(false,row_start,row_end,col_start,col_end,D0,D1); - - V0 = stitcher->V0; - V1 = stitcher->V1; - H0 = stitcher->H0; - H1 = stitcher->H1; - D0 = stitcher->D0; - D1 = stitcher->D1; - - //computing VH coordinates of all stripes - for(int row_index=stitcher->ROW_START; row_index<=stitcher->ROW_END; row_index++) - { - stripesCoords[row_index].up_left.V = stitcher->getStripeABS_V(row_index,true); - stripesCoords[row_index].up_left.H = volume->getSTACKS()[row_index][stitcher->COL_START]->getABS_H(); - stripesCoords[row_index].bottom_right.V = stitcher->getStripeABS_V(row_index,false); - stripesCoords[row_index].bottom_right.H = volume->getSTACKS()[row_index][stitcher->COL_END]->getABS_H()+volume->getStacksWidth(); - } - - // clear stripesCorners - for ( int i=0; igetN_ROWS(); i++ ) { - stripesCorners[i].ups.clear(); - stripesCorners[i].bottoms.clear(); - stripesCorners[i].merged.clear(); - } - - //computing stripes corners, i.e. corners that result from the overlap between each pair of adjacent stripes - for(int row_index=stitcher->ROW_START; row_index<=stitcher->ROW_END; row_index++) - { - stripe_corner tmp; - - //for first VirtualStack of every stripe - tmp.H = volume->getSTACKS()[row_index][stitcher->COL_START]->getABS_H(); - tmp.h = volume->getSTACKS()[row_index][stitcher->COL_START]->getABS_V()-stripesCoords[row_index].up_left.V; - tmp.up = true; - stripesCorners[row_index].ups.push_back(tmp); - - tmp.h = stripesCoords[row_index].bottom_right.V - volume->getSTACKS()[row_index][stitcher->COL_START]->getABS_V() - volume->getStacksHeight(); - tmp.up = false; - stripesCorners[row_index].bottoms.push_back(tmp); - - for(int col_index=stitcher->COL_START; col_indexCOL_END; col_index++) - { - if(volume->getSTACKS()[row_index][col_index]->getABS_V() < volume->getSTACKS()[row_index][col_index+1]->getABS_V()) - { - tmp.H = volume->getSTACKS()[row_index][col_index]->getABS_H() + volume->getStacksWidth(); - tmp.h = volume->getSTACKS()[row_index][col_index+1]->getABS_V() - stripesCoords[row_index].up_left.V; - tmp.up = true; - stripesCorners[row_index].ups.push_back(tmp); - - tmp.H = volume->getSTACKS()[row_index][col_index+1]->getABS_H(); - tmp.h = stripesCoords[row_index].bottom_right.V - volume->getSTACKS()[row_index][col_index+1]->getABS_V() - volume->getStacksHeight(); - tmp.up = false; - stripesCorners[row_index].bottoms.push_back(tmp); - } - else - { - tmp.H = volume->getSTACKS()[row_index][col_index+1]->getABS_H(); - tmp.h = volume->getSTACKS()[row_index][col_index+1]->getABS_V() - stripesCoords[row_index].up_left.V; - tmp.up = true; - stripesCorners[row_index].ups.push_back(tmp); - - tmp.H = volume->getSTACKS()[row_index][col_index]->getABS_H()+volume->getStacksWidth(); - tmp.h = stripesCoords[row_index].bottom_right.V - volume->getSTACKS()[row_index][col_index+1]->getABS_V() - volume->getStacksHeight(); - tmp.up = false; - stripesCorners[row_index].bottoms.push_back(tmp); - } - } - - //for last VirtualStack of every stripe (h is not set because it doesn't matter) - tmp.H = volume->getSTACKS()[row_index][stitcher->COL_END]->getABS_H() + volume->getStacksWidth(); - tmp.up = true; - stripesCorners[row_index].ups.push_back(tmp); - - tmp.up = false; - stripesCorners[row_index].bottoms.push_back(tmp); - } - - //ordered merging between ups and bottoms corners for every stripe - for(int row_index = 1; row_index<=(volume->getN_ROWS()-1); row_index++) - { - stripesCorners[row_index-1].merged.merge(stripesCorners[row_index-1].bottoms, compareCorners); - stripesCorners[row_index-1].merged.merge(stripesCorners[row_index ].ups, compareCorners); - } - - sint64 height; - sint64 width; - sint64 depth; - int slice_height = -1; - int slice_width = -1; - - width = H1 - H0; - height = V1 - V0; - depth = D1 - D0; - - slice_height = (int)(slice_height == -1 ? height : slice_height); - slice_width = (int)(slice_width == -1 ? width : slice_width); - - sint64 u_strp_bottom_displ; - sint64 d_strp_top_displ; - sint64 u_strp_top_displ; - sint64 d_strp_left_displ; - sint64 u_strp_left_displ; - sint64 d_strp_width; - sint64 u_strp_width; - sint64 dd_strp_top_displ; - sint64 u_strp_d_strp_overlap = 0; // WARNING: check how initialize - sint64 h_up, h_down, h_overlap; - iom::real_t *buffer_ptr, *ustripe_ptr, *dstripe_ptr; - - iom::real_t* buffer; //buffer temporary image data are stored - iom::real_t* stripe_up=NULL, *stripe_down; //will contain up-stripe and down-stripe computed by calling 'getStripe' method - double angle; //angle between 0 and PI used to sample overlapping zone in [0,PI] - double delta_angle; //angle step - - iom::real_t (*blending)(double& angle, iom::real_t& pixel1, iom::real_t& pixel2); - int blending_algo = S_SINUSOIDAL_BLENDING; - - //retrieving blending function - if(blending_algo == S_SINUSOIDAL_BLENDING) - blending = StackStitcher::sinusoidal_blending; - else if(blending_algo == S_NO_BLENDING) - blending = StackStitcher::no_blending; - else if(blending_algo == S_SHOW_STACK_MARGIN) - blending = StackStitcher::stack_margin; - else - throw iim::IOException(iom::strprintf("unrecognized blending function"), __iom__current__function__); - - buffer = new iom::real_t[height*width*depth]; - for (int i=0; iROW_START; row_index<=stitcher->ROW_END; row_index++) - { - //loading down stripe - if(row_index==stitcher->ROW_START) stripe_up = NULL; - stripe_down = stitcher->getStripe(row_index,(int)(z+k), restore_direction, stk_rst, blending_algo); - - if(stripe_up) u_strp_bottom_displ = stripesCoords[row_index-1].bottom_right.V - V0; - d_strp_top_displ = stripesCoords[row_index ].up_left.V - V0; - if(stripe_up) u_strp_top_displ = stripesCoords[row_index-1].up_left.V - V0; - d_strp_left_displ = stripesCoords[row_index ].up_left.H - H0; - if(stripe_up) u_strp_left_displ = stripesCoords[row_index-1].up_left.H - H0; - d_strp_width = stripesCoords[row_index ].bottom_right.H - stripesCoords[row_index ].up_left.H; - if(stripe_up) u_strp_width = stripesCoords[row_index-1].bottom_right.H - stripesCoords[row_index-1].up_left.H; - if(stripe_up) u_strp_d_strp_overlap = u_strp_bottom_displ - d_strp_top_displ; - if(row_index!=stitcher->ROW_END) - dd_strp_top_displ = stripesCoords[row_index+1].up_left.V - V0; - h_up = h_down = u_strp_d_strp_overlap; - - //overlapping zone - if(row_index!=stitcher->ROW_START) - { - std::list::iterator cnr_i_next, cnr_i = stripesCorners[row_index-1].merged.begin(); - stripe_corner *cnr_left=&(*cnr_i), *cnr_right; - cnr_i++; - cnr_i_next = cnr_i; - cnr_i_next++; - - while( cnr_i != stripesCorners[row_index-1].merged.end()) - { - //computing h_up, h_overlap, h_down - cnr_right = &(*cnr_i); - if(cnr_i_next == stripesCorners[row_index-1].merged.end()) - { - h_up = cnr_left->up ? u_strp_d_strp_overlap : 0; - h_down = cnr_left->up ? 0 : u_strp_d_strp_overlap; - } - else - if(cnr_left->up) - h_up = cnr_left->h; - else - h_down = cnr_left->h; - - h_overlap = u_strp_d_strp_overlap - h_up - h_down; - - //splitting overlapping zone in sub-regions along H axis - for(sint64 j= cnr_left->H - H0; j < cnr_right->H - H0; j++) - { - delta_angle = PI/(h_overlap-1); - angle = 0; - - //UP stripe zone - buffer_ptr = &buffer[k*height*width+d_strp_top_displ*width+j]; - ustripe_ptr = &stripe_up[(d_strp_top_displ-u_strp_top_displ)*u_strp_width +j - u_strp_left_displ]; - for(sint64 i=d_strp_top_displ; i= 0 ? 0 : h_overlap); i++, buffer_ptr+=width, ustripe_ptr+= u_strp_width) - *buffer_ptr = *ustripe_ptr; - - //OVERLAPPING zone - buffer_ptr = &buffer[k*height*width+(d_strp_top_displ+h_up)*width+j]; - ustripe_ptr = &stripe_up[(d_strp_top_displ+h_up-u_strp_top_displ)*u_strp_width +j - u_strp_left_displ]; - dstripe_ptr = &stripe_down[(d_strp_top_displ+h_up-d_strp_top_displ)*d_strp_width +j - d_strp_left_displ]; - for(sint64 i=d_strp_top_displ+h_up; i= 0 ? h_overlap : 0))*width+j]; - dstripe_ptr = &stripe_down[((d_strp_top_displ+h_up+(h_overlap >= 0 ? h_overlap : 0))-d_strp_top_displ)*d_strp_width +j - d_strp_left_displ]; - for(sint64 i=d_strp_top_displ+h_up+(h_overlap >= 0 ? h_overlap : 0); iROW_START ? 0 : u_strp_bottom_displ))*width]; - for(sint64 i= (row_index==stitcher->ROW_START ? 0 : u_strp_bottom_displ); i<(row_index==stitcher->ROW_END? height : dd_strp_top_displ); i++) - { - dstripe_ptr = &stripe_down[(i-d_strp_top_displ)*d_strp_width - d_strp_left_displ]; - for(sint64 j=0; j= 0 && j - d_strp_left_displ < stripesCoords[row_index].bottom_right.H) - *buffer_ptr = *dstripe_ptr; - } - - //moving to bottom stripe_up - delete stripe_up; - stripe_up=stripe_down; - } - //releasing last stripe_down - delete stripe_down; - } - - VV0 = V0; - VV1 = V1; - HH0 = H0; - HH1 = H1; - DD0 = D0; - DD1 = D1; - - return buffer; -} - -//loads given subvolume in a 1-D array of float -real32* UnstitchedVolume::loadSubvolume_to_real32(int V0,int V1, int H0, int H1, int D0, int D1) throw (IOException) -{ - //throw iim::IOException("Not yet implemented", __iom__current__function__); - - /**/iim::debug(iim::LEV3, strprintf("V0=%d, V1=%d, H0=%d, H1=%d, D0=%d, D1=%d", V0, V1, H0, H1, D0, D1).c_str(), __iim__current__function__); - - if ( DIM_C > 1 && iom::CHANS == iom::ALL ) { - throw iim::IOException(iom::strprintf("conversion from multi-channel to intensity images not supported"), __iom__current__function__); - } - - int VV0, VV1, HH0, HH1, DD0, DD1; - - //initializations - V0 = V0 < 0 ? 0 : V0; - H0 = H0 < 0 ? 0 : H0; - D0 = D0 < 0 ? 0 : D0; - V1 = (V1 < 0 || V1 > (int)DIM_V) ? DIM_V : V1; - H1 = (H1 < 0 || H1 > (int)DIM_H) ? DIM_H : H1; - D1 = (D1 < 0 || D1 > (int)DIM_D) ? DIM_D : D1; - - real32 *buf = internal_loadSubvolume_to_real32(VV0, VV1, HH0, HH1, DD0, DD1, V0, V1, H0, H1, D0, D1); - - if ( VV0 == V0 && HH0 == H0 && DD0 == D0 && VV1 == V1 && HH1 == H1 && DD1 == D1 ) - // there is no need to extract the subvolume from the returned buffer - return buf; - - // extract requested subvolume from the returned buffer - - sint64 stridex = HH1 - HH0; - sint64 stridexy = stridex * (VV1 - VV0); - - sint64 sbv_width = H1 - H0; - sint64 sbv_height = V1 - V0; - sint64 sbv_depth = D1 - D0; - - real32 *subvol = new real32[sbv_width * sbv_height * sbv_depth * DIM_C * BYTESxCHAN]; - - int i, j, k; - real32 *ptr_s_xy; - real32 *ptr_s_x; - real32 *ptr_s; - real32 *ptr_d = subvol; - for ( k=D0, ptr_s_xy=buf + (V0 - VV0)*stridex + (H0 - HH0); k (int)DIM_V) ? DIM_V : V1; - H1 = (H1 < 0 || H1 > (int)DIM_H) ? DIM_H : H1; - D1 = (D1 < 0 || D1 > (int)DIM_D) ? DIM_D : D1; - - if ( DIM_C > 1 ){ - // load the first channel - iom::CHANS = iom::R; - } - - real32 *buf = internal_loadSubvolume_to_real32(VV0, VV1, HH0, HH1, DD0, DD1, V0, V1, H0, H1, D0, D1); - - if ( VV0 > V0 || HH0 > H0 || DD0 > D0 || VV1 < V1 || HH1 < H1 || DD1 < D1 ) - throw iim::IOException(iom::strprintf("returned buffer is smaller than the requested subvolume (requested [V0=%d, V1=%d, H0=%d, H1=%d, D0=%d, D1=%d] -- returned [VV0=%d, VV1=%d, HH0=%d, HH1=%d, DD0=%d, DD1=%d])", - V0, V1, H0, H1, D0, D1, VV0, VV1, HH0, HH1, DD0, DD1), __iim__current__function__); - - // change when subvolumes are enabled - sint64 stridex = HH1 - HH0; - sint64 stridexy = stridex * (VV1 - VV0); - - sint64 sbv_width = H1 - H0; - sint64 sbv_height = V1 - V0; - sint64 sbv_depth = D1 - D0; - - uint8 *subvol = new uint8[sbv_width * sbv_height * sbv_depth * DIM_C * BYTESxCHAN]; - - int i, j, k, c; - real32 *ptr_s_xy; - real32 *ptr_s_x; - real32 *ptr_s; - if ( BYTESxCHAN == 1 ) { - - uint8 *ptr_d = subvol; - for ( k=D0, ptr_s_xy=buf + (V0 - VV0)*stridex + (H0 - HH0); k -#include - -#include "../volumemanager/volumemanager.config.h" -#include "../stitcher/StackStitcher.h" - - -struct coord_2D{int V,H;}; -struct stripe_2Dcoords{coord_2D up_left, bottom_right;}; -struct stripe_corner{int h,H; bool up;}; -struct stripe_2Dcorners{std::list ups, bottoms, merged;}; -extern bool compareCorners (stripe_corner first, stripe_corner second); - - -//every object of this class has the default (1,2,3) reference system -class UnstitchedVolume : public iim::VirtualVolume -{ - private: - - volumemanager::VirtualVolume* volume; - StackStitcher* stitcher; - - iim::ref_sys reference_system; //reference system of the stored volume - - stripe_2Dcoords *stripesCoords; - stripe_2Dcorners *stripesCorners; - - - //***OBJECT PRIVATE METHODS**** - UnstitchedVolume(void); - - //Given the reference system, initializes all object's members using stack's directories hierarchy - void init(); - - //rotate stacks matrix around D axis (accepted values are theta=0,90,180,270) - void rotate(int theta); - - //mirror stacks matrix along mrr_axis (accepted values are mrr_axis=1,2,3) - void mirror(iim::axis mrr_axis); - - //extract spatial coordinates (in millimeters) of given Stack object reading directory and filenames as spatial coordinates - void extractCoordinates(iim::Block* stk, int z, int* crd_1, int* crd_2, int* crd_3); - - // iannello returns the number of channels of images composing the volume - void initChannels ( ) throw (iim::IOException); - - //loads given subvolume in a 1-D array of iim::real32; since the loaded subvolume can have slightly different vertices, returns the actual - //vertices of the subvolume in (VV0, VV1, HH0, HH1, DD0, DD1) - iim::real32 *internal_loadSubvolume_to_real32(int &VV0, int &VV1, int &HH0, int &HH1, int &DD0, int &DD1, - int V0=-1, int V1=-1, int H0=-1, int H1=-1, int D0=-1, int D1=-1) throw (iim::IOException); - - public: - //CONSTRUCTORS-DECONSTRUCTOR - UnstitchedVolume(const char* _root_dir) throw (iim::IOException); - - ~UnstitchedVolume(void); - - //GET methods - float getVXL_1(){return VXL_V;} - float getVXL_2(){return VXL_H;} - float getVXL_3(){return VXL_D;} - iim::axis getAXS_1(){return reference_system.first;} - iim::axis getAXS_2(){return reference_system.second;} - iim::axis getAXS_3(){return reference_system.third;} - - // returns a unique ID that identifies the volume format - std::string getPrintableFormat(){ return iim::UNST_TIF3D_FORMAT; } - - //PRINT method - void print(); - - //loads given subvolume in a 1-D array of iim::real32 - iim::real32 *loadSubvolume_to_real32(int V0=-1,int V1=-1, int H0=-1, int H1=-1, int D0=-1, int D1=-1) throw (iim::IOException); - - //loads given subvolume in a 1-D array of iim::uint8 while releasing stacks slices memory when they are no longer needed - iim::uint8 *loadSubvolume_to_UINT8(int V0=-1,int V1=-1, int H0=-1, int H1=-1, int D0=-1, int D1=-1, - int *channels=0, int ret_type=iim::DEF_IMG_DEPTH) throw (iim::IOException); -}; - -#endif //_UNSTITCHED_VOLUME_H diff --git a/v3d_main/terafly/src/core/imagemanager/VirtualFmtMngr.cpp b/v3d_main/terafly/src/core/imagemanager/VirtualFmtMngr.cpp deleted file mode 100644 index f3dd6c9dd6..0000000000 --- a/v3d_main/terafly/src/core/imagemanager/VirtualFmtMngr.cpp +++ /dev/null @@ -1,315 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -#include "VirtualFmtMngr.h" -#include "Tiff3DMngr.h" - -using namespace iim; - - -/***************************************** - * class VirtualFmtMngr - *****************************************/ - -void VirtualFmtMngr::copyBlock2SubBuf ( unsigned char *src, unsigned char *dst, int dimi, int dimj, int dimk, int typesize, - sint64 s_stridej, sint64 s_strideij, sint64 d_stridej, sint64 d_strideij ) { - - unsigned char *s_slice = src; - unsigned char *d_slice = dst; - unsigned char *s_stripe; - unsigned char *d_stripe; - int i, k; - - s_stridej *= typesize; - s_strideij *= typesize; - d_stridej *= typesize; - d_strideij *= typesize; - - for ( k=0; k -#include "VirtualVolume.h" -#include "SimpleVolume.h" -#include "SimpleVolumeRaw.h" -#include "RawVolume.h" -#include "TiledVolume.h" -#include "TiledMCVolume.h" -#include "StackedVolume.h" -#include "UnstitchedVolume.h" -#include "BDVVolume.h" -#include "RawFmtMngr.h" -#include "Tiff3DMngr.h" -#include "TimeSeries.h" -#include - -// Giulio_CV #include -// Giulio_CV #include -#include "IOPluginAPI.h" // 2014-11-26. Giulio. - - -#include - - -using namespace iim; - -// 2015-04-15. Alessandro. @ADDED definition for default constructor. -VirtualVolume::VirtualVolume(void) -{ - /**/iim::debug(iim::LEV3, 0, __iim__current__function__); - - root_dir = 0; - VXL_V = VXL_H = VXL_D = ORG_V = ORG_H = ORG_D = 0.0f; - DIM_V = DIM_H = DIM_D = DIM_C = 0; - BYTESxCHAN = 0; - active = 0; - n_active = 0; - t0 = t1 = 0; - DIM_T = 1; -} - -/************************************************************************************************************* -* Save image method. <> parameters are mandatory, while [] are optional. -* : absolute path of image to be saved. It DOES NOT include its extension, which is -* provided by the [img_format] parameter. -* : image to be saved. Raw data is in [0,1] and it is stored row-wise in a 1D array. -* : dimensions of raw_img. -* [start/end_height/width] : optional ROI (region of interest) to be set on the given image. -* [img_format] : image format extension to be used (e.g. "tif", "png", etc.) -* [img_depth] : image bitdepth to be used (8 or 16) -**************************************************************************************************************/ -void VirtualVolume::saveImage(std::string img_path, real32* raw_img, int raw_img_height, int raw_img_width, - int start_height, int end_height, int start_width, int end_width, - const char* img_format, int img_depth) throw (IOException) -{ - /**/iim::debug(iim::LEV3, strprintf("img_path=%s, raw_img_height=%d, raw_img_width=%d, start_height=%d, end_height=%d, start_width=%d, end_width=%d", - img_path.c_str(), raw_img_height, raw_img_width, start_height, end_height, start_width, end_width).c_str(), __iim__current__function__); - - //throw IOException("in VirtualVolume::saveImage(...): disabled to remove dependence from openCV"); // Giulio_CV - - // Giulio_CV uint8 *row_data_8bit; - // Giulio_CV uint16 *row_data_16bit; - // Giulio_CV uint32 img_data_step; - // Giulio_CV float scale_factor_16b, scale_factor_8b; - int img_height, img_width; - // Giulio_CV int i,j; - char img_filepath[5000]; - - //setting some default parameters and image dimensions - end_height = (end_height == -1 ? raw_img_height - 1 : end_height); - end_width = (end_width == -1 ? raw_img_width - 1 : end_width ); - img_height = end_height - start_height + 1; - img_width = end_width - start_width + 1; - - //checking parameters correctness - if(!(start_height>=0 && end_height>start_height && end_height=0 && end_width>start_width && end_width(raw_img[ii*raw_img_width+jj] * 255.0f + 0.5f); - } - } - else // img_depth == 16 - { - for(int i = 0, ii = start_height; i (raw_img[ii*raw_img_width+jj] * 65535.0f + 0.5f); - } - } - - //generating complete path for image to be saved - sprintf(img_filepath, "%s.%s", img_path.c_str(), img_format); - - // 2014-11-26. Giulio. @ADDED the output plugin must be explicitly set by the caller - try - { - //iomanager::IOPluginFactory::getPlugin2D(iomanager::IMOUT_PLUGIN)->writeData( - // img_filepath, raw_img, img_height, img_width, 1, start_height, end_height, start_width, end_width, img_depth); - iomanager::IOPluginFactory::getPlugin2D(iomanager::IMOUT_PLUGIN)->writeData( - img_filepath, buffer, img_height, img_width, img_depth/8, 1, 0, img_height, 0, img_width); // ROI limits specify right-open intervals - } - catch (iom::exception & ex) - { - if ( strstr(ex.what(),"2D I/O plugin") ) // this method has be called to save the middle slice for test purposes, even though output plugin is not a 2D plugin - iomanager::IOPluginFactory::getPlugin2D("tiff2D")->writeData( - img_filepath, buffer, img_height, img_width, img_depth/8, 1, 0, img_height, 0, img_width); // ROI limits specify right-open intervals - else - throw iom::exception(iom::strprintf(ex.what()), __iom__current__function__); - } - - delete []buffer; -} - -/************************************************************************************************************* -* Save image method from uint8 raw data. <> parameters are mandatory, while [] are optional. -* : absolute path of image to be saved. It DOES NOT include its extension, which is -* provided by the [img_format] parameter. -* : dimensions of raw_img. -* : raw data of the first channel with values in [0,255]. -* For grayscale images this is the pointer to the raw image data. -* For colour images this is the pointer to the raw image data of the RED channel. -* : raw data of the second channel with values in [0,255]. -* For grayscale images this should be a null pointer (as it is by default). -* For colour images this is the pointer to the raw image data of the GREEN channel. -* : raw data of the third channel with values in [0,255]. -* For grayscale images this should be a null pointer (as it is by default). -* For colour images this is the pointer to the raw image data of the BLUE channel. -* [start/end_height/width] : optional ROI (region of interest) to be set on the given image. -* [img_format] : image format extension to be used (e.g. "tif", "png", etc.) -* [img_depth] : image bitdepth to be used (8 or 16) -**************************************************************************************************************/ -void VirtualVolume::saveImage_from_UINT8 (std::string img_path, uint8* raw_ch1, uint8* raw_ch2, uint8* raw_ch3, - int raw_img_height, int raw_img_width, int start_height, int end_height, int start_width, - int end_width, const char* img_format, int img_depth ) throw (IOException) -{ - /**/iim::debug(iim::LEV3, strprintf("img_path=%s, raw_img_height=%d, raw_img_width=%d, start_height=%d, end_height=%d, start_width=%d, end_width=%d, img_format=%s, img_depth=%d", - img_path.c_str(), raw_img_height, raw_img_width, start_height, end_height, start_width, end_width, img_format, img_depth).c_str(), __iim__current__function__); - - // throw IOException("in VirtualVolume::saveImage_from_UINT8(...): disabled to remove dependence from openCV"); // Giulio_CV - - if ( strcmp(img_format,"tif") != 0 ) - throw iom::exception(iom::strprintf("unsupported file format %s",img_format), __iom__current__function__); - - //checking for non implemented features - //if( img_depth != 8 ) { - // char err_msg[STATIC_STRINGS_SIZE]; - // sprintf(err_msg,"SimpleVolume::loadSubvolume_to_UINT8: invalid number of bits per channel (%d)",img_depth); - // throw IOException(err_msg); - //} - - //LOCAL VARIABLES - char buffer[STATIC_STRINGS_SIZE]; - // Giulio_CV IplImage* img = 0; - uint8 *img = (uint8 *) 0; - int img_height, img_width; - int nchannels = 0; - - //detecting the number of channels (WARNING: the number of channels is an attribute of the volume - nchannels = static_cast(raw_ch1!=0) + static_cast(raw_ch2!=0) + static_cast(raw_ch3!=0); - - //setting some default parameters and image dimensions - end_height = (end_height == -1 ? raw_img_height - 1 : end_height); - end_width = (end_width == -1 ? raw_img_width - 1 : end_width ); - img_height = end_height - start_height + 1; - img_width = end_width - start_width + 1; - - //checking parameters correctness - if(!(start_height>=0 && end_height>start_height && end_height=0 && end_width>start_width && end_width 3) - { - sprintf(buffer,"in saveImage_from_UINT8(): unsupported number of channels (= %d)\n",nchannels); - throw IOException(buffer); - } - if(img_depth != 8 && img_depth != 16 && nchannels == 1) - { - sprintf(buffer,"in saveImage_from_UINT8(..., img_depth=%d, ...): unsupported bit depth for greyscale images\n",img_depth); - throw IOException(buffer); - } - //if(img_depth != 8 && nchannels == 3) // nchannels may be also 2 - if(img_depth != 8 && nchannels > 1) - { - sprintf(buffer,"in saveImage_from_UINT8(..., img_depth=%d, ...): unsupported bit depth for multi-channels images\n",img_depth); - throw IOException(buffer); - } - if ( nchannels >1 && !(iom::IOPluginFactory::getPlugin2D(iom::IMOUT_PLUGIN)->isChansInterleaved()) ) { - throw iom::exception("the plugin do not store channels in interleaved mode: more than one channel not supported yet."); - } - - //converting raw data into tif image data - if(nchannels == 3) - { - img = new uint8[img_width * img_height * nchannels]; // Giulio_CV cvCreateImage(cvSize(img_width, img_height), IPL_DEPTH_8U, 3); - int img_data_step = img_width * nchannels; - for(int i = 0; i depth == 16 - { - int img_data_step = img_width * nchannels * 2; - for(int i = 0; i 1 ? 3 : 1),img_depth/8)) != 0 ) { - throw iom::exception(iom::strprintf("unable to create tiff file (%s)",err_tiff_fmt), __iom__current__function__); - } - - if ( (err_tiff_fmt = appendSlice2Tiff3DFile(buffer,0,(unsigned char *)img,(int)img_width,(int)img_height)) != 0 ) { - throw iom::exception(iom::strprintf("error in saving 2D image (%lld x %lld) in file %s (appendSlice2Tiff3DFile: %s)",img_width,img_height,buffer,err_tiff_fmt), __iom__current__function__); - } - - /* Giulio_CV - - } - catch(std::exception ex) - { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"in saveImage_from_UINT8(...): unable to save image at \"%s\". Unsupported format or wrong path.\n",buffer); - throw IOException(err_msg); - } - - releasing memory - cvReleaseImage(&img); - - */ - - if ( img ) - delete []img; -} - - - -/************************************************************************************************************* -* Save image method to Vaa3D raw format. <> parameters are mandatory, while [] are optional. -* : absolute path of image to be saved. It DOES NOT include its extension, which is -* provided by the [img_format] parameter. -* : image to be saved. Raw data is in [0,1] and it is stored row-wise in a 1D array. -* : dimensions of raw_img. -* [start/end_height/width] : optional ROI (region of interest) to be set on the given image. -* [img_format] : image format extension to be used (e.g. "tif", "png", etc.) -* [img_depth] : image bitdepth to be used (8 or 16) -**************************************************************************************************************/ -void VirtualVolume::saveImage_to_Vaa3DRaw(int slice, std::string img_path, real32* raw_img, int raw_img_height, int raw_img_width, - int start_height, int end_height, int start_width, int end_width, - const char* img_format, int img_depth - ) throw (IOException) -{ - /**/iim::debug(iim::LEV3, strprintf("img_path=%s, raw_img_height=%d, raw_img_width=%d, start_height=%d, end_height=%d, start_width=%d, end_width=%d", img_path.c_str(), raw_img_height, raw_img_width, start_height, end_height, start_width, end_width).c_str(), __iim__current__function__); - - //checking for non implemented features - if ( strcmp(img_format,"Vaa3DRaw")!=0 && strcmp(img_format,"Tiff3D")!=0 ) { // WARNING: there is not a well defined convention yet for specify image format - char msg[STATIC_STRINGS_SIZE]; - sprintf(msg,"in VirtualVolume::saveImage_to_Vaa3DRaw: format \"%s\" not implemented yet",img_format); - throw IOException(msg); - } - - uint8 *row_data_8bit; - uint16 *row_data_16bit; - //uint32 img_data_step; - float scale_factor_16b, scale_factor_8b; - int img_height, img_width; - int i, j, k; - char img_filepath[5000]; - - // WARNING: currently supported only 8/16 bits depth by VirtualVolume::saveImage_from_UINT8_to_Vaa3DRaw - if(img_depth != 8 && img_depth != 16) - { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"in saveImage_to_Vaa3DRaw(..., img_depth=%d, ...): unsupported bit depth\n",img_depth); - throw IOException(err_msg); - } - - //setting some default parameters and image dimensions - end_height = (end_height == -1 ? raw_img_height - 1 : end_height); - end_width = (end_width == -1 ? raw_img_width - 1 : end_width ); - img_height = end_height - start_height + 1; - img_width = end_width - start_width + 1; - - //checking parameters correctness - if(!(start_height>=0 && end_height>start_height && end_height=0 && end_width>start_width && end_width parameters are mandatory, while [] are optional. -* : absolute path of image to be saved. It DOES NOT include its extension, which is -* provided by the [img_format] parameter. -* : array of pointers to raw data of the channels with values in [0,255]. -* For grayscale images raw_ch[0] is the pointer to the raw image data. -* For colour images raw_ch[0] is the pointer to the raw image data of the RED channel. -* WARNING: raw_ch elements should not be overwritten -* : number of channels (length of raw_ch). -* : offset to be added to raw_ch[i] to get actual data -* : dimensions of raw_img. -* [start/end_height/width] : optional ROI (region of interest) to be set on the given image. -* [img_format] : image format extension to be used (e.g. "tif", "png", etc.) -* [img_depth] : image bitdepth to be used (8 or 16) -**************************************************************************************************************/ -void VirtualVolume::saveImage_from_UINT8_to_Vaa3DRaw (int slice, std::string img_path, uint8** raw_ch, int n_chans, sint64 offset, - int raw_img_height, int raw_img_width, int start_height, int end_height, int start_width, - int end_width, const char* img_format, int img_depth ) throw (IOException) -{ - /**/iim::debug(iim::LEV3, strprintf("img_path=%s, raw_img_height=%d, raw_img_width=%d, start_height=%d, end_height=%d, start_width=%d, end_width=%d", img_path.c_str(), raw_img_height, raw_img_width, start_height, end_height, start_width, end_width).c_str(), __iim__current__function__); - - //LOCAL VARIABLES - char buffer[STATIC_STRINGS_SIZE]; - sint64 img_height, img_width; - sint64 img_width_b; // image width in bytes - int img_bytes_per_chan; - - //add offset to raw_ch - //for each channel adds to raw_ch the offset of current slice from the beginning of buffer - uint8** raw_ch_temp = new uint8 *[n_chans]; - for (int i=0; i=0 && end_height>start_height && end_height=0 && end_width>start_width && end_width 1) - // { - // sprintf(buffer,"in saveImage_from_UINT8(..., img_depth=%d, ...): unsupported bit depth for multi-channel images\n",img_depth); - // throw iim::IOException(buffer); - // } - - if(img_depth != 8 && img_depth != 16 && n_chans == 1) - { - sprintf(buffer,"in saveImage_from_UINT8(..., img_depth=%d, ...): unsupported bit depth\n",img_depth); - throw IOException(buffer); - } - img_bytes_per_chan = (img_depth == 8) ? 1 : 2; - // all width parameters have to be multiplied by the number of bytes per channel - img_width_b = img_width * img_bytes_per_chan; - raw_img_width *= img_bytes_per_chan; - start_width *= img_bytes_per_chan; - - uint8 *imageData = new uint8[img_height * img_width_b * n_chans]; - for ( int c=0; c parameters are mandatory, while [] are optional. -* : absolute path of image to be saved. It DOES NOT include its extension, which is -* provided by the [img_format] parameter. -* : array of pointers to raw data of the channels with values in [0,255]. -* For grayscale images raw_ch[0] is the pointer to the raw image data. -* For colour images raw_ch[0] is the pointer to the raw image data of the RED channel. -* WARNING: raw_ch elements should not be overwritten -* : number of channels (length of raw_ch). -* : offset to be added to raw_ch[i] to get actual data -* : dimensions of raw_img. -* [start/end_height/width] : optional ROI (region of interest) to be set on the given image. -* [img_format] : image format extension to be used (e.g. "tif", "png", etc.) -* [img_depth] : image bitdepth to be used (8 or 16) -**************************************************************************************************************/ -void VirtualVolume::saveImage_from_UINT8_to_Tiff3D (int slice, std::string img_path, uint8** raw_ch, int n_chans, sint64 offset, - int raw_img_height, int raw_img_width, int start_height, int end_height, int start_width, - int end_width, const char* img_format, int img_depth, void *fhandle, int n_pages, bool do_open ) throw (IOException) -{ - /**/iim::debug(iim::LEV3, strprintf("img_path=%s, raw_img_height=%d, raw_img_width=%d, start_height=%d, end_height=%d, start_width=%d, end_width=%d", img_path.c_str(), raw_img_height, raw_img_width, start_height, end_height, start_width, end_width).c_str(), __iim__current__function__); - - //LOCAL VARIABLES - char buffer[STATIC_STRINGS_SIZE]; - sint64 img_height, img_width; - sint64 img_width_b; // image width in bytes - int img_bytes_per_chan; - int temp_n_chans = n_chans; // number of channels of the saved image: initialize with the number of channels of the source volume - - //add offset to raw_ch - //for each channel adds to raw_ch the offset of current slice from the beginning of buffer - uint8** raw_ch_temp = new uint8 *[n_chans]; - for (int i=0; i=0 && end_height>start_height && end_height=0 && end_width>start_width && end_width1 && !(iom::IOPluginFactory::getPlugin3D(iom::IMOUT_PLUGIN)->isChansInterleaved()) ) { - throw iom::exception("the 3D plugin do not store channels in interleaved mode: more than one channel not supported yet."); - } - - img_bytes_per_chan = (img_depth == 8) ? 1 : 2; - img_width_b = img_width * img_bytes_per_chan; - - if ( n_chans == 2 ) // for Tiff files channels must be 1 or 3 - temp_n_chans++; - - uint8 *imageData = new uint8[img_height * img_width_b * temp_n_chans]; - - if ( img_bytes_per_chan == 1 ) { - for(sint64 i=0; iappendSlice(buffer,(unsigned char *)imageData,(int)img_height,(int)img_width,img_bytes_per_chan,temp_n_chans,-1,-1,-1,-1,slice); - else if ( ((err_tiff_fmt = appendSlice2Tiff3DFile(fhandle,slice,(unsigned char *)imageData,(int)img_width,(int)img_height,temp_n_chans,img_depth,n_pages)) != 0) ) { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"VirtualVolume::saveImage_from_UINT8_to_Tiff3D: error in saving slice %d (%lld x %lld) in file %s (appendSlice2Tiff3DFile: %s)", slice,img_width,img_height,buffer,err_tiff_fmt); - throw IOException(err_msg); - }; - - delete imageData; -} - - -/************************************************************************************************************* -* Performs downsampling at a halved frequency on the given 3D image. The given image is overwritten in order -* to store its halvesampled version without allocating any additional resources. -**************************************************************************************************************/ -void VirtualVolume::halveSample ( real32* img, int height, int width, int depth, int method ) -{ - float A,B,C,D,E,F,G,H; - - // indices are sint64 because offsets can be larger that 2^31 - 1 - - if ( method == HALVE_BY_MEAN ) { - - for(sint64 z=0; z A ) A = B; - B = img[2*z*width*height + (2*i+1)*width + 2*j]; - if ( B > A ) A = B; - B = img[2*z*width*height + (2*i+1)*width + (2*j+1)]; - if ( B > A ) A = B; - B = img[(2*z+1)*width*height + 2*i*width + 2*j]; - if ( B > A ) A = B; - B = img[(2*z+1)*width*height + 2*i*width + (2*j+1)]; - if ( B > A ) A = B; - B = img[(2*z+1)*width*height + (2*i+1)*width + 2*j]; - if ( B > A ) A = B; - B = img[(2*z+1)*width*height + (2*i+1)*width + (2*j+1)]; - if ( B > A ) A = B; - - //computing mean - img[z*(width/2)*(height/2) + i*(width/2) + j] = A; - } - } - } - - } - else { - char buffer[STATIC_STRINGS_SIZE]; - sprintf(buffer,"in halveSample(...): invalid halving method\n"); - throw IOException(buffer); - } - -} - - -void VirtualVolume::halveSample_UINT8 ( uint8** img, int height, int width, int depth, int channels, int method, int bytes_chan ) -{ - - float A,B,C,D,E,F,G,H; - - // indices are sint64 because offsets can be larger that 2^31 - 1 - - if ( bytes_chan == 1 ) { - - if ( method == HALVE_BY_MEAN ) { - - for(sint64 c=0; c A ) A = B; - B = img[c][2*z*width*height + (2*i+1)*width + 2*j]; - if ( B > A ) A = B; - B = img[c][2*z*width*height + (2*i+1)*width + (2*j+1)]; - if ( B > A ) A = B; - B = img[c][(2*z+1)*width*height + 2*i*width + 2*j]; - if ( B > A ) A = B; - B = img[c][(2*z+1)*width*height + 2*i*width + (2*j+1)]; - if ( B > A ) A = B; - B = img[c][(2*z+1)*width*height + (2*i+1)*width + 2*j]; - if ( B > A ) A = B; - B = img[c][(2*z+1)*width*height + (2*i+1)*width + (2*j+1)]; - if ( B > A ) A = B; - - //computing mean - img[c][z*(width/2)*(height/2) + i*(width/2) + j] = (uint8) iim::round(A); - } - } - } - } - - } - else { - char buffer[STATIC_STRINGS_SIZE]; - sprintf(buffer,"in VirtualVolume::halveSample_UINT8(...): invalid halving method\n"); - throw IOException(buffer); - } - - } - else if ( bytes_chan == 2 ) { - - uint16 **img16 = (uint16 **) img; - - if ( method == HALVE_BY_MEAN ) { - - for(sint64 c=0; c A ) A = B; - B = img16[c][2*z*width*height + (2*i+1)*width + 2*j]; - if ( B > A ) A = B; - B = img16[c][2*z*width*height + (2*i+1)*width + (2*j+1)]; - if ( B > A ) A = B; - B = img16[c][(2*z+1)*width*height + 2*i*width + 2*j]; - if ( B > A ) A = B; - B = img16[c][(2*z+1)*width*height + 2*i*width + (2*j+1)]; - if ( B > A ) A = B; - B = img16[c][(2*z+1)*width*height + (2*i+1)*width + 2*j]; - if ( B > A ) A = B; - B = img16[c][(2*z+1)*width*height + (2*i+1)*width + (2*j+1)]; - if ( B > A ) A = B; - - //computing mean - img[c][z*(width/2)*(height/2) + i*(width/2) + j] = (uint8) iim::round(A); - } - } - } - } - - } - else { - char buffer[STATIC_STRINGS_SIZE]; - sprintf(buffer,"in VirtualVolume::halveSample_UINT8(...): invalid halving method\n"); - throw IOException(buffer); - } - - } - else { - char buffer[STATIC_STRINGS_SIZE]; - sprintf(buffer,"VirtualVolume::in halveSample_UINT8(...): invalid number of bytes per channel (%d)\n", bytes_chan); - throw IOException(buffer); - } -} - -// 2014-04-14. Alessandro. @ADDED 'instance_format' method with inputs = {path, format}. -VirtualVolume* VirtualVolume::instance_format(const char* path, std::string format) throw (iim::IOException) -{ - /**/iim::debug(iim::LEV3, strprintf("path = \"%s\", format = \"%s\"", path, format.c_str()).c_str(), __iim__current__function__); - - VirtualVolume* volume = 0; - - // directory formats - if(isDirectory(path)) - { - if((format.compare(TILED_MC_FORMAT) == 0) || (format.compare(TILED_MC_TIF3D_FORMAT) == 0)) - volume = new TiledMCVolume(path); - else if(format.compare(STACKED_FORMAT) == 0) - volume = new StackedVolume(path); - else if((format.compare(TILED_FORMAT) == 0) || (format.compare(TILED_TIF3D_FORMAT) == 0)) - volume = new TiledVolume(path); - else if(format.compare(SIMPLE_RAW_FORMAT) == 0) - volume = new SimpleVolumeRaw(path); - else if(format.compare(SIMPLE_FORMAT) == 0) - volume = new SimpleVolume(path); - else if(format.compare(TIME_SERIES) == 0) - volume = new TimeSeries(path); - else - throw IOException(strprintf("in VirtualVolume::instance(): Unsupported format \"%s\" for path \"%s\" which is a directory", format.c_str(), path), __iim__current__function__); - } - // file formats - else if(isFile(path)) - { - if(format.compare(RAW_FORMAT) == 0 || (format.compare(TIF3D_FORMAT) == 0)) - volume = new RawVolume(path); - else if(format.compare(UNST_TIF3D_FORMAT) == 0) - volume = new UnstitchedVolume(path); - else if(format.compare(BDV_HDF5_FORMAT) == 0) - throw IOException(strprintf("in VirtualVolume::instance(): volumes in format \"%s\" should be created with another \"instance\" method", format.c_str(), path), __iim__current__function__); - else - throw IOException(strprintf("in VirtualVolume::instance(): Unsupported format \"%s\" for path \"%s\" which is a file", format.c_str(), path), __iim__current__function__); - } - else - throw IOException(strprintf("in VirtualVolume::instance(): path = \"%s\" does not exist", path), __iim__current__function__); - - return volume; -} - -// tries to automatically detect the volume format and returns the imported volume if succeeds (otherwise returns 0) -// WARNING: all metadata files (if needed by that format) are assumed to be present. Otherwise, that format will be skipped. -VirtualVolume* VirtualVolume::instance(const char* path) throw (IOException) -{ - /**/iim::debug(iim::LEV3, strprintf("path = \"%s\"", path).c_str(), __iim__current__function__); - - VirtualVolume* volume = 0; - - // directory formats - if(isDirectory(path)) - { - // 2015-02-06. Alessandro. @ADDED volume format metadata file for faster opening of a "directory format" - std::string format = "unknown"; - if(isFile(std::string(path) + "/" + iim::FORMAT_MDATA_FILE_NAME)) - { - try - { - std::ifstream f((std::string(path) + "/" + iim::FORMAT_MDATA_FILE_NAME).c_str()); - if(f.is_open()) - { - std::getline(f,format); - f.close(); - - // 2015-04-14. Alessandro. @FIXED detection of volume format from .iim.format file - if(format.compare((TiledMCVolume().getPrintableFormat())) == 0) - volume = new TiledMCVolume(path); - else if(format.compare((StackedVolume().getPrintableFormat())) == 0) - volume = new StackedVolume(path); - else if(format.compare((TiledVolume().getPrintableFormat())) == 0) - volume = new TiledVolume(path); - else if(format.compare((SimpleVolume().getPrintableFormat())) == 0) - volume = new SimpleVolume(path); - else if(format.compare((SimpleVolumeRaw().getPrintableFormat())) == 0) - volume = new SimpleVolumeRaw(path); - else if(format.compare((TimeSeries().getPrintableFormat())) == 0) - volume = new TimeSeries(path); - else - iim::warning(iim::strprintf("Cannot recognize format \"%s\"", format.c_str()).c_str(), __iim__current__function__); - } - } - catch(IOException &ex) - { - debug(LEV3, strprintf("Cannot import <%s> format at \"%s\": %s", format.c_str(), path, ex.what()).c_str(),__iim__current__function__); - } - } - - if(!volume) - { - try - { - volume = new TiledMCVolume(path); - } - catch(IOException &ex) - { - debug(LEV3, strprintf("Cannot import at \"%s\": %s", path, ex.what()).c_str(),__iim__current__function__); - try - { - volume = new StackedVolume(path); - } - catch(IOException &ex) - { - debug(LEV3, strprintf("Cannot import at \"%s\": %s", path, ex.what()).c_str(),__iim__current__function__); - try - { - volume = new TiledVolume(path); - } - catch(IOException &ex) - { - debug(LEV3, strprintf("Cannot import at \"%s\": %s", path, ex.what()).c_str(),__iim__current__function__); - try - { - volume = new SimpleVolume(path); - } - catch(IOException &ex) - { - debug(LEV3, strprintf("Cannot import at \"%s\": %s", path, ex.what()).c_str(),__iim__current__function__); - try - { - volume = new SimpleVolumeRaw(path); - } - catch(IOException &ex) - { - debug(LEV3, strprintf("Cannot import at \"%s\": %s", path, ex.what()).c_str(),__iim__current__function__); - try - { - volume = new TimeSeries(path); - } - catch(IOException &ex) - { - debug(LEV3, strprintf("Cannot import at \"%s\": %s", path, ex.what()).c_str(),__iim__current__function__); - } - } - } - } - } - } - catch(...) - { - debug(LEV3, strprintf("generic error occurred when importing volume at \"%s\"", path).c_str(),__iim__current__function__); - } - } - - // 2015-04-14. Alessandro. @FIXED detection of volume format from .iim.format file - // 2015-02-06. Alessandro. @ADDED volume format metadata file for faster opening of a "directory format" - if(volume && !isFile(std::string(path) + "/" + iim::FORMAT_MDATA_FILE_NAME)) - { - std::ofstream f((std::string(path) + "/" + iim::FORMAT_MDATA_FILE_NAME).c_str(), std::ofstream::out); - if(f.is_open()) - { - f << volume->getPrintableFormat(); - f.close(); - } - } - } - // try all file formats - else if(isFile(path)) - { - try - { - volume = new RawVolume(path); - } - catch(IOException &ex) - { - debug(LEV3, strprintf("Cannot import at \"%s\": %s", path, ex.what()).c_str(),__iim__current__function__); - try - { - volume = new UnstitchedVolume(path); - } - catch(IOException &ex) - { - debug(LEV3, strprintf("Cannot import at \"%s\": %s", path, ex.what()).c_str(),__iim__current__function__); - // does not try BVDVolume because this volume should be created using the next "instance" method - } - } - catch(...) - { - debug(LEV3, strprintf("generic error occurred when importing volume at \"%s\"", path).c_str(),__iim__current__function__); - } - } - else - throw IOException(strprintf("Path = \"%s\" does not exist", path), __iim__current__function__); - - return volume; -} - - -// this version if "instance" methods should be used to create a BDVVolume since at least the 'res' parameter is needed -VirtualVolume* VirtualVolume::instance(const char* fname, int res, void *descr) throw (iim::IOException) { - /**/iim::debug(iim::LEV3, strprintf("fname = \"%s\", res = %d, descr = %p", fname, res, descr).c_str(), __iim__current__function__); - - return new BDVVolume(fname,res,0,descr); // assumes there is only time point 0 -} - - -// returns the imported volume if succeeds (otherwise returns 0) -// WARNING: no assumption is made on metadata files, which are possibly (re-)generated using the additional informations provided. -VirtualVolume* VirtualVolume::instance(const char* path, std::string format, - iim::axis AXS_1, iim::axis AXS_2, iim::axis AXS_3, /* = iim::axis_invalid */ - float VXL_1 /* = 0 */, float VXL_2 /* = 0 */, float VXL_3 /* = 0 */) throw (iim::IOException) -{ - /**/iim::debug(iim::LEV3, strprintf("path = \"%s\", format = %s, AXS_1 = %s, AXS_2 = %s, AXS_3 = %s, VXL_1 = %.2f, VXL_2 = %.2f, VXL_3 = %.2f", - path, format.c_str(), axis_to_str(AXS_1), axis_to_str(AXS_2), axis_to_str(AXS_3), - VXL_1, VXL_2, VXL_3).c_str(), __iim__current__function__); - - VirtualVolume* volume = 0; - - // directory formats - if(isDirectory(path)) - { - if((format.compare(TILED_MC_FORMAT) == 0) || (format.compare(TILED_MC_TIF3D_FORMAT) == 0)) - { - if(AXS_1 != axis_invalid && AXS_2 != axis_invalid && AXS_3 != axis_invalid && VXL_1 != 0 && VXL_2 != 0 && VXL_3 != 0) - volume = new TiledMCVolume(path, ref_sys(AXS_1,AXS_2,AXS_3), VXL_1, VXL_2, VXL_3, true, true); - else - throw IOException(strprintf("Invalid parameters AXS_1(%s), AXS_2(%s), AXS_3(%s), VXL_1(%.2f), VXL_2(%.2f), VXL_3(%.2f)", - axis_to_str(AXS_1), axis_to_str(AXS_2), axis_to_str(AXS_3), VXL_1, VXL_2, VXL_3).c_str()); - } - else if(format.compare(STACKED_FORMAT) == 0) - { - if(AXS_1 != axis_invalid && AXS_2 != axis_invalid && AXS_3 != axis_invalid && VXL_1 != 0 && VXL_2 != 0 && VXL_3 != 0) - volume = new StackedVolume(path, ref_sys(AXS_1,AXS_2,AXS_3), VXL_1, VXL_2, VXL_3, true, true); - else - throw IOException(strprintf("Invalid parameters AXS_1(%s), AXS_2(%s), AXS_3(%s), VXL_1(%.2f), VXL_2(%.2f), VXL_3(%.2f)", - axis_to_str(AXS_1), axis_to_str(AXS_2), axis_to_str(AXS_3), VXL_1, VXL_2, VXL_3).c_str()); - } - else if((format.compare(TILED_FORMAT) == 0) || (format.compare(TILED_TIF3D_FORMAT) == 0)) - { - if(AXS_1 != axis_invalid && AXS_2 != axis_invalid && AXS_3 != axis_invalid && VXL_1 != 0 && VXL_2 != 0 && VXL_3 != 0) - volume = new TiledVolume(path, ref_sys(AXS_1,AXS_2,AXS_3), VXL_1, VXL_2, VXL_3, true, true); - else - throw IOException(strprintf("Invalid parameters AXS_1(%s), AXS_2(%s), AXS_3(%s), VXL_1(%.2f), VXL_2(%.2f), VXL_3(%.2f)", - axis_to_str(AXS_1), axis_to_str(AXS_2), axis_to_str(AXS_3), VXL_1, VXL_2, VXL_3).c_str()); - } - else if(format.compare(SIMPLE_RAW_FORMAT) == 0) - volume = new SimpleVolumeRaw(path); - else if(format.compare(SIMPLE_FORMAT) == 0) - volume = new SimpleVolume(path); - else - throw IOException(strprintf("in VirtualVolume::instance(): Unsupported format \"%s\" for path \"%s\" which is a directory", format.c_str(), path), __iim__current__function__); - } - // file formats - else if(isFile(path)) - { - if(format.compare(RAW_FORMAT) == 0 || (format.compare(TIF3D_FORMAT) == 0)) - volume = new RawVolume(path); - else if(format.compare(UNST_TIF3D_FORMAT) == 0) - volume = new UnstitchedVolume(path); - else if(format.compare(BDV_HDF5_FORMAT) == 0) - throw IOException(strprintf("in VirtualVolume::instance(): volumes in format \"%s\" should be created with another \"instance\" method", format.c_str(), path), __iim__current__function__); - else - throw IOException(strprintf("in VirtualVolume::instance(): Unsupported format \"%s\" for path \"%s\" which is a file", format.c_str(), path), __iim__current__function__); - } - else - throw IOException(strprintf("in VirtualVolume::instance(): path = \"%s\" does not exist", path), __iim__current__function__); - - - return volume; -} - -// (@MOVED from TiledMCVolume.cpp by Alessandro on 2014-02-20) -void VirtualVolume::setActiveChannels ( uint32 *_active, int _n_active ) -{ - /**/iim::debug(iim::LEV3, 0, __iim__current__function__); - - if ( active ) - delete[] active; - active = _active; - n_active = _n_active; -} - -// returns true if the given format is hierarchical, i.e. if it consists of nested folders (1 level at least) -bool VirtualVolume::isHierarchical(std::string format) throw (iim::IOException) -{ - /**/iim::debug(iim::LEV3, strprintf("format = %s", format.c_str()).c_str(), __iim__current__function__); - - if(format.compare(TILED_FORMAT) == 0) - return true; - else if(format.compare(TILED_MC_FORMAT) == 0) - return true; - else if(format.compare(TILED_MC_TIF3D_FORMAT) == 0) - return true; - else if(format.compare(STACKED_FORMAT) == 0) - return true; - else if(format.compare(TIME_SERIES) == 0) - return true; - else if(format.compare(SIMPLE_FORMAT) == 0) - return true; - else if(format.compare(SIMPLE_RAW_FORMAT) == 0) - return true; - else if(format.compare(TILED_TIF3D_FORMAT) == 0) - return true; - else if(format.compare(RAW_FORMAT) == 0) - return false; - else if(format.compare(TIF3D_FORMAT) == 0) - return false; - else if(format.compare(UNST_TIF3D_FORMAT) == 0) - return false; - else if(format.compare(BDV_HDF5_FORMAT) == 0) - return false; - else - throw IOException(strprintf("Unsupported format %s", format.c_str()), __iim__current__function__); - -} diff --git a/v3d_main/terafly/src/core/imagemanager/VirtualVolume.h b/v3d_main/terafly/src/core/imagemanager/VirtualVolume.h deleted file mode 100644 index 2c75244651..0000000000 --- a/v3d_main/terafly/src/core/imagemanager/VirtualVolume.h +++ /dev/null @@ -1,322 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -* 2015-04-14. Alessandro. @ADDED 'instance_format' method with inputs = {path, format}. -* 2015-02-28. Giulio. @FIXED added deallocation of data member 'active' in the destructor -* 2015-02-18. Giulio. @CHANGED modified defalut values of parameters of loadSubvolume methods -* 2015-01-06. Giulio. @ADDED changed interface of saveImage_from_UINT8_to_Tiff3D to introduce optimizations to reduce opend/close in append operations -*/ - -#ifndef _IIM_VIRTUAL_VOLUME_H -#define _IIM_VIRTUAL_VOLUME_H - -# define HALVE_BY_MEAN 1 -# define HALVE_BY_MAX 2 - -#include -#include - -#include "IM_config.h" - -class iim::VirtualVolume { - -protected: - //******OBJECT ATTRIBUTES****** - char* root_dir; // C-string that contains the directory path of stacks matrix - float VXL_V, VXL_H, VXL_D; // [microns]: voxel dimensions (in microns) along V(Vertical), H(horizontal) and D(Depth) axes - float ORG_V, ORG_H, ORG_D; // [millimeters]: origin spatial coordinates (in millimeters) along VHD axes - iim::uint32 DIM_V, DIM_H, DIM_D;// volume dimensions (in voxels) along VHD axes - int DIM_C; // number of channels (@ADDED by Iannello on ..........) - int BYTESxCHAN; // number of bytes per channel - iim::uint32 *active; // array of active channels (@MOVED from "TiledMCVolume" by Alessandro on 2014-02-20) - int n_active; // number of active channels (@MOVED from "TiledMCVolume" by Alessandro on 2014-02-20) - - int DIM_T; // number of time frames (@ADDED by Alessandro on 2014-02-20) - int t0, t1; // active frames are in [t0, t1] (@ADDED by Alessandro on 2014-02-20) - -public: - //CONSTRUCTORS-DECONSTRUCTOR - VirtualVolume(); - VirtualVolume(const char* _root_dir, float VXL_1=0, float VXL_2=0, float VXL_3=0) throw (iim::IOException) - { - - this->root_dir = new char[strlen(_root_dir)+1]; - strcpy(this->root_dir, _root_dir); - - VXL_V = VXL_1; - VXL_H = VXL_2; - VXL_D = VXL_3; - - ORG_V = ORG_H = ORG_D = (float) 0.0; - DIM_V = DIM_H = DIM_D = 0; - - DIM_C = 0; - BYTESxCHAN = 0; - active = (iim::uint32 *)0; - n_active = 0; - - t0 = t1 = 0; - DIM_T = 1; - - } - - virtual ~VirtualVolume() { - if(root_dir) - delete[] root_dir; - if(active) - delete []active; - } - - virtual void initChannels ( ) throw (iim::IOException) = 0; - - - //loads given subvolume in a 1-D array of iim::real32 while releasing stacks slices memory when they are no longer needed - virtual iim::real32 *loadSubvolume_to_real32(int V0=-1,int V1=-1, int H0=-1, int H1=-1, int D0=-1, int D1=-1) throw (iim::IOException) = 0; - - - /* @ADDED by Giulio on 2015-12-06: - * loads given subvolume in a 1-D array of iim::uint8 - * data is returned in interna Vaa3D representation, i.e. voxels are stored as one 3D matrix per channel in C-like ordering - * (dimension order is: H,V,D,channel) - * - * V0-D1: indices that define the subvolume; index intervals are open at right (e.g. [V0,V1)) - * channels: returns the number of channels loaded - * ret_type: specifies the number of bits per voxel in each channel; the default is iim::DEF_IMG_DEPTH (see IM_config.h for definition) - * if the value of this parameter is iim::NATIVE_RTYPE (see IM_config.h for definition) the subvolume is stored in the - * returned buffer using the number of bits per voxel in each channel of the current volume - * currently only iim::DEF_IMG_DEPTH and iim::NATIVE_RTYPE are permitted values for this parameter - */ - virtual iim::uint8 *loadSubvolume_to_UINT8(int V0=-1,int V1=-1, int H0=-1, int H1=-1, int D0=-1, int D1=-1, - int *channels=0, int ret_type=iim::DEF_IMG_DEPTH) throw (iim::IOException) = 0; - - // ******GET METHODS****** - float getORG_V() {return ORG_V;} - float getORG_H() {return ORG_H;} - float getORG_D() {return ORG_D;} - int getDIM_V() {return DIM_V;} - int getDIM_H() {return DIM_H;} - int getDIM_D() {return DIM_D;} - int getABS_V(int ABS_PIXEL_V) {return iim::round( ORG_V * 1000 + ABS_PIXEL_V*this->getVXL_V());} - int getABS_H(int ABS_PIXEL_H) {return iim::round( ORG_H * 1000 + ABS_PIXEL_H*this->getVXL_H());} - int getABS_D(int ABS_PIXEL_D) {return iim::round( ORG_D * 1000 + ABS_PIXEL_D*this->getVXL_D());} - float getVXL_V() {return VXL_V;} - float getVXL_H() {return VXL_H;} - float getVXL_D() {return VXL_D;} - int getDIM_C() {return DIM_C;} - int getDIM_T() {return DIM_T;} //@ADDED by Alessandro on 2014-02-18 - int getBYTESxCHAN() {return BYTESxCHAN;} - char* getROOT_DIR() {return this->root_dir;} - virtual float getMVoxels(){return (DIM_V/1024.0f)*(DIM_H/1024.0f)*DIM_D*DIM_T;} // can be overriden - int getNActiveFrames(){return t1 -t0 +1;} - virtual int getNACtiveChannels() {return n_active;} - virtual iim::uint32* getActiveChannels(){return active;} - - // @ADDED by Alessandro on 2014-02-18: returns a unique ID that identifies the volume format - virtual std::string getPrintableFormat() = 0; - - // @ADDED by Alessandro on 2014-02-18: additional info on the reference system (where available) - virtual float getVXL_1() = 0; - virtual float getVXL_2() = 0; - virtual float getVXL_3() = 0; - virtual iim::axis getAXS_1() = 0; - virtual iim::axis getAXS_2() = 0; - virtual iim::axis getAXS_3() = 0; - - // set active channels (@MOVED from TileMCVolume.h by Alessandro on 2014-02-20) - virtual void setActiveChannels ( iim::uint32 *_active, int _n_active ); - - // set methods (@MOVED from TimeSeries.h by Alessandro on 2014-02-20) - void setActiveFrames(int _t0, int _t1) - { - t0 = std::max(0, std::min(_t0,DIM_T-1)); - t1 = std::max(0, std::min(_t1,DIM_T-1)); - iim::debug(iim::LEV_MAX, iim::strprintf("asked to set [%d, %d], but set [%d, %d]", _t0, _t1, t0, t1).c_str(), __iim__current__function__); - } - - /************************************************************************************************************* - * Save image method. <> parameters are mandatory, while [] are optional. - * : absolute path of image to be saved. It DOES NOT include its extension, which is - * provided by the [img_format] parameter. - * : image to be saved. Raw data is in [0,1] and it is stored row-wise in a 1D array. - * : dimensions of raw_img. - * [start/end_height/width] : optional ROI (region of interest) to be set on the given image. - * [img_format] : image format extension to be used (e.g. "tif", "png", etc.) - * [img_depth] : image bitdepth to be used (8 or 16) - **************************************************************************************************************/ - static void saveImage(std::string img_path, iim::real32* raw_img, int raw_img_height, int raw_img_width, - int start_height = 0, int end_height = - 1, int start_width = 0, int end_width = - 1, - const char* img_format = iim::DEF_IMG_FORMAT.c_str(), int img_depth = iim::DEF_IMG_DEPTH ) - throw (iim::IOException); - - /************************************************************************************************************* - * Save image method from iim::uint8 raw data. <> parameters are mandatory, while [] are optional. - * : absolute path of image to be saved. It DOES NOT include its extension, which is - * provided by the [img_format] parameter. - * : raw data of the first channel with values in [0,255]. - * For grayscale images this is the pointer to the raw image data. - * For colour images this is the pointer to the raw image data of the RED channel. - * : raw data of the second channel with values in [0,255]. - * For grayscale images this should be a null pointer. - * For colour images this is the pointer to the raw image data of the GREEN channel. - * : raw data of the second channel with values in [0,255]. - * For grayscale images this should be a null pointer. - * For colour images this is the pointer to the raw image data of the BLUE channel. - * : dimensions of raw_img. - * [start/end_height/width] : optional ROI (region of interest) to be set on the given image. - * [img_format] : image format extension to be used (e.g. "tif", "png", etc.) - * [img_depth] : image bitdepth to be used (8 or 16) - * - * WARNING: this method is intended to be used to save one slice into a file using a 2D format (i.e. a 2D plugin) - * use saveImage_from_UINT8_to_Tiff3D to append one slice to a file storing images in 3D format - **************************************************************************************************************/ - static void saveImage_from_UINT8 (std::string img_path, - iim::uint8* raw_ch1, iim::uint8* raw_ch2, iim::uint8* raw_ch3, - int raw_img_height, int raw_img_width, - int start_height=0, int end_height =-1, int start_width=0, int end_width=-1, - const char* img_format = iim::DEF_IMG_FORMAT.c_str(), int img_depth = iim::DEF_IMG_DEPTH ) throw (iim::IOException); - - - /************************************************************************************************************* - * Save image method to Vaa3D raw format. <> parameters are mandatory, while [] are optional. - * : absolute path of image to be saved. It DOES NOT include its extension, which is - * provided by the [img_format] parameter. - * : image to be saved. Raw data is in [0,1] and it is stored row-wise in a 1D array. - * : dimensions of raw_img. - * [start/end_height/width] : optional ROI (region of interest) to be set on the given image. - * [img_format] : image format extension to be used (e.g. "tif", "png", etc.) - * [img_depth] : image bitdepth to be used (8 or 16) - **************************************************************************************************************/ - static void saveImage_to_Vaa3DRaw(int slice, std::string img_path, iim::real32* raw_img, int raw_img_height, int raw_img_width, - int start_height = 0, int end_height = - 1, int start_width = 0, int end_width = - 1, - const char* img_format = iim::DEF_IMG_FORMAT.c_str(), int img_depth = iim::DEF_IMG_DEPTH - ) - throw (iim::IOException); - - /************************************************************************************************************* - * Save image method from iim::uint8 raw data to Vaa3D raw format. <> parameters are mandatory, while [] are optional. - * : absolute path of image to be saved. It DOES NOT include its extension, which is - * provided by the [img_format] parameter. - * : array of pointers to raw data of the channels with values in [0,255]. - * For grayscale images raw_ch[0] is the pointer to the raw image data. - * For colour images raw_ch[0] is the pointer to the raw image data of the RED channel. - * : number of channels (length of raw_ch). - * : offset to be added to raw_ch[i] to get actual data - * : dimensions of raw_img. - * [start/end_height/width] : optional ROI (region of interest) to be set on the given image. - * [img_format] : image format extension to be used (e.g. "tif", "png", etc.) - * [img_depth] : image bitdepth to be used (8 or 16) - **************************************************************************************************************/ - static void saveImage_from_UINT8_to_Vaa3DRaw (int slice, std::string img_path, - iim::uint8** raw_ch, int n_chans, iim::sint64 offset, - int raw_img_height, int raw_img_width, - int start_height=0, int end_height =-1, int start_width=0, int end_width=-1, - const char* img_format = iim::DEF_IMG_FORMAT.c_str(), int img_depth = iim::DEF_IMG_DEPTH ) throw (iim::IOException); - - - - /************************************************************************************************************* - * Save image method from iim::uint8 raw data to Tiff 3D (multipage) format. <> parameters are mandatory, while [] are optional. - * : absolute path of image to be saved. It DOES NOT include its extension, which is - * provided by the [img_format] parameter. - * : array of pointers to raw data of the channels with values in [0,255]. - * For grayscale images raw_ch[0] is the pointer to the raw image data. - * For colour images raw_ch[0] is the pointer to the raw image data of the RED channel. - * : number of channels (length of raw_ch). - * : offset to be added to raw_ch[i] to get actual data - * : dimensions of raw_img. - * [start/end_height/width] : optional ROI (region of interest) to be set on the given image. - * [img_format] : image format extension to be used (e.g. "tif", "png", etc.) - * [img_depth] : image bitdepth to be used (8 or 16) - * [fhandle] : handle to the (open) file which image has to be appended (used only if do_open = false) - * [n_pages] : total number of slice to be appended to the file (used only if do_open = false) - * [do_open] : if true img_path has to be used to open the file which is closed after the image has been appended - * if false the image is appended without opening the file which is left open - **************************************************************************************************************/ - // WARNING: current implementation could not work if the slice is not appended after the last one - // in other words the multipage file should have exactly (slice-1) pages - static void saveImage_from_UINT8_to_Tiff3D (int slice, std::string img_path, - iim::uint8** raw_ch, int n_chans, iim::sint64 offset, - int raw_img_height, int raw_img_width, - int start_height=0, int end_height =-1, int start_width=0, int end_width=-1, - const char* img_format = iim::DEF_IMG_FORMAT.c_str(), int img_depth = iim::DEF_IMG_DEPTH, - void *fhandle = 0, int n_pages = -1, bool do_open = true ) throw (iim::IOException); - - /************************************************************************************************************* - * Performs downsampling at a halved frequency on the given 3D image. The given image is overwritten in order - * to store its halvesampled version without allocating any additional resources. - * - * WARNING: Since the downsampling is carried out for more slices, a stride is introduced between downsampled - * slices. The stride introduced is (height*width) - **************************************************************************************************************/ - static void halveSample( iim::real32* img, int height, int width, int depth, int method = HALVE_BY_MEAN ); - - static void halveSample_UINT8 ( iim::uint8** img, int height, int width, int depth, int channels, int method = HALVE_BY_MEAN, int bytes_chan = 1 ); - - //utility function: returns true if "fullString" ends with "ending" - inline static bool hasEnding (std::string const &fullString, std::string const &ending) - { - if (fullString.length() >= ending.length()) - return (0 == fullString.compare (fullString.length() - ending.length(), ending.length(), ending)); - else - return false; - } - - // tries to automatically detect the volume format and returns the imported volume if succeeds (otherwise returns 0) - // WARNING: all metadata files (if needed by that format) are assumed to be present. Otherwise, that format will be skipped. - static VirtualVolume* instance(const char* path) throw (iim::IOException); - - // should be used to instantiate BDV HDF5 volumes - static VirtualVolume* instance(const char* fname, int res, void *descr) throw (iim::IOException); - - // returns the imported volume if succeeds (otherwise returns 0) - // WARNING: no assumption is made on metadata files, which are possibly (re-)generated using the additional informations provided. - static VirtualVolume* instance(const char* path, std::string format, - iim::axis AXS_1 = iim::axis_invalid, iim::axis AXS_2 = iim::axis_invalid, iim::axis AXS_3 = iim::axis_invalid, - float VXL_1=0.0f, float VXL_2=0.0f, float VXL_3=0.0f) throw (iim::IOException); - - // 2015-04-14. Alessandro. @ADDED 'instance_format' method with inputs = {path, format}. - static VirtualVolume* instance_format(const char* path, std::string format) throw (iim::IOException); - - // checks whether the volume stored in "path" can be imported directly (i.e., w/o additional metadata provided by the user) - static bool isDirectlyImportable(const char* path) - { - /**/iim::debug(iim::LEV3, iim::strprintf("path = \"%s\"", path).c_str(), __iim__current__function__); - - VirtualVolume* vol = 0; - try{vol = instance(path);} - catch(iim::IOException &ex){/**/iim::debug(iim::LEV3, iim::strprintf("error = %s", ex.what()).c_str(), __iim__current__function__);} - catch(...){} - bool result = vol != 0; - delete vol; - return result; - } - - // returns true if the given format is hierarchical, i.e. if it consists of nested folders (1 level at least) - static bool isHierarchical(std::string format) throw (iim::IOException); -}; - -#endif diff --git a/v3d_main/terafly/src/core/imagemanager/dirent_win.h b/v3d_main/terafly/src/core/imagemanager/dirent_win.h deleted file mode 100644 index 6425174092..0000000000 --- a/v3d_main/terafly/src/core/imagemanager/dirent_win.h +++ /dev/null @@ -1,230 +0,0 @@ -/***************************************************************************** - * dirent.h - dirent API for Microsoft Visual Studio - * - * Copyright (C) 2006 Toni Ronkko - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * ``Software''), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL TONI RONKKO BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - * - * Dec 15, 2009, John Cunningham - * Added rewinddir member function - * - * Jan 18, 2008, Toni Ronkko - * Using FindFirstFileA and WIN32_FIND_DATAA to avoid converting string - * between multi-byte and unicode representations. This makes the - * code simpler and also allows the code to be compiled under MingW. Thanks - * to Azriel Fasten for the suggestion. - * - * Mar 4, 2007, Toni Ronkko - * Bug fix: due to the strncpy_s() function this file only compiled in - * Visual Studio 2005. Using the new string functions only when the - * compiler version allows. - * - * Nov 2, 2006, Toni Ronkko - * Major update: removed support for Watcom C, MS-DOS and Turbo C to - * simplify the file, updated the code to compile cleanly on Visual - * Studio 2005 with both unicode and multi-byte character strings, - * removed rewinddir() as it had a bug. - * - * Aug 20, 2006, Toni Ronkko - * Removed all remarks about MSVC 1.0, which is antiqued now. Simplified - * comments by removing SGML tags. - * - * May 14 2002, Toni Ronkko - * Embedded the function definitions directly to the header so that no - * source modules need to be included in the Visual Studio project. Removed - * all the dependencies to other projects so that this very header can be - * used independently. - * - * May 28 1998, Toni Ronkko - * First version. - *****************************************************************************/ -#ifndef DIRENT_H -#define DIRENT_H - -#include -#include -#include - - -typedef struct dirent -{ - char d_name[MAX_PATH + 1]; /* current dir entry (multi-byte char string) */ - WIN32_FIND_DATAA data; /* file attributes */ -} dirent; - - -typedef struct DIR -{ - dirent current; /* Current directory entry */ - int cached; /* Indicates un-processed entry in memory */ - HANDLE search_handle; /* File search handle */ - char patt[MAX_PATH + 3]; /* search pattern (3 = pattern + "\\*\0") */ -} DIR; - - -/* Forward declarations */ -static DIR *opendir (const char *dirname); -static struct dirent *readdir (DIR *dirp); -static int closedir (DIR *dirp); -static void rewinddir(DIR* dirp); - - -/* Use the new safe string functions introduced in Visual Studio 2005 */ -#if defined(_MSC_VER) && _MSC_VER >= 1400 -# define STRNCPY(dest,src,size) strncpy_s((dest),(size),(src),_TRUNCATE) -#else -# define STRNCPY(dest,src,size) strncpy((dest),(src),(size)) -#endif - - -/***************************************************************************** - * Open directory stream DIRNAME for read and return a pointer to the - * internal working area that is used to retrieve individual directory - * entries. - */ -static DIR *opendir(const char *dirname) -{ - DIR *dirp; - assert (dirname != NULL); - assert (strlen (dirname) < MAX_PATH); - - /* construct new DIR structure */ - dirp = (DIR*) malloc (sizeof (struct DIR)); - if (dirp != NULL) { - char *p; - - /* take directory name... */ - STRNCPY (dirp->patt, dirname, sizeof(dirp->patt)); - dirp->patt[MAX_PATH] = '\0'; - - /* ... and append search pattern to it */ - p = strchr (dirp->patt, '\0'); - if (dirp->patt < p && *(p-1) != '\\' && *(p-1) != ':') { - *p++ = '\\'; - } - *p++ = '*'; - *p = '\0'; - - /* open stream and retrieve first file */ - dirp->search_handle = FindFirstFileA (dirp->patt, &dirp->current.data); - if (dirp->search_handle == INVALID_HANDLE_VALUE) { - /* invalid search pattern? */ - free (dirp); - return NULL; - } - - /* there is an un-processed directory entry in memory now */ - dirp->cached = 1; - } - - return dirp; -} - - -/***************************************************************************** - * Read a directory entry, and return a pointer to a dirent structure - * containing the name of the entry in d_name field. Individual directory - * entries returned by this very function include regular files, - * sub-directories, pseudo-directories "." and "..", but also volume labels, - * hidden files and system files may be returned. - */ -static struct dirent *readdir(DIR *dirp) -{ - assert (dirp != NULL); - - if (dirp->search_handle == INVALID_HANDLE_VALUE) { - /* directory stream was opened/rewound incorrectly or ended normally */ - return NULL; - } - - /* get next directory entry */ - if (dirp->cached != 0) { - /* a valid directory entry already in memory */ - dirp->cached = 0; - } else { - /* read next directory entry from disk */ - if (FindNextFileA (dirp->search_handle, &dirp->current.data) == FALSE) { - /* the very last file has been processed or an error occured */ - FindClose (dirp->search_handle); - dirp->search_handle = INVALID_HANDLE_VALUE; - return NULL; - } - } - - /* copy as a multibyte character string */ - STRNCPY ( dirp->current.d_name, - dirp->current.data.cFileName, - sizeof(dirp->current.d_name) ); - dirp->current.d_name[MAX_PATH] = '\0'; - - return &dirp->current; -} - - -/***************************************************************************** - * Close directory stream opened by opendir() function. Close of the - * directory stream invalidates the DIR structure as well as any previously - * read directory entry. - */ -static int closedir(DIR *dirp) -{ - assert (dirp != NULL); - - /* release search handle */ - if (dirp->search_handle != INVALID_HANDLE_VALUE) { - FindClose (dirp->search_handle); - dirp->search_handle = INVALID_HANDLE_VALUE; - } - - /* release directory handle */ - free (dirp); - return 0; -} - - -/***************************************************************************** - * Resets the position of the directory stream to which dirp refers to the - * beginning of the directory. It also causes the directory stream to refer - * to the current state of the corresponding directory, as a call to opendir() - * would have done. If dirp does not refer to a directory stream, the effect - * is undefined. - */ -static void rewinddir(DIR* dirp) -{ - /* release search handle */ - if (dirp->search_handle != INVALID_HANDLE_VALUE) { - FindClose (dirp->search_handle); - dirp->search_handle = INVALID_HANDLE_VALUE; - } - - /* open new search handle and retrieve first file */ - dirp->search_handle = FindFirstFileA (dirp->patt, &dirp->current.data); - if (dirp->search_handle == INVALID_HANDLE_VALUE) { - /* invalid search pattern? */ - free (dirp); - return; - } - - /* there is an un-processed directory entry in memory now */ - dirp->cached = 1; -} - - -#endif /*DIRENT_H*/ diff --git a/v3d_main/terafly/src/core/imagemanager/imBlock.cpp b/v3d_main/terafly/src/core/imagemanager/imBlock.cpp deleted file mode 100644 index 7aa488c9b1..0000000000 --- a/v3d_main/terafly/src/core/imagemanager/imBlock.cpp +++ /dev/null @@ -1,495 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -* 2014-11-22 Giulio. @CHANGED code using OpenCV has been commente. It can be found searching comments containing 'Giulio_CV' -*/ - -#include "imBlock.h" -#include "VirtualVolume.h" -#include "VirtualFmtMngr.h" -//#include "RawFmtMngr.h" -// Giulio_CV #include -// Giulio_CV #include -#ifdef _WIN32 -#include "dirent_win.h" -#else -#include -#endif -#include -#include - -// 140427_IANNELLO -#ifdef min -#undef min -#endif - -#ifdef max -#undef max -#endif - -// Giulio_CV #include - -//2014-11-21 Giulio. @ADDED MIN, MAX macros -#ifndef MIN -#define MIN(a,b) ((a)<(b) ? (a) : (b)) -#endif -#ifndef MAX -#define MAX(a,b) ((a)>(b) ? (a) : (b)) -#endif - - -using namespace std; -using namespace iim; - -Block::Block(VirtualVolume* _CONTAINER, int _ROW_INDEX, int _COL_INDEX, char* _DIR_NAME) -{ - /**/iim::debug(iim::LEV3, strprintf("_ROW_INDEX=%d, _COL_INDEX=%d, _DIR_NAME=%s", _ROW_INDEX, _COL_INDEX, _DIR_NAME).c_str(), __iim__current__function__); - - this->CONTAINER = _CONTAINER; - - this->DIR_NAME = new char[strlen(_DIR_NAME)+1]; - strcpy(this->DIR_NAME, _DIR_NAME); - - this->ROW_INDEX = _ROW_INDEX; - this->COL_INDEX = _COL_INDEX; - - FILENAMES = NULL; - HEIGHT = WIDTH = DEPTH = 0; - N_BLOCKS = 0; - N_CHANS = 0; - N_BYTESxCHAN = 0; - ABS_V = ABS_H = 0; - BLOCK_SIZE = 0; - BLOCK_ABS_D = 0; - - init(); -} - -Block::Block(VirtualVolume* _CONTAINER, int _ROW_INDEX, int _COL_INDEX, FILE* bin_file) throw (IOException) -{ - /**/iim::debug(iim::LEV3, strprintf("_ROW_INDEX=%d, _COL_INDEX=%d", _ROW_INDEX, _COL_INDEX).c_str(), __iim__current__function__); - - CONTAINER = _CONTAINER; - ROW_INDEX = _ROW_INDEX; - COL_INDEX = _COL_INDEX; - - DIR_NAME = NULL; - FILENAMES = NULL; - HEIGHT = WIDTH = DEPTH = 0; - N_BLOCKS = 0; - N_CHANS = 0; - N_BYTESxCHAN = 0; - ABS_V = ABS_H = 0; - BLOCK_SIZE = 0; - BLOCK_ABS_D = 0; - - unBinarizeFrom(bin_file); - - //initializing STACKED_IMAGE array - //this->STACKED_IMAGE = new CvMat*[DEPTH]; - //for(uint32 z=0; zSTACKED_IMAGE[z] = NULL; -} - -Block::~Block(void) -{ - /**/iim::debug(iim::LEV3, strprintf("ROW_INDEX=%d, COL_INDEX=%d", ROW_INDEX, COL_INDEX).c_str(), __iim__current__function__); - - if (BLOCK_SIZE) - delete[] BLOCK_SIZE; - if (BLOCK_ABS_D) - delete[] BLOCK_ABS_D; - - for(uint32 z=0; z entries_lev3; - string entry; - - //building filenames_list - char abs_path[STATIC_STRINGS_SIZE]; - sprintf(abs_path,"%s/%s", CONTAINER->getROOT_DIR(), DIR_NAME); - cur_dir_lev3 = opendir(abs_path); - if (!cur_dir_lev3) - { - char errMsg[STATIC_STRINGS_SIZE]; - sprintf(errMsg, "in Block::init(): can't open directory \"%s\"", abs_path); - throw IOException(errMsg); - } - - //scanning third level of hierarchy which entries need to be ordered alphabetically. This is done using STL. - while ((entry_lev3=readdir(cur_dir_lev3))) - { - tmp = entry_lev3->d_name; - if(tmp.compare(".") != 0 && tmp.compare("..") != 0 && tmp.find(".") != string::npos) - entries_lev3.push_back(tmp); - } - entries_lev3.sort(); - N_BLOCKS = (int)entries_lev3.size(); - - //----- Alessandro added on August 12, 2013 - //----- Bug fixed: exceeding the maximum number of directories opened at the same time - closedir(cur_dir_lev3); - - //checking if current stack is not empty - if(N_BLOCKS == 0) - { - char msg[1000]; - sprintf(msg,"in Block[%d,%d]::init(): stack in \"%s\" is empty", ROW_INDEX, COL_INDEX, abs_path); - throw IOException(msg); - } - - //converting filenames_list (STL list of C-strings) into FILENAMES (1-D array of C-strings) - FILENAMES = new char*[N_BLOCKS]; - for(uint32 z=0; zgetROOT_DIR(), DIR_NAME, FILENAMES[0]); - - //if ( (err_rawfmt = loadRaw2Metadata(slice_fullpath,sz,datatype,b_swap,dummy,header_len)) != 0 ) { - if ( (err_rawfmt = fmtMngr->loadMetadata(slice_fullpath,sz,datatype,b_swap,dummy,header_len)) != 0 ) { - if ( sz ) delete[] sz; - char msg[STATIC_STRINGS_SIZE]; - sprintf(msg,"in Block[%d,%d]::init(): unable to open block \"%s\". Wrong path or format (%s)", - ROW_INDEX, COL_INDEX, slice_fullpath,err_rawfmt); - throw IOException(msg); - } - fmtMngr->closeFile(dummy); - - HEIGHT = (uint32)sz[1]; - WIDTH = (uint32)sz[0]; - N_CHANS = (uint32)sz[3]; - N_BYTESxCHAN = (uint32)datatype; - - //extracting DEPTH and other attributes from all blocks - BLOCK_SIZE = new uint32[N_BLOCKS]; - BLOCK_ABS_D = new int[N_BLOCKS]; - - BLOCK_ABS_D[0] = 0; - DEPTH = BLOCK_SIZE[0] = (uint32)sz[2]; - for ( int ib=1; ib<(int)N_BLOCKS; ib++ ) { - sprintf(slice_fullpath, "%s/%s/%s", CONTAINER->getROOT_DIR(), DIR_NAME, FILENAMES[ib]); - if ( (err_rawfmt = fmtMngr->loadMetadata(slice_fullpath,sz,datatype,b_swap,dummy,header_len)) != 0 ) { - if ( sz ) delete[] sz; - char msg[STATIC_STRINGS_SIZE]; - sprintf(msg,"in Block[%d,%d]::init(): unable to open block \"%s\". Wrong path or format (%s)", - ROW_INDEX, COL_INDEX, slice_fullpath,err_rawfmt); - throw IOException(msg); - } - fmtMngr->closeFile((FILE *)dummy); - - BLOCK_SIZE[ib] = (uint32)sz[2]; - BLOCK_ABS_D[ib] = DEPTH; - DEPTH += BLOCK_SIZE[ib]; - } - - delete fmtMngr; - - delete[] sz; -} - -string Block::getFMT ( ) { - string ffmt; - char *temp = FILENAMES[0]+strlen(FILENAMES[0])-3; - if ( strcmp(temp,"tif")==0 ) - ffmt = "Tiff3D"; - else if ( strcmp(temp,"raw")==0 ) - ffmt = "Vaa3DRaw"; - else { - char msg[STATIC_STRINGS_SIZE]; - sprintf(msg,"in Block::getFMT(...): Unknown file format \"%s\"", temp); - throw IOException(msg); - } - - return ffmt; -} - -//PRINT method -void Block::print() -{ - printf("\t |\t[%d,%d]\n", ROW_INDEX, COL_INDEX); - printf("\t |\tDirectory:\t\t%s\n", DIR_NAME); - printf("\t |\tDimensions:\t\t%d(V) x %d(H) x %d(D)\n", HEIGHT, WIDTH, DEPTH); - printf("\t |\tNumber of blocks:\t\t%d\n", N_BLOCKS); - printf("\t |\tNumber of channels:\t\t%d\n", N_CHANS); - printf("\t |\tNumber of bytes per channel:\t\t%d\n", N_BYTESxCHAN); - printf("\t |\tAbsolute position:\t%d(V) x %d(H) x %d(D)\n", ABS_V, ABS_H, 0); - /*printf("\t |\tFilenames:\t\n"); - for(int z=0; z ABS_H && - area.V0 < (int)(ABS_V + HEIGHT) && - area.V1 > ABS_V ); - - //if intersection occurs, computing intersection area, otherwise returning NULL - if(intersects) - { - Rect_t *intersect_rect = new Rect_t; - intersect_rect->H0 = MAX(ABS_H, area.H0); - intersect_rect->V0 = MAX(ABS_V, area.V0); - intersect_rect->H1 = MIN((int)(ABS_H + WIDTH), area.H1); - intersect_rect->V1 = MIN((int)(ABS_V + HEIGHT), area.V1); - - return intersect_rect; - } - else - return NULL; -} - - -Segm_t* Block::Intersects(int D0, int D1) { - - if ( D0 >= BLOCK_ABS_D[N_BLOCKS-1]+(int)(BLOCK_SIZE[N_BLOCKS-1]) || D1 <= 0 ) // GI_141110: added '=' (D1 is the last slice + 1) - // there is no intersection - return NULL; - - bool found0, found1; - int i0, i1; - - found0 = false; - i0 = 0; - while ( i0<(int)(N_BLOCKS-1) && !found0 ) - if ( D0 < BLOCK_ABS_D[i0+1] ) - found0 = true; - else - i0++; - // !found0 -> i0 = N_BLOCKS-1 - - found1 = false; - i1 = (int)(N_BLOCKS-1); - while ( i1>0 && !found1 ) - if ( D1 > BLOCK_ABS_D[i1] ) // GI_140507: deleted '=' - found1 = true; - else - i1--; - // !found1 -> i1 = 0 - - Segm_t *intersect_segm = new Segm_t; - intersect_segm->D0 = MAX(D0,0); - intersect_segm->D1 = MIN(D1,(int)DEPTH); - intersect_segm->ind0 = i0; - intersect_segm->ind1 = i1; - - return intersect_segm; -} diff --git a/v3d_main/terafly/src/core/imagemanager/imBlock.h b/v3d_main/terafly/src/core/imagemanager/imBlock.h deleted file mode 100644 index 0541b2d6ed..0000000000 --- a/v3d_main/terafly/src/core/imagemanager/imBlock.h +++ /dev/null @@ -1,108 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -#ifndef _IIM_BLOCK_H -#define _IIM_BLOCK_H - -#include -#include -#include "IM_config.h" -#include "VirtualVolume.h" - -//FORWARD-DECLARATIONS -//class iim::VirtualVolume; - -//TYPE DEFINITIONS -//typedef struct {int V0, V1, H0, H1;} Rect_t; -typedef struct {int D0, D1, ind0, ind1;} Segm_t; - -class iim::Block -{ - private: - - //*********** OBJECT ATTRIBUTES *********** - iim::VirtualVolume* CONTAINER; //pointer to object that contains the current object - char** FILENAMES; //1-D dinamic array of pointers to blocks filanames - iim::uint32 HEIGHT, WIDTH, DEPTH; //VHD (Vertical, Horizontal, Depth) dimensions of current stack - iim::uint32 N_BLOCKS; //number of blocks along z - iim::uint32 N_CHANS; //number of channels - iim::uint32 N_BYTESxCHAN; //number of bytes per channel - int ROW_INDEX, COL_INDEX; //row and col index relative to stack matrix - int ABS_V, ABS_H; //absolute VH voxel coordinates of current stack - iim::uint32 *BLOCK_SIZE; //dimensions of blocks along z - int *BLOCK_ABS_D; //absolute D voxel coordinates of blocks - char* DIR_NAME; //string containing current stack directory - - //******** OBJECT PRIVATE METHODS ********* - Block(void); - - //Initializes all object's members given DIR_NAME - void init(); - - public: - - Block(iim::VirtualVolume* _CONTAINER, int _ROW_INDEX, int _COL_INDEX, FILE* bin_file) throw (iim::IOException); - Block(iim::VirtualVolume* _CONTAINER, int _ROW_INDEX, int _COL_INDEX, char* _DIR_NAME); - ~Block(void); - - //GET methods - char* getDIR_NAME() {return DIR_NAME;} - int getROW_INDEX() {return ROW_INDEX;} - int getCOL_INDEX() {return COL_INDEX;} - iim::uint32 getHEIGHT() {return HEIGHT;} - iim::uint32 getWIDTH() {return WIDTH;} - iim::uint32 getDEPTH() {return DEPTH;} - iim::uint32 getN_BLOCKS() {return N_BLOCKS;} - iim::uint32 getN_CHANS() {return N_CHANS;} - iim::uint32 getN_BYTESxCHAN() {return N_BYTESxCHAN;} - int getABS_V() {return ABS_V;} - int getABS_H() {return ABS_H;} - iim::uint32 *getBLOCK_SIZE() {return BLOCK_SIZE;} - int *getBLOCK_ABS_D() {return BLOCK_ABS_D;} - char** getFILENAMES() {return FILENAMES;} - std::string getFMT(); - - //SET methods - void setROW_INDEX(int _ROW_INDEX){ROW_INDEX = _ROW_INDEX;} - void setCOL_INDEX(int _COL_INDEX){COL_INDEX = _COL_INDEX;} - void setABS_V (int _ABS_V) {ABS_V = _ABS_V; } - void setABS_H (int _ABS_H) {ABS_H = _ABS_H; } - - //PRINT method - void print(); - - //binarizing-unbinarizing methods - void binarizeInto(FILE* file); - void unBinarizeFrom(FILE* file) throw (iim::IOException); - - //returns a pointer to the intersection rectangle if the given area intersects current stack, otherwise returns NULL - Rect_t* Intersects(const Rect_t& area); - - //returns a pointer to the intersection segment (along D) if the given segment (D0,D1-1) intersects current stack, otherwise returns NULL - //D0 first index of the segment - //D1 last index of the segment + 1 - Segm_t* Intersects(int D0, int D1); -}; - -#endif //_BLOCK_H diff --git a/v3d_main/terafly/src/core/imagemanager/imProgressBar.cpp b/v3d_main/terafly/src/core/imagemanager/imProgressBar.cpp deleted file mode 100644 index 7f282de05a..0000000000 --- a/v3d_main/terafly/src/core/imagemanager/imProgressBar.cpp +++ /dev/null @@ -1,136 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -#include "ProgressBar.h" -#include -#include -#include -#include - -#ifdef _VAA3D_TERAFLY_PLUGIN_MODE -#include "PConverter.h" -#include "PMain.h" -#endif - - -/********************************************************************************** -* Singleton design pattern: this class can have one instance only, which must be -* instantiated by calling static method "istance(...)" -***********************************************************************************/ -iim::imProgressBar* iim::imProgressBar::uniqueInstance = 0; -iim::imProgressBar* iim::imProgressBar::instance() -{ - if (uniqueInstance == 0) - uniqueInstance = new imProgressBar(); - uniqueInstance = new imProgressBar(); - return uniqueInstance; -} - -iim::imProgressBar::imProgressBar() -{ - reset(); -} - - -void iim::imProgressBar::reset() -{ - strcpy(this->message_level_1, ""); - strcpy(this->message_level_2, ""); - strcpy(this->message_level_3, ""); - progress_value=0; - proctime = 0; - minutes_remaining = 0; - seconds_remaining = 0; -} - - -void iim::imProgressBar::start(const char *new_operation_desc, bool toConverter /* = true */) -{ - strcpy(this->message_level_2, new_operation_desc); - this->progress_value=0; - strcpy(this->message_level_3, ""); - proctime = -TIME(0); - minutes_remaining = 0; - seconds_remaining = 0; - - #ifdef _VAA3D_TERAFLY_PLUGIN_MODE - int progress_value_int = (int) progress_value; - if(toConverter) - teramanager::PConverter::instance()->emitProgressBarChanged(progress_value_int, 0, 0, new_operation_desc); - else - teramanager::PMain::getInstance()->emitProgressBarChanged(progress_value_int, 0, 0, message_level_1); - #endif -} - -void iim::imProgressBar::update(float new_progress_value, const char* new_progress_info) -{ - progress_value=new_progress_value; - strcpy(message_level_3,new_progress_info); - - if(new_progress_value!=0) - { - minutes_remaining = (int)((proctime + TIME(0))*(100.0-progress_value)/(progress_value*60.0)); - seconds_remaining = (int)((proctime + TIME(0))*(100.0-progress_value)/(progress_value)); - } -} - - -void iim::imProgressBar::updateInfo(const char* new_progress_info) -{ - strcpy(message_level_3,new_progress_info); -} - -void iim::imProgressBar::show(bool toConverter /* = true */) -{ - #ifdef _VAA3D_TERAFLY_PLUGIN_MODE - int progress_value_int = (int) (progress_value+0.5f); - if(toConverter) - teramanager::PConverter::instance()->emitProgressBarChanged(progress_value_int, minutes_remaining, seconds_remaining%60, message_level_1); - else - teramanager::PMain::getInstance()->emitProgressBarChanged(progress_value_int, minutes_remaining, seconds_remaining%60, message_level_1); - #else - int dummy = system_CLEAR(); - printf("OPERATION:\t%s\n",this->message_level_1); // 140427_IANNELLO - printf("PHASE:\t\t%s\n",this->message_level_2); // 140427_IANNELLO - printf("TIME REMAINING:\t%d minutes and %d seconds\n", minutes_remaining, seconds_remaining%60); - printf("PROGRESS:\t"); - printf("%d%%\t",(int)(progress_value)); - for(int i=1; i<=progress_value; i++) - printf("*"); - for(int i=(int)progress_value; i<100; i++) - printf(":"); - printf("\n\n"); - #endif -} - - -void iim::imProgressBar::setMessage(int level, const char* message) -{ - if(level == 1) - strcpy(message_level_1,message); - else if(level == 2) - strcpy(message_level_2,message); - else if(level == 3) - strcpy(message_level_3,message); -} diff --git a/v3d_main/terafly/src/core/iomanager/CMakeLists.txt b/v3d_main/terafly/src/core/iomanager/CMakeLists.txt deleted file mode 100644 index 865bf40b0a..0000000000 --- a/v3d_main/terafly/src/core/iomanager/CMakeLists.txt +++ /dev/null @@ -1,62 +0,0 @@ -# CmakeLists.txt in iomanager dir - -# add used modules to include path -include_directories (${TeraStitcher_SOURCE_DIR}/imagemanager) - -# find plugins -SUBDIRLIST(SUBDIRS ${CMAKE_CURRENT_SOURCE_DIR}/plugins) - -# ask for selection of the plugins to be included in the project -# tiff2D and tiff3D are mandatory, thus they are set to ON by default -FOREACH(subdir ${SUBDIRS}) - if(subdir STREQUAL "tiff2D" OR subdir STREQUAL "tiff3D") - option (WITH_IO_PLUGIN_${subdir} "Include this plugin (mandatory) in the project" ON) - else() - option (WITH_IO_PLUGIN_${subdir} "Include this plugin (optional) in the project" OFF) - endif() -ENDFOREACH() - -# check if tiff2D and tiff3D are selected. If they are not, an error is thrown -if(NOT WITH_IO_PLUGIN_tiff2D) - message(SEND_ERROR "You cannot deselect plugin tiff2D (mandatory)") -endif() -if(NOT WITH_IO_PLUGIN_tiff3D) - message(SEND_ERROR "You cannot deselect plugin tiff3D (mandatory)") -endif() - -# check if opencv2D is selected. If it's not, we hide the OpenCV_DIR variable from the GUI -if(NOT WITH_IO_PLUGIN_opencv2D) - set ( OpenCV_DIR CACHE INTERNAL "not set" FORCE ) -endif() - -# include selected plugins only -FOREACH(subdir ${SUBDIRS}) - if(WITH_IO_PLUGIN_${subdir}) - message(STATUS "Include I/O plugin " "${subdir} ...") - add_subdirectory(plugins/${subdir}) - message(STATUS "Include I/O plugin " "${subdir} ... OK!") - endif(WITH_IO_PLUGIN_${subdir}) -ENDFOREACH() - -# create header that includes all plugin headers (assuming they are are named like their plugin directory) -file(WRITE ioplugins.h "// Include plugins headers\n") -FOREACH(subdir ${SUBDIRS}) - if(WITH_IO_PLUGIN_${subdir}) - file(APPEND ioplugins.h "#include \"plugins/${subdir}/${subdir}.h\"\n") - endif(WITH_IO_PLUGIN_${subdir}) -ENDFOREACH() - -# add STATIC library from the all .h and .cpp files -file(GLOB iomanager_headers *.h) -file(GLOB iomanager_sources *.cpp) -add_library(iomanager STATIC ${iomanager_headers} ${iomanager_sources} ${plugin_headers} ${plugin_sources}) - -# link with the selected plugins -FOREACH(subdir ${SUBDIRS}) - if(WITH_IO_PLUGIN_${subdir}) - target_link_libraries(iomanager ioplugin_${subdir}) - endif(WITH_IO_PLUGIN_${subdir}) -ENDFOREACH() - -# link with other dependencies -target_link_libraries(iomanager imagemanager ) diff --git a/v3d_main/terafly/src/core/iomanager/IOPluginAPI.h b/v3d_main/terafly/src/core/iomanager/IOPluginAPI.h deleted file mode 100644 index a2cb2e07b9..0000000000 --- a/v3d_main/terafly/src/core/iomanager/IOPluginAPI.h +++ /dev/null @@ -1,659 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* -* Bria, A., Iannello, G., "TeraStitcher - A Tool for Fast 3D Automatic Stitching of Teravoxel-sized Microscopy Images", (2012) BMC Bioinformatics, 13 (1), art. no. 316. -* -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -#ifndef _IOM_IMAGE_FORMAT_H -#define _IOM_IMAGE_FORMAT_H - -/************************************************************************************************ -* General information -* -* Different plugins are available for managing 2D image formats and 3D image formats. -* Nevertheless 3D plugins may occasionally manage images which third dimension is a -* singleton. -* -* All plugins are assumed to manage images that can be in compressed format. -* In case of 3D plugins it is assumed that the image format can extract efficiently 2D slices -* from files containing 3D images (e.g. multi-page tiff format). -* -* Plugins can manage multi-channel images in two ways: interleaving channels (i.e. channels are -* the first dimension) or splitting channels (i.e. channels are the last dimension). -* Plugins inform client code on how channels are managed through the method 'isChansInterleaved', -* returning true if channels are interleaved, false if they are splitted. -* Client code must check which representation is used and correctly process image data returned -* by the 'read' methods, as well as pass image data to write methods in the right format. -* -* Intervals used to specify ROIs refer to pixel indices and do not include the upper limit, -* i.e. the interval [x0,x1) includes the (x1-x0) indices from x0 to x1-1, included. -*************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -* 2015-01-02. Giulio. @ADDED new plugins interface -*/ - -#include -#include -#include "iomanager.config.h" - -// top-level image i/o plugin -class iomanager::IOPlugin -{ - public: - - double time_IO; //time employed in Input/Output - double time_conversions; //time employed in converting raw data to/from image data - - IOPlugin() : time_IO(0), time_conversions(0){} - - // return plugin description - virtual std::string desc() = 0; -}; - - - -// abstract 2Dimage-based IO plugin: a new plugin should implement just its abstract methods (see exampleplugin2D) -class iomanager::IOPlugin2D : public iomanager::IOPlugin -{ - public: - - /************************************************************************************************ - * Read image metadata from a 2D file - *************************************************************************************************/ - virtual void - readMetadata( - std::string img_path, // (INPUT) image filepath - int & img_width, // (OUTPUT) image width (in pixels) - int & img_height, // (OUTPUT) image height (in pixels) - int & img_bytes_x_chan, // (OUTPUT) number of bytes per channel - int & img_chans, // (OUTPUT) number of channels - const std::string & params = iom::IMIN_PLUGIN_PARAMS) // (INPUT) additional parameters - throw (iom::exception) = 0; - - /************************************************************************************************ - * Read 2D image data - * If data in not NULL, parameters img_width, img_height, img_bytes_x_chan, img_chans - * must be passed by the caller otherwise a buffer is internally allocated and the above parameters - * are set with metadata recovered from the image. - * If data in not NULL data must point to a buffer of: - * img_height x img_width x img_bytes_x_chan x img_chans - * bytes. - * In all cases the buffer with read data is returned to the caller. - * Bytes swapping, if needed is performed before returning the buffer filled with the image data - *************************************************************************************************/ - virtual unsigned char * // (OUTPUT) a buffer storing the 2D image - readData( - std::string img_path, // (INPUT) image filepath - int & img_width, // (INPUT/OUTPUT) image width (in pixels) - int & img_height, // (INPUT/OUTPUT) image height (in pixels) - int & img_bytes_x_chan, // (INPUT/OUTPUT) number of bytes per channel - int & img_chans, // (INPUT/OUTPUT) number of channels to be read - unsigned char *data = 0, // (INPUT) image data - const std::string & params = iom::IMIN_PLUGIN_PARAMS) // (INPUT) additional parameters - throw (iom::exception) = 0; - - /************************************************************************************************ - * Write 2D image data into a single (2D) image file - * The ROI specifies a subvolume into the buffer pointed by raw_img which are the only data saved - * into the file. This means that the image actually saved has dimensions: - * (y1-y0) x (x1-x0) - * Default values for ROI limits correspond to the whole buffer. - *************************************************************************************************/ - virtual void - writeData( - std::string img_path, // (INPUT) image filepath (it includes the file extension) - unsigned char *raw_img, // (INPUT) image data to be saved into the file - int img_height, // (INPUT) image height - int img_width, // (INPUT) image width - int img_bytes_x_chan, // (INPUT) number of bytes per channel - int img_chans, // (INPUT) number of channels - int y0 = -1, // (INPUT) region of interest [x0,x1][y0,y1] to be set on the image - int y1 = -1, // (INPUT) region of interest [x0,x1][y0,y1] to be set on the image - int x0 = -1, // (INPUT) region of interest [x0,x1][y0,y1] to be set on the image - int x1 = -1, // (INPUT) region of interest [x0,x1][y0,y1] to be set on the image - const std::string & params = iom::IMOUT_PLUGIN_PARAMS) // (INPUT) additional parameters - throw (iom::exception) = 0; - - /************************************************************************************************ - * Return plugin description - *************************************************************************************************/ - virtual std::string desc() = 0; - - /************************************************************************************************ - * Return if channels are interleaved (in case the image has just one channel return value is - * indefinite) - *************************************************************************************************/ - virtual bool isChansInterleaved() = 0; - - - /************************************************************************************************ - * Methods deprecated - *************************************************************************************************/ - - // read 3D image data from a stack of (2D) image files - virtual iom::real_t* // (OUTPUT) a [0.0,1.0]-valued array storing the 3D image in channel->slice->row order - readData( - char **files, // (INPUT) array of C-strings storing image filenames - int files_size, // (INPUT) size of 'files' - const char *path = 0, // (INPUT) path to be concatenated to the i-th entry of 'files' - int first = -1, // (INPUT) selects a range [first, last] of files to be loaded - int last = -1, // (INPUT) selects a range [first, last] of files to be loaded - bool is_sparse = false, // (INPUT) if true, 'files' is a sparse array and null entries should be treated as empty (black) images - iom::channel chan = CHANS, // (INPUT) channel selection { ALL, R, G, B }. - const std::string & params = iom::IMIN_PLUGIN_PARAMS) // (INPUT) additional parameters - throw (iom::exception) = 0; - - - // write 2D image data into a single (2D) image file - virtual void - writeData( - std::string img_path, // (INPUT) image filepath (it includes the file extension) - iom::real_t *raw_img, // (INPUT) a [0.0,1.0]-valued array storing the 2D image in channel->row order - int img_height, // (INPUT) image height - int img_width, // (INPUT) image width - int img_chans, // (INPUT) number of channels - int y0 = -1, // (INPUT) region of interest [x0,x1][y0,y1] to be set on the image - int y1 = -1, // (INPUT) region of interest [x0,x1][y0,y1] to be set on the image - int x0 = -1, // (INPUT) region of interest [x0,x1][y0,y1] to be set on the image - int x1 = -1, // (INPUT) region of interest [x0,x1][y0,y1] to be set on the image - int bpp = iom::DEF_BPP, // (INPUT) color depth (bits per pixel) - const std::string & params = iom::IMOUT_PLUGIN_PARAMS) // (INPUT) additional parameters - throw (iom::exception) = 0; -}; - - - -// abstract 3D IO plugin: a new plugin should implement just its abstract methods (see ExamplePlugin) -class iomanager::IOPlugin3D : public iomanager::IOPlugin -{ - public: - - /************************************************************************************************ - * Read image metadata from a 3D file - *************************************************************************************************/ - virtual void - readMetadata( - std::string img_path, // (INPUT) image filepath - int & img_width, // (OUTPUT) image width (in pixels) - int & img_height, // (OUTPUT) image height (in pixels) - int & img_depth, // (OUTPUT) image depth (in pixels) - int & img_bytes_x_chan, // (OUTPUT) number of bytes per channel - int & img_chans, // (OUTPUT) number of channels - const std::string & params = iom::IMIN_PLUGIN_PARAMS) // additional parameters - throw (iom::exception) = 0; - - /************************************************************************************************ - * Read 3D image data - * A subset of slices can be specified by parameters z0 and z1. - * Default values correspond to z0 = 0 and z1 = total number o slices in the file. - * If data in not NULL, parameters img_width, img_height, img_depth, img_bytes_x_chan, img_chans - * must be passed by the caller and the data must point to a buffer of - * (img_width * img_height * (z1-z0) * img_bytes_x_chan * img_chans) - * bytes, otherwise a buffer is internally allocated and the above parameters are set with metadata - * recovered from the image. - * In all cases the buffer with read data is returned to the caller. - * Bytes swapping, if needed is performed before returning the buffer filled with the image data - *************************************************************************************************/ - virtual unsigned char * // (OUTPUT) buffer containing the read image data - readData( - std::string img_path, // (INPUT) image filepath - int & img_width, // (INPUT/OUTPUT) image width (in pixels) - int & img_height, // (INPUT/OUTPUT) image height (in pixels) - int & img_depth, // (INPUT/OUTPUT) image depth (in pixels) - int & img_bytes_x_chan, // (INPUT/OUTPUT) number of bytes per channel - int & img_chans, // (INPUT/OUTPUT) number of channels to be read - unsigned char *data = 0, // (INPUT) image data - int z0 = -1, // (INPUT) region of interest [x0,x1)[y0,y1)[z0,z1) to be set on the image - int z1 = -1, // (INPUT) region of interest [x0,x1)[y0,y1)[z0,z1) to be set on the image - const std::string & params = iom::IMIN_PLUGIN_PARAMS) // (INPUT) additional parameters - throw (iom::exception) = 0; - - /************************************************************************************************ - * Write 3D image data into a single (3D) image file - * If there is more than one channel, channel layout must be coherent with the value returned by - * method isChansInterleaved(). - * The ROI specifies a subvolume into the buffer pointed by raw_img which are the only data to be - * saved into the file. This means that the image actually saved has dimensions: - * (z1-z0) x (y1-y0) x (x1-x0) - * Default values for ROI limits correspond to the whole buffer. - *************************************************************************************************/ - virtual void - writeData( - std::string img_path, // (INPUT) image filepath (it includes the file extension) - unsigned char * raw_img, // (INPUT) image data to be saved into the file - int img_height, // (INPUT) image height (in pixels) - int img_width, // (INPUT) image width (in pixels) - int img_depth, // (INPUT) image depth (in pixels) - int img_bytes_x_chan, // (INPUT) number of bytes per channel - int img_chans, // (INPUT) number of channels - int z0 = -1, // (INPUT) region of interest [x0,x1)[y0,y1)[z0,z1) to be set on the image - int z1 = -1, // (INPUT) region of interest [x0,x1)[y0,y1)[z0,z1) to be set on the image - int y0 = -1, // (INPUT) region of interest [x0,x1)[y0,y1)[z0,z1) to be set on the image - int y1 = -1, // (INPUT) region of interest [x0,x1)[y0,y1)[z0,z1) to be set on the image - int x0 = -1, // (INPUT) region of interest [x0,x1)[y0,y1)[z0,z1) to be set on the image - int x1 = -1, // (INPUT) region of interest [x0,x1)[y0,y1)[z0,z1) to be set on the image - const std::string & params = iom::IMOUT_PLUGIN_PARAMS) // (INPUT) additional parameters - throw (iom::exception) = 0; - - /************************************************************************************************ - * Create an empty 3D image - * Initialize a file that has to contain a 3D image. The newly created file is initially empty - * and it has to be filled adding slices with method 'appendSlice'. - * WARNING: exactly 'img_depth' slices have to be written in the newly created file before it can be read. - *************************************************************************************************/ - virtual void - create3Dimage( - std::string img_path, // (INPUT) image filepath (it includes the file extension) - int img_height, // (INPUT) image height (in pixels) - int img_width, // (INPUT) image width (in pixels) - int img_depth, // (INPUT) image depth (in pixels) - int img_bytes_x_chan, // (INPUT) number of bytes per channel - int img_chans, // (INPUT) number of channels - const std::string & params = iom::IMOUT_PLUGIN_PARAMS) // (INPUT) additional parameters - throw (iom::exception) = 0; - - /************************************************************************************************ - * Append a single slice at the bottom of a 3D image file - * The ROI specify a subarea into the buffer pointed by raw_img which are the only data appended - * to the file. This means that the saved slice actually saved has dimensions: - * (y1-y0) x (x1-x0) - * Default values for ROI limits correspond to the whole buffer. - * If the value of parameter slice is not the default value, its value must be equal to the - * number of slices already stored into the file. - * WARNING: if more slices than were specified when the file was created (see 'create3Dimage'), - * the file might be corrupted. - *************************************************************************************************/ - virtual void - appendSlice( - std::string img_path, // (INPUT) image filepath (it includes the file extension) - unsigned char * raw_img, // (INPUT) slice to be saved into the file - int img_height, // (INPUT) slice height (in pixels) - int img_width, // (INPUT) slice width (in pixels) - int img_bytes_x_chan, // (INPUT) number of bytes per channel - int img_chans, // (INPUT) number of channels - int y0 = -1, // (INPUT) region of interest [x0,x1)[y0,y1) to be set on the image - int y1 = -1, // (INPUT) region of interest [x0,x1)[y0,y1) to be set on the image - int x0 = -1, // (INPUT) region of interest [x0,x1)[y0,y1) to be set on the image - int x1 = -1, // (INPUT) region of interest [x0,x1)[y0,y1) to be set on the image - int slice = -1, // (INPUT) slice index - const std::string & params = iom::IMOUT_PLUGIN_PARAMS) // (INPUT) additional parameters - throw (iom::exception) = 0; - - /************************************************************************************************ - * Return plugin description - *************************************************************************************************/ - virtual std::string desc() = 0; - - /************************************************************************************************ - * return if channels are interleaved (in case the image has just one channel return value is - * indefinite) - *************************************************************************************************/ - virtual bool isChansInterleaved() = 0; - - - /************************************************************************************************ - * Methods deprecated - *************************************************************************************************/ - - // read 3D image data - virtual void - readData( - char *finName, // (INPUT) image filepath - int XSIZE, // (INPUT) image width (in pixels) - int YSIZE, // (INPUT) image height (in pixels) - unsigned char *data, // (OUTPUT) image data - int first, // (INPUT) selects a range [first, last] of files to be loaded - int last, // (INPUT) selects a range [first, last] of files to be loaded - const std::string & params = iom::IMIN_PLUGIN_PARAMS) // (INPUT) additional parameters - throw (iom::exception) = 0; -}; - - -// define new type: Format2D plugin creator function -typedef iomanager::IOPlugin2D* (*IOPlugin2DCreator)(void); - -// define new type: Format3D plugin creator function -typedef iomanager::IOPlugin3D* (*IOPlugin3DCreator)(void); - -// Factory for plugins' registration and instantiation -class iomanager::IOPluginFactory -{ - private: - - // map of registered I/O plugins - std::map registry2D; - std::map registry3D; - - public: - - // singleton - static IOPluginFactory* instance() - { - static IOPluginFactory* uniqueInstance = new IOPluginFactory(); - return uniqueInstance; - } - - // plugin registration - static std::string registerPlugin2D(IOPlugin2DCreator creator, std::string id) - { - instance()->registry2D[id] = creator; - return id; - } - static std::string registerPlugin3D(IOPlugin3DCreator creator, std::string id) - { - instance()->registry3D[id] = creator; - return id; - } - - // plugin instantiation - static IOPlugin2D* getPlugin2D(std::string id) throw (iom::exception) - { - if(instance()->registry2D.find(id) == instance()->registry2D.end()) - throw iom::exception(iom::strprintf("Cannot find 2D I/O plugin \"%s\" or it is not a 2D I/O plugin", id.c_str()).c_str()); - return (instance()->registry2D[id])(); - } - static IOPlugin3D* getPlugin3D(std::string id) throw (iom::exception) - { - if(instance()->registry3D.find(id) == instance()->registry3D.end()) - throw iom::exception(iom::strprintf("Cannot find 3D I/O plugin \"%s\" or it is not a 3D I/O plugin", id.c_str()).c_str()); - return (instance()->registry3D[id])(); - } - - // get list of registered plugins - static std::string registeredPlugins2D(){ - std::string plugins; - for(std::map::iterator it = instance()->registry2D.begin(); it != instance()->registry2D.end(); it++) - plugins += "\"" + it->first + "\", "; - plugins = plugins.substr(0, plugins.find_last_of(",")); - return plugins; - } - static std::string registeredPlugins3D(){ - std::string plugins; - for(std::map::iterator it = instance()->registry3D.begin(); it != instance()->registry3D.end(); it++) - plugins += "\"" + it->first + "\", "; - plugins = plugins.substr(0, plugins.find_last_of(",")); - return plugins; - } - static std::string registeredPlugins(){ - std::string plugins; - for(std::map::iterator it = instance()->registry2D.begin(); it != instance()->registry2D.end(); it++) - plugins += "\"" + it->first + "\", "; - for(std::map::iterator it = instance()->registry3D.begin(); it != instance()->registry3D.end(); it++) - plugins += "\"" + it->first + "\", "; - plugins = plugins.substr(0, plugins.find_last_of(",")); - return plugins; - } - static std::vector< std::string > registeredPluginsList(){ - std::vector< std::string > plugins; - for(std::map::iterator it = instance()->registry2D.begin(); it != instance()->registry2D.end(); it++) - plugins.push_back(it->first); - for(std::map::iterator it = instance()->registry3D.begin(); it != instance()->registry3D.end(); it++) - plugins.push_back(it->first); - return plugins; - } - - // get plugins info - static std::string pluginsInfo(){ - std::string info; - for(std::map::iterator it = instance()->registry2D.begin(); it != instance()->registry2D.end(); it++) - info += "\n" + it->second()->desc() + "\n"; - for(std::map::iterator it = instance()->registry3D.begin(); it != instance()->registry3D.end(); it++) - info += "\n" + it->second()->desc() + "\n"; - return info; - } - - // get total time - static double getTimeConversions(){ - double sum = 0; - for(std::map::iterator it = instance()->registry3D.begin(); it != instance()->registry3D.end(); it++) - sum += it->second()->time_conversions; - for(std::map::iterator it = instance()->registry2D.begin(); it != instance()->registry2D.end(); it++) - sum += it->second()->time_conversions; - return sum; - } - static double getTimeIO(){ - double sum = 0; - for(std::map::iterator it = instance()->registry3D.begin(); it != instance()->registry3D.end(); it++) - sum += it->second()->time_IO; - for(std::map::iterator it = instance()->registry2D.begin(); it != instance()->registry2D.end(); it++) - sum += it->second()->time_IO; - return sum; - } -}; - -// macro for automated 2D IO plugin definition -#define TERASTITCHER_CREATE_IO_PLUGIN_2D(classname) \ -namespace iomanager \ -{ \ - class classname : public IOPlugin2D \ - { \ - private: \ - \ - static const std::string _id; \ - static IOPlugin2D* create() { return instance(); } \ - \ - public: \ - \ - static classname* instance(){ \ - static classname * uniqueInstance = new classname (); \ - return uniqueInstance; \ - } \ - \ - virtual void \ - readMetadata( \ - std::string img_path, \ - int & img_width, \ - int & img_height, \ - int & img_bytes_x_chan, \ - int & img_chans, \ - const std::string & params = iom::IMIN_PLUGIN_PARAMS) \ - throw (iom::exception); \ - \ - virtual unsigned char * \ - readData( \ - std::string img_path, \ - int & img_width, \ - int & img_height, \ - int & img_bytes_x_chan, \ - int & img_chans, \ - unsigned char *data = 0, \ - const std::string & params = iom::IMIN_PLUGIN_PARAMS) \ - throw (iom::exception); \ - \ - virtual void \ - writeData( \ - std::string img_path, \ - unsigned char *raw_img, \ - int img_height, \ - int img_width, \ - int img_bytes_x_chan, \ - int img_chans, \ - int y0 = -1, \ - int y1 = -1, \ - int x0 = -1, \ - int x1 = -1, \ - const std::string & params = iom::IMOUT_PLUGIN_PARAMS) \ - throw (iom::exception); \ - \ - virtual std::string desc(); \ - \ - virtual bool isChansInterleaved(); \ - \ - virtual iom::real_t* \ - readData( \ - char **files, \ - int files_size, \ - const char *path = 0, \ - int first = -1, \ - int last = -1, \ - bool is_sparse = false, \ - iom::channel chan = CHANS, \ - const std::string & params = iom::IMIN_PLUGIN_PARAMS) \ - throw (iom::exception); \ - \ - virtual void \ - writeData( \ - std::string img_path, \ - iom::real_t *raw_img, \ - int img_height, \ - int img_width, \ - int img_chans, \ - int y0 = -1, \ - int y1 = -1, \ - int x0 = -1, \ - int x1 = -1, \ - int bpp = iom::DEF_BPP, \ - const std::string & params = iom::IMOUT_PLUGIN_PARAMS) \ - throw (iom::exception); \ - }; \ -} \ - \ -namespace{ \ - const iomanager::classname* object##classname = iomanager::classname::instance(); \ -} - -// macro for automated 3D IO plugin definition -#define TERASTITCHER_CREATE_IO_PLUGIN_3D(classname) \ -namespace iomanager \ -{ \ - class classname : public IOPlugin3D \ - { \ - private: \ - \ - static const std::string _id; \ - static IOPlugin3D* create() { return instance(); } \ - \ - public: \ - \ - static classname* instance(){ \ - static classname * uniqueInstance = new classname (); \ - return uniqueInstance; \ - } \ - \ - virtual void \ - readMetadata( \ - std::string img_path, \ - int & img_width, \ - int & img_height, \ - int & img_depth, \ - int & img_bytes_x_chan, \ - int & img_chans, \ - const std::string & params = IMIN_PLUGIN_PARAMS) \ - throw (iom::exception); \ - \ - virtual unsigned char * \ - readData( \ - std::string img_path, \ - int & img_width, \ - int & img_height, \ - int & img_depth, \ - int & img_bytes_x_chan, \ - int & img_chans, \ - unsigned char *data = 0, \ - int z0 = -1, \ - int z1 = -1, \ - const std::string & params = iom::IMIN_PLUGIN_PARAMS) \ - throw (iom::exception); \ - \ - virtual void \ - writeData( \ - std::string img_path, \ - unsigned char * raw_img, \ - int img_height, \ - int img_width, \ - int img_depth, \ - int img_bytes_x_chan, \ - int img_chans, \ - int z0 = -1, \ - int z1 = -1, \ - int y0 = -1, \ - int y1 = -1, \ - int x0 = -1, \ - int x1 = -1, \ - const std::string & params = iom::IMOUT_PLUGIN_PARAMS) \ - throw (iom::exception); \ - \ - virtual void \ - create3Dimage( \ - std::string img_path, \ - int img_height, \ - int img_width, \ - int img_depth, \ - int img_bytes_x_chan, \ - int img_chans, \ - const std::string & params = iom::IMOUT_PLUGIN_PARAMS) \ - throw (iom::exception); \ - \ - virtual void \ - appendSlice( \ - std::string img_path, \ - unsigned char * raw_img, \ - int img_height, \ - int img_width, \ - int img_bytes_x_chan, \ - int img_chans, \ - int y0 = -1, \ - int y1 = -1, \ - int x0 = -1, \ - int x1 = -1, \ - int slice = -1, \ - const std::string & params = iom::IMOUT_PLUGIN_PARAMS) \ - throw (iom::exception); \ - \ - virtual std::string desc(); \ - \ - virtual bool isChansInterleaved(); \ - \ - virtual void \ - readData( \ - char *finName, \ - int XSIZE, \ - int YSIZE, \ - unsigned char *data, \ - int first, \ - int last, \ - const std::string & params = IMIN_PLUGIN_PARAMS) \ - throw (iom::exception); \ - }; \ -} \ - \ -namespace{ \ - const iomanager::classname* object##classname = iomanager::classname::instance(); \ -} - -// macro for automated 2D IO plugin registration -#define TERASTITCHER_REGISTER_IO_PLUGIN_2D(classname) \ - const std::string iomanager::classname::_id = iomanager::IOPluginFactory::registerPlugin2D(&create, #classname); - -// macro for automated 3D IO plugin registration -#define TERASTITCHER_REGISTER_IO_PLUGIN_3D(classname) \ - const std::string iomanager::classname::_id = iomanager::IOPluginFactory::registerPlugin3D(&create, #classname); - -// include the header automatically generated by CMakeFile to import all the available plugins -#include "ioplugins.h" - -#endif // _IOM_IMAGE_FORMAT_H diff --git a/v3d_main/terafly/src/core/iomanager/ProgressBar.cpp b/v3d_main/terafly/src/core/iomanager/ProgressBar.cpp deleted file mode 100644 index 265e12fb30..0000000000 --- a/v3d_main/terafly/src/core/iomanager/ProgressBar.cpp +++ /dev/null @@ -1,103 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* -* Bria, A., Iannello, G., "TeraStitcher - A Tool for Fast 3D Automatic Stitching of Teravoxel-sized Microscopy Images", (2012) BMC Bioinformatics, 13 (1), art. no. 316. -* -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -#include "ProgressBar.h" -#include -#include -#include -#include - -using namespace std; - -#ifdef _VAA3D_PLUGIN_MODE -#include "../../presentation/PMain.h" -#endif - -ProgressBar::ProgressBar() -{ - strcpy(this->operation_desc, "none"); - progress_value=0; - strcpy(this->progress_info, ""); - proctime = 0; - minutes_remaining = 0; - seconds_remaining = 0; -} - - -void ProgressBar::start(const char *new_operation_desc) -{ - strcpy(this->operation_desc, new_operation_desc); - this->progress_value=0; - strcpy(this->progress_info, ""); - proctime = -TIME(0); - minutes_remaining = 0; - seconds_remaining = 0; - - #ifdef _VAA3D_PLUGIN_MODE - int progress_value_int = (int) progress_value; - terastitcher::PMain::instance()->emitProgressBarChanged(progress_value_int, 0, 0, new_operation_desc); - #endif -} - -void ProgressBar::update(float new_progress_value, const char* new_progress_info) -{ - progress_value=new_progress_value; - strcpy(progress_info,new_progress_info); - - if(new_progress_value!=0) - { - minutes_remaining = (int)((proctime + TIME(0))*(100.0-progress_value)/(progress_value*60.0)); - seconds_remaining = (int)((proctime + TIME(0))*(100.0-progress_value)/(progress_value)); - } -} - - -void ProgressBar::updateInfo(const char* new_progress_info) -{ - strcpy(progress_info,new_progress_info); -} - -void ProgressBar::show() -{ - -#ifdef _VAA3D_PLUGIN_MODE - int progress_value_int = (int) progress_value; - terastitcher::PMain::instance()->emitProgressBarChanged(progress_value_int, minutes_remaining, seconds_remaining%60); -#else - system_CLEAR(); - printf("OPERATION:\t%s\n",this->operation_desc); - printf("PHASE:\t\t%s\n",this->progress_info); - printf("TIME REMAINING:\t%d minutes and %d seconds\n", minutes_remaining, seconds_remaining%60); - printf("PROGRESS:\t"); - printf("%d%%\t",(int)(progress_value)); - for(int i=1; i<=progress_value; i++) - printf("*"); - for(int i=(int)progress_value; i<100; i++) - printf(":"); - printf("\n\n"); -#endif -} diff --git a/v3d_main/terafly/src/core/iomanager/ProgressBar.h b/v3d_main/terafly/src/core/iomanager/ProgressBar.h deleted file mode 100644 index b0a51abc81..0000000000 --- a/v3d_main/terafly/src/core/iomanager/ProgressBar.h +++ /dev/null @@ -1,63 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* -* Bria, A., Iannello, G., "TeraStitcher - A Tool for Fast 3D Automatic Stitching of Teravoxel-sized Microscopy Images", (2012) BMC Bioinformatics, 13 (1), art. no. 316. -* -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -#ifndef _PROGRESS_BAR_H -#define _PROGRESS_BAR_H - -#include -#include "iomanager.config.h" -#include - -class ProgressBar -{ - private: - - ProgressBar(); - - char operation_desc[500]; - float progress_value; - char progress_info[500]; - double proctime; - int minutes_remaining; - int seconds_remaining; - - public: - - // singleton - static ProgressBar* instance(){ - static ProgressBar* uniqueInstance = new ProgressBar(); - return uniqueInstance; - }; - - - void start(const char* new_operation_desc); - void update(float new_progress_value, const char* new_progress_info); - void updateInfo(const char* new_progress_info); - void show(); -}; - -#endif diff --git a/v3d_main/terafly/src/core/iomanager/iomanager.config.cpp b/v3d_main/terafly/src/core/iomanager/iomanager.config.cpp deleted file mode 100644 index 0662f805ae..0000000000 --- a/v3d_main/terafly/src/core/iomanager/iomanager.config.cpp +++ /dev/null @@ -1,52 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* -* Bria, A., Iannello, G., "TeraStitcher - A Tool for Fast 3D Automatic Stitching of Teravoxel-sized Microscopy Images", (2012) BMC Bioinformatics, 13 (1), art. no. 316. -* -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -#include "iomanager.config.h" -#include "IOPluginAPI.h" - -/****************** -* CHANGELOG * -******************* -* 2014-11-25 Giulio. @CHANGED default plugins are set to "empty" because they have to be set by the application -*/ - -// initialize namespace parameters -namespace iomanager -{ - /******************* - * PARAMETERS * - ******************** - ---------------------------------------------------------------------------------------------------------------------------*/ - int DEBUG = NO_DEBUG; // debug level - bool TIME_CALC = true; // whether to enable time measurements - channel CHANS = ALL; // channel to be loaded (default is ALL) - std::string IMIN_PLUGIN = "empty"; // plugin to manage input image format - std::string IMIN_PLUGIN_PARAMS=""; // additional parameters to the plugin for image input - std::string IMOUT_PLUGIN = "empty"; // plugin to manage output image format (WARNING: must be a 2D pluging to output test image until 3D plugins do not have a write operation) - std::string IMOUT_PLUGIN_PARAMS=""; // additional parameters to the plugin for image output - /*-------------------------------------------------------------------------------------------------------------------------*/ -} \ No newline at end of file diff --git a/v3d_main/terafly/src/core/iomanager/iomanager.config.h b/v3d_main/terafly/src/core/iomanager/iomanager.config.h deleted file mode 100644 index 7afd14d8bb..0000000000 --- a/v3d_main/terafly/src/core/iomanager/iomanager.config.h +++ /dev/null @@ -1,259 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* -* Bria, A., Iannello, G., "TeraStitcher - A Tool for Fast 3D Automatic Stitching of Teravoxel-sized Microscopy Images", (2012) BMC Bioinformatics, 13 (1), art. no. 316. -* -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -* 2014-09-02. Alessandro. @ADDED 'uint64' type. -*/ - - -#ifndef _IO_MANAGER_DEFS_H -#define _IO_MANAGER_DEFS_H - -#include -#include -#include -#include -#include -#include -#include - -/****************************************************************************************************************************** - * Interfaces, constants, enums, parameters, and cross-platform utility functions * - ******************************************************************************************************************************/ -namespace iomanager -{ - /******************* - * TYPES * - ******************** - ---------------------------------------------------------------------------------------------------------------------------*/ - typedef float real_t; // real type definition (float for single precision, double for double precision) - typedef unsigned char uint8; // 8-bit unsigned integer data type - typedef unsigned short uint16; // 16-bit unsigned integer data type - typedef unsigned int uint32; // 32-bit unsigned integer data type - typedef int sint32; // 32-bit signed integer data type - typedef long long sint64; // 64-bit signed integer data type - typedef unsigned long long uint64; // 64-bit unsigned integer data type - /*-------------------------------------------------------------------------------------------------------------------------*/ - - - /******************* - * INTERFACES * - ******************** - ---------------------------------------------------------------------------------------------------------------------------*/ - class IOPlugin; - class IOPlugin2D; - class IOPlugin3D; - class IOPluginFactory; - class exception; - /*-------------------------------------------------------------------------------------------------------------------------*/ - - - /******************* - * CONSTANTS * - ******************** - ---------------------------------------------------------------------------------------------------------------------------*/ - const std::string DEF_IMG_FORMAT = "tif"; // default image format - const int DEF_BPP = 8; // default image depth - /*-------------------------------------------------------------------------------------------------------------------------*/ - - - /******************* - * ENUMS * - ******************** - ---------------------------------------------------------------------------------------------------------------------------*/ - enum debug_level { NO_DEBUG, LEV1, LEV2, LEV3, LEV_MAX }; - enum channel { ALL, R, G, B }; - /*-------------------------------------------------------------------------------------------------------------------------*/ - - - /******************* - * PARAMETERS * - ******************** - ---------------------------------------------------------------------------------------------------------------------------*/ - extern int DEBUG; // debug level of current module - extern bool TIME_CALC; // whether to enable time measurements - extern channel CHANS; // channel to be loaded (default is ALL) - extern std::string IMIN_PLUGIN; // plugin to manage input image format - extern std::string IMIN_PLUGIN_PARAMS; // additional parameters to the plugin for image input - extern std::string IMOUT_PLUGIN; // plugin to manage output image format - extern std::string IMOUT_PLUGIN_PARAMS; // additional parameters to the plugin for image output - /*-------------------------------------------------------------------------------------------------------------------------*/ - - - /******************************************** - * Cross-platform UTILITY functions * - ******************************************** - ---------------------------------------------------------------------------------------------------------------------------*/ - - //string-based sprintf function - inline std::string strprintf(const std::string fmt, ...){ - int size = 100; - std::string str; - va_list ap; - while (1) { - str.resize(size); - va_start(ap, fmt); - int n = vsnprintf((char *)str.c_str(), size, fmt.c_str(), ap); - va_end(ap); - if (n > -1 && n < size) { - str.resize(n); - return str; - } - if (n > -1) - size = n + 1; - else - size *= 2; - } - return str; - } - - // tokenizer - inline void split(const std::string & theString, std::string delim, std::vector& tokens) - { - size_t start = 0, end = 0; - while ( end != std::string::npos) - { - end = theString.find( delim, start); - - // If at end, use length=maxLength. Else use length=end-start. - tokens.push_back( theString.substr( start, - (end == std::string::npos) ? std::string::npos : end - start)); - - // If at end, use start=maxSize. Else use start=end+delimiter. - start = ( ( end > (std::string::npos - delim.size()) ) - ? std::string::npos : end + delim.size()); - } - } - - // removes all tab, space and newline characters from the given string - inline std::string cls(std::string string){ - string.erase(std::remove(string.begin(), string.end(), '\t'), string.end()); - string.erase(std::remove(string.begin(), string.end(), ' '), string.end()); - string.erase(std::remove(string.begin(), string.end(), '\n'), string.end()); - return string; - } - - //number to string conversion function and vice versa - template - std::string num2str ( T Number ){ - std::stringstream ss; - ss << Number; - return ss.str(); - } - template - T str2num ( const std::string &Text ){ - std::stringstream ss(Text); - T result; - return ss >> result ? result : 0; - } - - //cross-platform current function macros (@WARNING: as they are macros, they are NOT namespaced) - #if defined(__GNUC__) || (defined(__MWERKS__) && (__MWERKS__ >= 0x3000)) || (defined(__ICC) && (__ICC >= 600)) - # define __iom__current__function__ __PRETTY_FUNCTION__ - #elif defined(__DMC__) && (__DMC__ >= 0x810) - # define __iom__current__function__ __PRETTY_FUNCTION__ - #elif defined(__FUNCSIG__) - # define __iom__current__function__ __FUNCSIG__ - #elif (defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 600)) || (defined(__IBMCPP__) && (__IBMCPP__ >= 500)) - # define __iom__current__function__ __FUNCTION__ - #elif defined(__BORLANDC__) && (__BORLANDC__ >= 0x550) - # define __iom__current__function__ __FUNC__ - #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901) - # define __iom__current__function__ __func__ - #else - # define __iom__current__function__ "(unknown)" - #endif - - //time macros (@WARNING: as they are macros, they are NOT namespaced) - #ifdef _WIN32 - #define TIME( arg ) (((double) clock()) / CLOCKS_PER_SEC) - #else - #define TIME( arg ) (time( arg )) - #endif - - //clear macros (@WARNING: as they are macros, they are NOT namespaced) - #ifdef _WIN32 - #define system_CLEAR() system("cls"); - #else - #define system_CLEAR() system("clear"); - #endif - - - - /*********************************************** - * DEBUG, WARNING and EXCEPTION FUNCTIONS * - ************************************************ - ---------------------------------------------------------------------------------------------------------------------------*/ - inline void warning(const char* message, const char* source = 0) - { - if(source) - printf("\n**** WARNING (source: \"%s\") ****\n |=> \"%s\"\n\n", source, message); - else - printf("\n**** WARNING ****: %s\n", message); - } - - inline void debug(debug_level dbg_level, const char* message=0, const char* source=0) - { - if(DEBUG >= dbg_level) - { - if(message && source) - printf("\n----------------------- iomanager module: DEBUG (level %d) ----: in \"%s\") ----\n" - " message: %s\n\n", dbg_level, source, message); - else if(message) - printf("\n----------------------- iomanager module: DEBUG (level %d) ----: %s\n", dbg_level, message); - else if(source) - printf("\n----------------------- iomanager module: DEBUG (level %d) ----: in \"%s\"\n", dbg_level, source); - } - } - - class exception : public std::exception - { - private: - - std::string message; - - public: - - exception(const std::string & new_message, std::string source = ""){ - if(source.empty()) - message = new_message; - else - message = std::string("in ") + source + ": " + new_message; - } - virtual ~exception() throw (){} - virtual const char* what() const throw (){return message.c_str();} - }; - - - -} - -namespace iom = iomanager; - -#endif /* _IO_MANAGER_DEFS_H */ diff --git a/v3d_main/terafly/src/core/iomanager/ioplugins.h b/v3d_main/terafly/src/core/iomanager/ioplugins.h deleted file mode 100644 index 8823e582a5..0000000000 --- a/v3d_main/terafly/src/core/iomanager/ioplugins.h +++ /dev/null @@ -1,3 +0,0 @@ -// Include plugins headers -#include "plugins/tiff2D/tiff2D.h" -#include "plugins/tiff3D/tiff3D.h" diff --git a/v3d_main/terafly/src/core/iomanager/plugins/exampleplugin2D/CMakeLists.txt b/v3d_main/terafly/src/core/iomanager/plugins/exampleplugin2D/CMakeLists.txt deleted file mode 100644 index 111649abc3..0000000000 --- a/v3d_main/terafly/src/core/iomanager/plugins/exampleplugin2D/CMakeLists.txt +++ /dev/null @@ -1,12 +0,0 @@ -# find all headers and sources -file(GLOB headers *.h) -file(GLOB sources *.cpp) - -# add parent dir to include path -include_directories (../../) - -# get current directory name -get_filename_component(dirname ${CMAKE_CURRENT_SOURCE_DIR} NAME) - -# add static library -add_library(ioplugin_${dirname} STATIC ${headers} ${sources}) \ No newline at end of file diff --git a/v3d_main/terafly/src/core/iomanager/plugins/exampleplugin2D/exampleplugin2D.cpp b/v3d_main/terafly/src/core/iomanager/plugins/exampleplugin2D/exampleplugin2D.cpp deleted file mode 100644 index d9339730a1..0000000000 --- a/v3d_main/terafly/src/core/iomanager/plugins/exampleplugin2D/exampleplugin2D.cpp +++ /dev/null @@ -1,186 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* -* Bria, A., Iannello, G., "TeraStitcher - A Tool for Fast 3D Automatic Stitching of Teravoxel-sized Microscopy Images", (2012) BMC Bioinformatics, 13 (1), art. no. 316. -* -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -* 2015-01-02. Giulio. @IMPLEMENTED new plugins interface -*/ - -#include "exampleplugin2D.h" - -// just call this macro to register your plugin -TERASTITCHER_REGISTER_IO_PLUGIN_2D(exampleplugin2D) - -// insert here your plugin description that will be displayed on the user interface -std::string iomanager::exampleplugin2D::desc() -{ - return "******************************************************\n" - "* exampleplugin2D v.1.0 *\n" - "******************************************************\n" - "* *\n" - "* A dummy 2D image-based I/O plugin to demonstrate *\n" - "* the extensibility of TeraStitcher I/O. *\n" - "* *\n" - "* Supported image formats: *\n" - "* - none *\n" - "* *\n" - "* Accepted configuration parameters: *\n" - "* - astring: example parameter to pass a string *\n" - "* - aninteger: example parameter to pass an integer *\n" - "* *\n" - "******************************************************\n"; -} - - -// Return if channels are interleaved (in case the image has just one channel return value is indefinite) -bool - iomanager::exampleplugin2D::isChansInterleaved( ) -{ - return true; -} - - -// read image metadata from a 2D image file -void - iomanager::exampleplugin2D::readMetadata( - std::string img_path, // (INPUT) image filepath - int & img_width, // (OUTPUT) image width (in pixels) - int & img_height, // (OUTPUT) image height (in pixels) - int & img_bytes_x_chan, // (OUTPUT) number of bytes per channel - int & img_chans, // (OUTPUT) number of channels - const std::string & params) // (INPUT) additional parameters -throw (iom::exception) -{ - /**/iom::debug(iom::LEV3, iom::strprintf("img_path = \"%s\", params = \"%s\"",img_path.c_str(), params.c_str()).c_str(), __iom__current__function__); - - // parse plugin configuration parameters, if any - std::string params_nospaces = iom::cls(params); // remove tabs and spaces - std::string astring; - int aninteger = 0; - if(!params_nospaces.empty()) - { - std::vector entries; - iom::split(params_nospaces, ",", entries); - for(int i=0; i tokens; - iom::split(entries[i], "=", tokens); - if(tokens.size() != 2) - throw iom::exception(iom::strprintf("cannot parse parameter entry \"%s\". Expected \"param=value\" format", entries[i].c_str()), __iom__current__function__); - if(tokens[0].compare("astring")==0) - astring = tokens[1]; - else if(tokens[0].compare("aninteger")==0) - aninteger = iom::str2num(tokens[1]); - else - throw iom::exception(iom::strprintf("cannot parse parameter entry \"%s\". Unrecognized parameter \"%s\"", entries[i].c_str(), tokens[0].c_str()), __iom__current__function__); - } - } - - throw iom::exception(iom::strprintf("not implemented yet (astring = \"%s\", aninteger = %d)", astring.c_str(), aninteger), __iom__current__function__); -} - - -// Read 2D image data -unsigned char * // (OUTPUT) a buffer storing the 2D image - iomanager::exampleplugin2D::readData( - std::string img_path, // (INPUT) image filepath - int & img_width, // (INPUT/OUTPUT) image width (in pixels) - int & img_height, // (INPUT/OUTPUT) image height (in pixels) - int & img_bytes_x_chan, // (INPUT/OUTPUT) number of bytes per channel - int & img_chans, // (INPUT/OUTPUT) number of channels to be read - unsigned char *data, // (INPUT) image data - const std::string & params) // (INPUT) additional parameters -throw (iom::exception) -{ - throw iom::exception(iom::strprintf("not implemented yet"), __iom__current__function__); - - return 0; -} - - -// Write 2D image data into a single (2D) image file -void - iomanager::exampleplugin2D::writeData( - std::string img_path, // (INPUT) image filepath (it includes the file extension) - unsigned char *raw_img, // (INPUT) image data to be saved into the file - int img_height, // (INPUT) image height - int img_width, // (INPUT) image width - int img_bytes_x_chan, // (INPUT) number of bytes per channel - int img_chans, // (INPUT) number of channels - int y0, // (INPUT) region of interest [x0,x1][y0,y1] to be set on the image - int y1, // (INPUT) region of interest [x0,x1][y0,y1] to be set on the image - int x0, // (INPUT) region of interest [x0,x1][y0,y1] to be set on the image - int x1, // (INPUT) region of interest [x0,x1][y0,y1] to be set on the image - const std::string & params) // (INPUT) additional parameters -throw (iom::exception) -{ - throw iom::exception(iom::strprintf("not implemented yet"), __iom__current__function__); -} - - -// read 3D image data from a stack of (2D) image files -iom::real_t* // (OUTPUT) a [0.0,1.0]-valued array storing the 3D image in channel->slice->row order - iomanager::exampleplugin2D::readData( - char **files, // (INPUT) array of C-strings storing image filenames - int files_size, // (INPUT) size of 'files' - const char *path /*= 0*/, // (INPUT) path to be concatenated to the i-th entry of 'files' - int first /*= -1*/, // (INPUT) selects a range [first, last] of files to be loaded - int last /*= -1*/, // (INPUT) selects a range [first, last] of files to be loaded - bool is_sparse /*= false*/, // (INPUT) if true, 'files' is a sparse array and null entries should be treated as empty (black) images - iom::channel chan, // (INPUT) channel selection { ALL, R, G, B }. - const std::string & params) // (INPUT) additional parameters -throw (iom::exception) -{ - throw iom::exception(iom::strprintf("not implemented yet (params = \"%s\")", params.c_str()), __iom__current__function__); - - /**/iom::debug(iom::LEV3, iom::strprintf("files_size = %d, path = %s, first = %d, last = %d, is_sparse = %s, chan = %d, params = \"%s\"", - files_size, path ? path : "null", first, last, is_sparse ? "true" : "false", chan, params.c_str()).c_str(), __iom__current__function__); -} - - -// write 2D image data into a single (2D) image file -void - iomanager::exampleplugin2D::writeData( - std::string img_path, // (INPUT) image filepath (it includes the file extension) - iom::real_t* raw_img, // (INPUT) a [0.0,1.0]-valued array storing the 2D image in channel->row order - int img_height, // (INPUT) image height - int img_width, // (INPUT) image width - int img_chans, // (INPUT) number of channels - int y0, // (INPUT) region of interest [x0,x1][y0,y1] to be set on the image - int y1, // (INPUT) region of interest [x0,x1][y0,y1] to be set on the image - int x0, // (INPUT) region of interest [x0,x1][y0,y1] to be set on the image - int x1, // (INPUT) region of interest [x0,x1][y0,y1] to be set on the image - int bpp, // (INPUT) color depth (bits per pixel) - const std::string & params) // (INPUT) additional parameters - throw (iom::exception) -{ - throw iom::exception(iom::strprintf("not implemented yet (params = \"%s\")", params.c_str()), __iom__current__function__); - - /**/iom::debug(iom::LEV3, iom::strprintf("img_path = %s, img_height = %d, img_width = %d, y0 = %d, y1 = %d, x0 = %d, x1 = %d, bpp = %d, params = \"%s\"", - img_path.c_str(), img_height, img_width, y0, y1, x0, x1, bpp, params.c_str()).c_str(), __iom__current__function__); -} \ No newline at end of file diff --git a/v3d_main/terafly/src/core/iomanager/plugins/exampleplugin2D/exampleplugin2D.h b/v3d_main/terafly/src/core/iomanager/plugins/exampleplugin2D/exampleplugin2D.h deleted file mode 100644 index 7a25735754..0000000000 --- a/v3d_main/terafly/src/core/iomanager/plugins/exampleplugin2D/exampleplugin2D.h +++ /dev/null @@ -1,9 +0,0 @@ -#ifndef _EXAMPLE_FORMAT_H -#define _EXAMPLE_FORMAT_H - -#include "../../IOPluginAPI.h" - -// just call this useful macro to create your plugin -TERASTITCHER_CREATE_IO_PLUGIN_2D(exampleplugin2D) - -#endif // _EXAMPLE_FORMAT_H \ No newline at end of file diff --git a/v3d_main/terafly/src/core/iomanager/plugins/opencv2D/CMakeLists.txt b/v3d_main/terafly/src/core/iomanager/plugins/opencv2D/CMakeLists.txt deleted file mode 100644 index 7b43858444..0000000000 --- a/v3d_main/terafly/src/core/iomanager/plugins/opencv2D/CMakeLists.txt +++ /dev/null @@ -1,20 +0,0 @@ -# find all headers and sources -file(GLOB headers *.h) -file(GLOB sources *.cpp) - -# add parent dir to include path -include_directories (../../) - -# get current directory name -get_filename_component(dirname ${CMAKE_CURRENT_SOURCE_DIR} NAME) - -# add static library -add_library(ioplugin_${dirname} STATIC ${headers} ${sources}) - -# set up OpenCV library -find_package(OpenCV REQUIRED) -include_directories(${OpenCV_INCLUDE_DIRS}) -link_directories(${OpenCV_LIB_DIR}) - -# link 3rd party libraries -target_link_libraries(ioplugin_${dirname} ${OpenCV_LIBS}) \ No newline at end of file diff --git a/v3d_main/terafly/src/core/iomanager/plugins/opencv2D/opencv2D.cpp b/v3d_main/terafly/src/core/iomanager/plugins/opencv2D/opencv2D.cpp deleted file mode 100644 index 9c32eebae7..0000000000 --- a/v3d_main/terafly/src/core/iomanager/plugins/opencv2D/opencv2D.cpp +++ /dev/null @@ -1,481 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* -* Bria, A., Iannello, G., "TeraStitcher - A Tool for Fast 3D Automatic Stitching of Teravoxel-sized Microscopy Images", (2012) BMC Bioinformatics, 13 (1), art. no. 316. -* -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -* 2015-01-02. Giulio. @IMPLEMENTED new plugins interface -*/ - -#include -#include -#include -#include "opencv2D.h" - -// just call this macro to register your plugin -TERASTITCHER_REGISTER_IO_PLUGIN_2D(opencv2D) - -// insert here your plugin description that will be displayed on the user interface -std::string iomanager::opencv2D::desc() -{ - return "******************************************************\n" - "* opencv2D v.1.0 *\n" - "******************************************************\n" - "* *\n" - "* 2D image-based I/O plugin that uses the OpenCV li- *\n" - "* brary to read/write 2D image files. *\n" - "* *\n" - "* Supported image format extentions: *\n" - "* - BMP *\n" - "* - DIB *\n" - "* - JPEG *\n" - "* - JPG *\n" - "* - JPE *\n" - "* - PNG *\n" - "* - PBM *\n" - "* - PGM *\n" - "* - PPM *\n" - "* - SR *\n" - "* - RAS *\n" - "* - TIFF *\n" - "* - TIF *\n" - "* *\n" - "* Accepted configuration parameters: *\n" - "* - none *\n" - "* *\n" - "******************************************************\n"; -} - - -// Return if channels are interleaved (in case the image has just one channel return value is indefinite) -bool - iomanager::opencv2D::isChansInterleaved( ) -{ - return true; -} - - -// read image metadata from a 2D image file -void - iomanager::opencv2D::readMetadata( - std::string img_path, // (INPUT) image filepath - int & img_width, // (OUTPUT) image width (in pixels) - int & img_height, // (OUTPUT) image height (in pixels) - int & img_bytes_x_chan, // (OUTPUT) number of bytes per channel - int & img_chans, // (OUTPUT) number of channels - const std::string & params) // (INPUT) additional parameters -throw (iom::exception) -{ - /**/iom::debug(iom::LEV3, iom::strprintf("img_path = \"%s\", params = \"%s\"",img_path.c_str(), params.c_str()).c_str(), __iom__current__function__); - - // try to read image - cv::Mat img = cv::imread(img_path); - if(!img.data) - throw iom::exception(iom::strprintf("unable to open image \"%s\". Possible unsupported format or it isn't an image.\nSupported formats are BMP, DIB, JPEG, JPG, JPE, PNG, PBM, PGM, PPM, SR, RAS, TIFF, TIF", - img_path.c_str()), __iom__current__function__); - - // read image metadata - img_width = img.rows; - img_height = img.cols; - img_chans = img.channels(); - switch(img.depth()) - { - case CV_8U: - img_bytes_x_chan = 1; break; - case CV_8S: - img_bytes_x_chan = 1; break; - case CV_16U: - img_bytes_x_chan = 2; break; - case CV_16S: - img_bytes_x_chan = 2; break; - case CV_32S: - img_bytes_x_chan = 4; break; - case CV_32F: - img_bytes_x_chan = 4; break; - case CV_64F: - img_bytes_x_chan = 8; break; - default: - throw iom::exception(iom::strprintf("unable determine bitdepth of image at \"%s\"", img_path.c_str()), __iom__current__function__); - } -} - - -// Read 2D image data -unsigned char * // (OUTPUT) a buffer storing the 2D image - iomanager::opencv2D::readData( - std::string img_path, // (INPUT) image filepath - int & img_width, // (INPUT/OUTPUT) image width (in pixels) - int & img_height, // (INPUT/OUTPUT) image height (in pixels) - int & img_bytes_x_chan, // (INPUT/OUTPUT) number of bytes per channel - int & img_chans, // (INPUT/OUTPUT) number of channels to be read - unsigned char *data, // (INPUT) image data - const std::string & params) // (INPUT) additional parameters -throw (iom::exception) -{ - //throw iom::exception(iom::strprintf("not implemented yet"), __iom__current__function__); - - if ( !data ) { // recover the metadata, allocate the buffer and set parameters - int _width; - int _height; - int _bytes_x_chan; - int _chans; - int b_swap; - void *fhandle; - int header_len; - - iom::IOPluginFactory::getPlugin2D(iom::IMIN_PLUGIN)->readMetadata(img_path,_width,_height,_bytes_x_chan,_chans); - - data = new unsigned char[_width * _height * _chans * _bytes_x_chan]; - img_width = _width; - img_height = _height; - img_bytes_x_chan = _bytes_x_chan; - img_chans = _chans; - } - - // load image - cv::Mat image; - image = cv::imread(img_path, CV_LOAD_IMAGE_ANYCOLOR); // load individual channels - if(!image.data) - throw iom::exception(iom::strprintf("unable to open image \"%s\". Possible unsupported format or it isn't an image.\nSupported formats are BMP, DIB, JPEG, JPG, JPE, PNG, PBM, PGM, PPM, SR, RAS, TIFF, TIF", img_path.c_str()), __iom__current__function__); - - if ( image.channels() == 1 ) { - if(image.depth() == CV_8U) - { - unsigned char *data_ptr = data; - for(int i=0; i(i); - for(int j=0; j(i); - for(int j=0; j -throw (iom::exception) -{ - //throw iom::exception(iom::strprintf("not implemented yet"), __iom__current__function__); - - // correct default parameters - y0 = (y0 < 0) ? 0: y0; - y1 = (y1 < 0) ? img_height : y1; - x0 = (x0 < 0) ? 0: x0; - x1 = (x1 < 0) ? img_width : x1; - - // compute ROI dimensions - int ROI_height = y1 - y0; - int ROI_width = x1 - x0; - - // precondition checks - if(! (y0>=0 && y1>y0 && y1<=img_height && x0>=0 && x1>x0 && x1<=img_width) ) - throw iom::exception(iom::strprintf("invalid ROI [%d,%d](X) x [%d,%d](Y) on image %d(X) x %d(Y)", x0, x1, y0, y1, img_width, img_height), __iom__current__function__); - if(img_bytes_x_chan != 1 && img_bytes_x_chan != 2) - throw iom::exception(iom::strprintf("unsupported bitdepth %d\n", img_bytes_x_chan*8), __iom__current__function__); - if(img_chans != 1) - throw iom::exception(iom::strprintf("unsupported number of channels = %d\n. Only single-channel images are supported", img_chans), __iom__current__function__); - - // copy data to OpenCV structure - - cv::Mat image(ROI_height, ROI_width, img_bytes_x_chan == 1 ? CV_8U : CV_16U, cv::Scalar(0)); - - if ( x0 == 0 && x1 == img_width && y0 == 0 && y1 == img_height ) { // all buffer must be written - if(img_bytes_x_chan == 1) - { - for(int i = 0; i (i); - for(int j = 0; j < ROI_width; j++) - img_data[j] = static_cast(raw_img[(i+y0)*img_width+j+x0] * 255.0f + 0.5f); - } - } - else - { - for(int i = 0; i (i); - for(int j = 0; j < ROI_width; j++) - img_data[j] = static_cast(raw_img[(i+y0)*img_width+j+x0] * 65535.0f + 0.5f); - } - } - } - else { - throw iom::exception(iom::strprintf("ROI not supported yet", img_chans), __iom__current__function__); - } - - // save image - try - { - cv::imwrite(img_path, image); - } - catch(...) - { - throw iom::exception(iom::strprintf("unable to save image at \"%s\". Unsupported format or wrong path.\n", img_path.c_str()), __iom__current__function__); - } -} - - -// read 3D image data from a stack of (2D) image files -iom::real_t* // (OUTPUT) a [0.0,1.0]-valued array storing the 3D image in channel->slice->row order - iomanager::opencv2D::readData( - char **files, // (INPUT) array of C-strings storing image filenames - int files_size, // (INPUT) size of 'files' - const char *path /*= 0*/, // (INPUT) path to be concatenated to the i-th entry of 'files' - int first /*= -1*/, // (INPUT) selects a range [first, last] of files to be loaded - int last /*= -1*/, // (INPUT) selects a range [first, last] of files to be loaded - bool is_sparse /*= false*/, // (INPUT) if true, 'files' is a sparse array and null entries should be treated as empty (black) images - iom::channel chan, // (INPUT) channel selection { ALL, R, G, B }. - const std::string & params) // (INPUT) additional parameters -throw (iom::exception) -{ - throw iom::exception(iom::strprintf("not implemented yet"), __iom__current__function__); - - /**/iom::debug(iom::LEV3, iom::strprintf("files_size = %d, path = %s, first = %d, last = %d, is_sparse = %s, chan = %d, params = \"%s\"", - files_size, path ? path : "null", first, last, is_sparse ? "true" : "false", chan, params.c_str()).c_str(), __iom__current__function__); - - iom::real_t *image_stack = 0; - uint64 image_stack_width=0, image_stack_height=0, z=0; - - // check for valid file list - if(!files || files_size <= 0) - throw iom::exception("invalid file list (null pointer or 0-sized)", __iom__current__function__); - - // check and adjust file selection - first = (first == -1 ? 0 : first); - last = (last == -1 ? files_size - 1 : last ); - first = std::min(first, files_size-1); - last = std::min(last, files_size-1); - - // loop over files - for(int file_i = first; file_i <= last; file_i++, z++) - { - // skip missing slices if stack is sparse - if(is_sparse && !files[file_i]) - continue; - - // if stack is not sparse, a missing slice must throw an iom::exception - if(!files[file_i]) - throw iom::exception("invalid slice filename in non-sparse tile", __iom__current__function__); - - // build absolute image path - std::string image_path = path ? std::string(path) + "/" + files[file_i] : files[file_i]; - - // load image - cv::Mat image; - double proctime = -TIME(0); - if(chan == iom::ALL) - image = cv::imread(image_path, CV_LOAD_IMAGE_GRAYSCALE | CV_LOAD_IMAGE_ANYDEPTH); // pack all channels into grayscale - else - image = cv::imread(image_path, CV_LOAD_IMAGE_ANYCOLOR); // load individual channels - if(!image.data) - throw iom::exception(iom::strprintf("unable to open image \"%s\". Possible unsupported format or it isn't an image.\nSupported formats are BMP, DIB, JPEG, JPG, JPE, PNG, PBM, PGM, PPM, SR, RAS, TIFF, TIF", image_path.c_str()), __iom__current__function__); - - // select channel (if requested) - if(image.channels() == 3 && chan != iom::ALL) - { - cv::Mat imageChannels[3]; - cv::split(image, imageChannels); - image = imageChannels[3-CHANS]; // OpenCV uses BGR ! - } - - // update time - if(TIME_CALC) - { - proctime += TIME(0); - time_IO+=proctime; - proctime = -TIME(0); - } - - // initialize output data and image dimensions - if(!image_stack) - { - image_stack_height = (uint64) image.rows; - image_stack_width = (uint64) image.cols; - uint64 image_stack_size = image_stack_width * image_stack_height * (last-first+1); - image_stack = new iom::real_t[image_stack_size]; - for(uint64 j=0; j < image_stack_size; j++) - image_stack[j] = 0; // default is 0 (black) - } - else if(image_stack_width != (uint64)image.cols || image_stack_height != (uint64)image.rows) - throw iom::exception("images in stack have not the same dimensions", __iom__current__function__); - - // convert image to [0.0,1.0]-valued array - iom::real_t *raw_data = &image_stack[z*image.rows*image.cols]; - if(image.depth() == CV_8U) - { - for(int i=0; i(i); - for(int j=0; j(i); - for(int j=0; jrow order - int img_height, // (INPUT) image height - int img_width, // (INPUT) image width - int img_chans, // (INPUT) number of channels - int y0, // (INPUT) region of interest [x0,x1][y0,y1] to be set on the image - int y1, // (INPUT) region of interest [x0,x1][y0,y1] to be set on the image - int x0, // (INPUT) region of interest [x0,x1][y0,y1] to be set on the image - int x1, // (INPUT) region of interest [x0,x1][y0,y1] to be set on the image - int bpp, // (INPUT) color depth (bits per pixel) - const std::string & params) // (INPUT) additional parameters -throw (iom::exception) -{ - throw iom::exception(iom::strprintf("not implemented yet"), __iom__current__function__); - - /**/iom::debug(iom::LEV3, iom::strprintf("img_path = %s, img_height = %d, img_width = %d, y0 = %d, y1 = %d, x0 = %d, x1 = %d, bpp = %d, params = \"%s\"", - img_path.c_str(), img_height, img_width, y0, y1, x0, x1, bpp, params.c_str()).c_str(), __iom__current__function__); - - - // correct default parameters - y1 = (y1 == -1 ? img_height - 1 : y1); - x1 = (x1 == -1 ? img_width - 1 : x1 ); - - // compute ROI dimensions - int ROI_height = y1 - y0 + 1; - int ROI_width = x1 - x0 + 1; - - // precondition checks - if(! (y0>=0 && y1>y0 && y1=0 && x1>x0 && x1(i); - for(int j = 0; j < ROI_width; j++) - img_data[j] = static_cast(raw_img[(i+y0)*img_width+j+x0] * 255.0f + 0.5f); - } - } - else - { - for(int i = 0; i (i); - for(int j = 0; j < ROI_width; j++) - img_data[j] = static_cast(raw_img[(i+y0)*img_width+j+x0] * 65535.0f + 0.5f); - } - } - - // update conversion time - if(TIME_CALC) - { - proctime += TIME(0); - time_conversions+=proctime; - proctime = -TIME(0); - } - - // save image - try - { - cv::imwrite(img_path, image); - } - catch(...) - { - throw iom::exception(iom::strprintf("unable to save image at \"%s\". Unsupported format or wrong path.\n", img_path.c_str()), __iom__current__function__); - } - - // update IO time - if(TIME_CALC) - { - proctime += TIME(0); - time_IO+=proctime; - } -} \ No newline at end of file diff --git a/v3d_main/terafly/src/core/iomanager/plugins/opencv2D/opencv2D.h b/v3d_main/terafly/src/core/iomanager/plugins/opencv2D/opencv2D.h deleted file mode 100644 index 56dd17b964..0000000000 --- a/v3d_main/terafly/src/core/iomanager/plugins/opencv2D/opencv2D.h +++ /dev/null @@ -1,8 +0,0 @@ -#ifndef _OPENCV_FORMAT_H -#define _OPENCV_FORMAT_H - -#include "../../IOPluginAPI.h" - -TERASTITCHER_CREATE_IO_PLUGIN_2D(opencv2D) - -#endif // _OPENCV_FORMAT_H \ No newline at end of file diff --git a/v3d_main/terafly/src/core/iomanager/plugins/tiff2D/CMakeLists.txt b/v3d_main/terafly/src/core/iomanager/plugins/tiff2D/CMakeLists.txt deleted file mode 100644 index 6afe18c6cf..0000000000 --- a/v3d_main/terafly/src/core/iomanager/plugins/tiff2D/CMakeLists.txt +++ /dev/null @@ -1,22 +0,0 @@ -# find all headers and sources -file(GLOB headers *.h) -file(GLOB sources *.cpp) - -# add parent dir to include path -include_directories (../../) - -# get current directory name -get_filename_component(dirname ${CMAKE_CURRENT_SOURCE_DIR} NAME) - -# add static library -add_library(ioplugin_${dirname} STATIC ${headers} ${sources}) - -# include 3rd party libraries -include_directories (${CMAKE_SOURCE_DIR}/3rdparty/zlib) -include_directories (${CMAKE_BINARY_DIR}/3rdparty/zlib) -include_directories (${CMAKE_SOURCE_DIR}/3rdparty/libtiff) -include_directories (${CMAKE_BINARY_DIR}/3rdparty/libtiff) - -# link 3rd party libraries -target_link_libraries(ioplugin_${dirname} zlib) -target_link_libraries(ioplugin_${dirname} tiff) \ No newline at end of file diff --git a/v3d_main/terafly/src/core/iomanager/plugins/tiff2D/tiff2D.cpp b/v3d_main/terafly/src/core/iomanager/plugins/tiff2D/tiff2D.cpp deleted file mode 100644 index ddffc75e91..0000000000 --- a/v3d_main/terafly/src/core/iomanager/plugins/tiff2D/tiff2D.cpp +++ /dev/null @@ -1,570 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* -* Bria, A., Iannello, G., "TeraStitcher - A Tool for Fast 3D Automatic Stitching of Teravoxel-sized Microscopy Images", (2012) BMC Bioinformatics, 13 (1), art. no. 316. -* -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -* 2015-01-02. Giulio. @IMPLEMENTED new plugins interface -*/ - -#include // 2014-09-18. Alessandro. @FIXED compilation issue on gcc compilers. -#include -#include "tiff2D.h" -#include "Tiff3DMngr.h" -#include "VirtualFmtMngr.h" - -#ifndef min -#define min(a,b) ((a)<(b) ? (a) : (b)) -#endif - -// just call this macro to register your plugin -TERASTITCHER_REGISTER_IO_PLUGIN_2D(tiff2D) - -// insert here your plugin description that will be displayed on the user interface -std::string iomanager::tiff2D::desc() -{ - return "******************************************************\n" - "* tiff2D v.1.0 *\n" - "******************************************************\n" - "* *\n" - "* 2D image-based I/O plugin that uses the libtiff li- *\n" - "* brary to read/write 2D image files. *\n" - "* *\n" - "* Supported image format extentions: *\n" - "* - TIFF *\n" - "* - TIF *\n" - "* *\n" - "* Accepted configuration parameters: *\n" - "* - none *\n" - "* *\n" - "******************************************************\n"; -} - - -// Return if channels are interleaved (in case the image has just one channel return value is indefinite) -bool - iomanager::tiff2D::isChansInterleaved( ) -{ - return true; -} - - -// read image metadata from a 2D image file -void - iomanager::tiff2D::readMetadata( - std::string img_path, // (INPUT) image filepath - int & img_width, // (OUTPUT) image width (in pixels) - int & img_height, // (OUTPUT) image height (in pixels) - int & img_bytes_x_chan, // (OUTPUT) number of bytes per channel - int & img_chans, // (OUTPUT) number of channels - const std::string & params) // (INPUT) additional parameters -throw (iom::exception) -{ - /**/iom::debug(iom::LEV3, iom::strprintf("img_path = \"%s\", params = \"%s\"",img_path.c_str(), params.c_str()).c_str(), __iom__current__function__); - - uint16 bpp; - uint16 spp; - - // disable warning handler to avoid messages on unrecognized tags - TIFFSetWarningHandler(0); - - TIFF* input=TIFFOpen(img_path.c_str(),"r"); - if (!input) - throw iom::exception(iom::strprintf("unable to open image \"%s\". Possible unsupported format or it isn't an image.\nSupported format is 2DTIFF", img_path.c_str()), __iom__current__function__); - - if (!TIFFGetField(input, TIFFTAG_IMAGEWIDTH, &img_width)) - throw iom::exception(iom::strprintf("unable to determine 'TIFFTAG_IMAGEWIDTH' from image \"%s\". ", img_path.c_str()), __iom__current__function__); - - if (!TIFFGetField(input, TIFFTAG_IMAGELENGTH, &img_height)) - throw iom::exception(iom::strprintf("unable to determine 'TIFFTAG_IMAGELENGTH' from image \"%s\". ", img_path.c_str()), __iom__current__function__); - - if (!TIFFGetField(input, TIFFTAG_BITSPERSAMPLE, &bpp)) - throw iom::exception(iom::strprintf("unable to determine 'TIFFTAG_BITSPERSAMPLE' from image \"%s\". ", img_path.c_str()), __iom__current__function__); - img_bytes_x_chan = bpp/8; - - if (!TIFFGetField(input, TIFFTAG_SAMPLESPERPIXEL, &spp)) - throw iom::exception(iom::strprintf("unable to determine 'TIFFTAG_SAMPLESPERPIXEL' from image \"%s\". ", img_path.c_str()), __iom__current__function__); - img_chans = spp; - - // Onofri - int img_depth; // image depth (in pixels) - uint16 cpage; // Current page. We do not actually need it. - uint16 npages; // Number of pages. - int PNcheck=TIFFGetField(input, TIFFTAG_PAGENUMBER, &cpage, &npages); - if (!PNcheck || npages==0) { // the tag has not been read correctly - iom::warning(iom::strprintf("unable to determine 'TIFFTAG_PAGENUMBER' from image file \"%s\". ", img_path.c_str()).c_str(),__iom__current__function__); - img_depth = 0; - do { - img_depth++; - } while (TIFFReadDirectory(input)); - } - else - img_depth = npages; - - TIFFClose(input); - - // check the exception after closing the file - if ( img_depth > 1 ) - throw iom::exception(iom::strprintf("image \"%s\" has more than one page.\nSupported format is 2DTIFF", img_path.c_str()), __iom__current__function__); -} - - -// Read 2D image data -unsigned char * // (OUTPUT) a buffer storing the 2D image - iomanager::tiff2D::readData( - std::string img_path, // (INPUT) image filepath - int & img_width, // (INPUT/OUTPUT) image width (in pixels) - int & img_height, // (INPUT/OUTPUT) image height (in pixels) - int & img_bytes_x_chan, // (INPUT/OUTPUT) number of bytes per channel - int & img_chans, // (INPUT/OUTPUT) number of channels to be read - unsigned char *data, // (INPUT) image data - const std::string & params) // (INPUT) additional parameters -throw (iom::exception) -{ - //throw iom::exception(iom::strprintf("not implemented yet"), __iom__current__function__); - - /**/iom::debug(iom::LEV3, iom::strprintf("img_path = %s, img_width 0 %d, img_height 0 %d, img_bytes_x_chan = %d, img_chans = %d, params = \"%s\"", - img_path.c_str(), img_width, img_height, img_bytes_x_chan, img_chans, params.c_str()).c_str(), __iom__current__function__); - - char *err_Tiff3Dfmt; - - //disable warning handler to avoid messages on unrecognized tags - TIFFSetWarningHandler(0); - - if ( !data ) { // recover the metadata, allocate the buffer and set parameters - unsigned int _width; - unsigned int _height; - unsigned int _depth; - int _bytes_x_chan; - unsigned int _chans; - int b_swap; - void *fhandle; - int header_len; - - if ( (err_Tiff3Dfmt = loadTiff3D2Metadata((char *)img_path.c_str(),_width,_height,_depth,_chans,_bytes_x_chan,b_swap,fhandle,header_len)) != 0 ) { - throw iom::exception(iom::strprintf("(%s) unable to read meta data of tiff file %s",err_Tiff3Dfmt,img_path.c_str()), __iom__current__function__); - } - closeTiff3DFile(fhandle); - - data = new unsigned char[_width * _height * _chans * _bytes_x_chan]; - img_width = _width; - img_height = _height; - img_bytes_x_chan = _bytes_x_chan; - img_chans = _chans; - } - - // load 2D image - if ( (err_Tiff3Dfmt = readTiff3DFile2Buffer((char *)img_path.c_str(),data,img_width,img_height,0,0)) != 0 ) { - throw iom::exception(iom::strprintf("(%s) unable to read tiff file %s",err_Tiff3Dfmt,img_path.c_str()), __iom__current__function__); - } - - return data; -} - - -// Write 2D image data into a single (2D) image file -void - iomanager::tiff2D::writeData( - std::string img_path, // (INPUT) image filepath (it includes the file extension) - unsigned char *raw_img, // (INPUT) image data to be saved into the file - int img_height, // (INPUT) image height - int img_width, // (INPUT) image width - int img_bytes_x_chan, // (INPUT) number of bytes per channel - int img_chans, // (INPUT) number of channels - int y0, // (INPUT) region of interest [x0,x1][y0,y1] to be set on the image - int y1, // (INPUT) region of interest [x0,x1][y0,y1] to be set on the image - int x0, // (INPUT) region of interest [x0,x1][y0,y1] to be set on the image - int x1, // (INPUT) region of interest [x0,x1][y0,y1] to be set on the image - const std::string & params) // (INPUT) additional parameters -throw (iom::exception) -{ - //throw iom::exception(iom::strprintf("not implemented yet"), __iom__current__function__); - - /**/iom::debug(iom::LEV3, iom::strprintf("img_path = %s, img_height = %d, img_width = %d, img_bytes_x_chan = %d, img_chans = %d, y0 = %d, y1 = %d, x0 = %d, x1 = %d, params = \"%s\"", - img_path.c_str(), img_height, img_width, img_bytes_x_chan, img_chans, y0, y1, x0, x1, params.c_str()).c_str(), __iom__current__function__); - - // correct default parameters - y0 = (y0 < 0) ? 0: y0; - y1 = (y1 < 0) ? img_height : y1; - x0 = (x0 < 0) ? 0: x0; - x1 = (x1 < 0) ? img_width : x1; - - // compute ROI dimensions - int ROI_height = y1 - y0; - int ROI_width = x1 - x0; - - // precondition checks - if(! (y0>=0 && y1>y0 && y1<=img_height && x0>=0 && x1>x0 && x1<=img_width) ) - throw iom::exception(iom::strprintf("invalid ROI [%d,%d](X) x [%d,%d](Y) on image %d(X) x %d(Y)", x0, x1, y0, y1, img_width, img_height), __iom__current__function__); - if(img_bytes_x_chan != 1 && img_bytes_x_chan != 2) - throw iom::exception(iom::strprintf("unsupported bitdepth %d\n", img_bytes_x_chan*8), __iom__current__function__); - if(img_chans != 1) - throw iom::exception(iom::strprintf("unsupported number of channels = %d\n. Only single-channel images are supported", img_chans), __iom__current__function__); - - // convert raw data to image data - double proctime = -TIME(0); - - char *err_Tiff3Dfmt; - - // creates the file (2D image: depth is 1) - if ( (err_Tiff3Dfmt = initTiff3DFile((char *)img_path.c_str(),ROI_width,ROI_height,1,img_chans,img_bytes_x_chan)) != 0 ) { - throw iom::exception(iom::strprintf("unable to create tiff file (%s)",err_Tiff3Dfmt), __iom__current__function__); - } - - // update conversion time - if(TIME_CALC) - { - proctime += TIME(0); - time_conversions+=proctime; - proctime = -TIME(0); - } - - // save image - - if ( x0 == 0 && x1 == img_width && y0 == 0 && y1 == img_height ) { // all buffer must be written - if ( (err_Tiff3Dfmt = appendSlice2Tiff3DFile((char *)img_path.c_str(),0,raw_img,ROI_width,ROI_height)) != 0 ) { - throw iom::exception(iom::strprintf("unable to save image at \"%s\". Unsupported format or wrong path.\n", img_path.c_str()), __iom__current__function__); - } - } - else { // copy to a sub buffer before writing - iim::sint64 stridex = img_width * img_chans * img_bytes_x_chan; - unsigned char *buf; // to scan the input buffer - iim::sint64 stridex_ROI = (x1-x0) * img_chans * img_bytes_x_chan; - unsigned char *raw_img_ROI = new unsigned char[(y1-y0) * (x1-x0) * img_chans * img_bytes_x_chan]; - - buf = raw_img + x0*stridex + y0*img_chans*img_bytes_x_chan; // buf points to the first byte to be written - - iim::VirtualFmtMngr::copyBlock2SubBuf(buf,raw_img_ROI,(y1-y0),(x1-x0),1,img_bytes_x_chan,stridex,0,stridex_ROI,0); // xy strides are 0 since the buffer is 2D - - if ( (err_Tiff3Dfmt = appendSlice2Tiff3DFile((char *)img_path.c_str(),0,raw_img_ROI,(x1-x0),(y1-y0))) != 0 ) { - throw iom::exception(iom::strprintf("(%s) unable to write 2D image into file %s",err_Tiff3Dfmt,img_path.c_str()), __iom__current__function__); - } - - delete []raw_img_ROI; - } - - // update IO time - if(TIME_CALC) - { - proctime += TIME(0); - time_IO+=proctime; - } -} - - -// read 3D image data from a stack of (2D) image files -iom::real_t* // (OUTPUT) a [0.0,1.0]-valued array storing the 3D image in channel->slice->row order - iomanager::tiff2D::readData( - char **files, // (INPUT) array of C-strings storing image filenames - int files_size, // (INPUT) size of 'files' - const char *path /*= 0*/, // (INPUT) path to be concatenated to the i-th entry of 'files' - int first /*= -1*/, // (INPUT) selects a range [first, last] of files to be loaded - int last /*= -1*/, // (INPUT) selects a range [first, last] of files to be loaded - bool is_sparse /*= false*/, // (INPUT) if true, 'files' is a sparse array and null entries should be treated as empty (black) images - iom::channel chan, // (INPUT) channel selection { ALL, R, G, B }. - const std::string & params) // (INPUT) additional parameters -throw (iom::exception) -{ - throw iom::exception(iom::strprintf("no more available"), __iom__current__function__); - - /**/iom::debug(iom::LEV3, iom::strprintf("files_size = %d, path = %s, first = %d, last = %d, is_sparse = %s, chan = %d, params = \"%s\"", - files_size, path ? path : "null", first, last, is_sparse ? "true" : "false", chan, params.c_str()).c_str(), __iom__current__function__); - - char *err_Tiff3Dfmt; - - unsigned int rows; - unsigned int cols; - unsigned int n_slices; - unsigned int channels; - int depth; - int swap; - void *dummy; - int dummy_len; - - unsigned char *data; - iom::real_t *raw_data; - - iom::real_t *image_stack = 0; - uint64 image_stack_width=0, image_stack_height=0, z=0; - - // check for valid file list - if(!files || files_size <= 0) - throw iom::exception("invalid file list (null pointer or 0-sized)", __iom__current__function__); - - // check and adjust file selection - first = (first == -1 ? 0 : first); - last = (last == -1 ? files_size - 1 : last ); - first = min(first, files_size-1); - last = min(last, files_size-1); - - //disable warning handler to avoid messages on unrecognized tags - TIFFSetWarningHandler(0); - - // build absolute image path of first file in the stack - int i = 0; - while ( is_sparse && i(i); -// for(int j=0; j(i); -// for(int j=0; jrow order - int img_height, // (INPUT) image height - int img_width, // (INPUT) image width - int img_chans, // (INPUT) number of channels - int y0, // (INPUT) region of interest [x0,x1][y0,y1] to be set on the image - int y1, // (INPUT) region of interest [x0,x1][y0,y1] to be set on the image - int x0, // (INPUT) region of interest [x0,x1][y0,y1] to be set on the image - int x1, // (INPUT) region of interest [x0,x1][y0,y1] to be set on the image - int bpp, // (INPUT) color depth (bits per pixel) - const std::string & params) // (INPUT) additional parameters -throw (iom::exception) -{ - throw iom::exception(iom::strprintf("no more available"), __iom__current__function__); - - /**/iom::debug(iom::LEV3, iom::strprintf("img_path = %s, img_height = %d, img_width = %d, y0 = %d, y1 = %d, x0 = %d, x1 = %d, bpp = %d, params = \"%s\"", - img_path.c_str(), img_height, img_width, y0, y1, x0, x1, bpp, params.c_str()).c_str(), __iom__current__function__); - - - // correct default parameters - y1 = (y1 == -1 ? img_height - 1 : y1); - x1 = (x1 == -1 ? img_width - 1 : x1 ); - - // compute ROI dimensions - int ROI_height = y1 - y0 + 1; - int ROI_width = x1 - x0 + 1; - - // precondition checks - if(! (y0>=0 && y1>y0 && y1=0 && x1>x0 && x1(raw_img[(i+y0)*img_width+j+x0] * 255.0f + 0.5f); - } - } - else // bpp == 16 - { - for(int i = 0; i (raw_img[(i+y0)*img_width+j+x0] * 65535.0f + 0.5f); - } - } - - // update conversion time - if(TIME_CALC) - { - proctime += TIME(0); - time_conversions+=proctime; - proctime = -TIME(0); - } - - // save image - if ( (err_Tiff3Dfmt = appendSlice2Tiff3DFile((char *)img_path.c_str(),0,buffer,ROI_width,ROI_height)) != 0 ) { - throw iom::exception(iom::strprintf("unable to save image at \"%s\". Unsupported format or wrong path.\n", img_path.c_str()), __iom__current__function__); - } - - delete []buffer; - - // update IO time - if(TIME_CALC) - { - proctime += TIME(0); - time_IO+=proctime; - } -} \ No newline at end of file diff --git a/v3d_main/terafly/src/core/iomanager/plugins/tiff2D/tiff2D.h b/v3d_main/terafly/src/core/iomanager/plugins/tiff2D/tiff2D.h deleted file mode 100755 index fac0c29dbb..0000000000 --- a/v3d_main/terafly/src/core/iomanager/plugins/tiff2D/tiff2D.h +++ /dev/null @@ -1,8 +0,0 @@ -#ifndef _TIFF2D_FORMAT_H -#define _TIFF2D_FORMAT_H - -#include "../../IOPluginAPI.h" - -TERASTITCHER_CREATE_IO_PLUGIN_2D(tiff2D) - -#endif // _TIFF2D_FORMAT_H \ No newline at end of file diff --git a/v3d_main/terafly/src/core/iomanager/plugins/tiff3D/CMakeLists.txt b/v3d_main/terafly/src/core/iomanager/plugins/tiff3D/CMakeLists.txt deleted file mode 100644 index 6afe18c6cf..0000000000 --- a/v3d_main/terafly/src/core/iomanager/plugins/tiff3D/CMakeLists.txt +++ /dev/null @@ -1,22 +0,0 @@ -# find all headers and sources -file(GLOB headers *.h) -file(GLOB sources *.cpp) - -# add parent dir to include path -include_directories (../../) - -# get current directory name -get_filename_component(dirname ${CMAKE_CURRENT_SOURCE_DIR} NAME) - -# add static library -add_library(ioplugin_${dirname} STATIC ${headers} ${sources}) - -# include 3rd party libraries -include_directories (${CMAKE_SOURCE_DIR}/3rdparty/zlib) -include_directories (${CMAKE_BINARY_DIR}/3rdparty/zlib) -include_directories (${CMAKE_SOURCE_DIR}/3rdparty/libtiff) -include_directories (${CMAKE_BINARY_DIR}/3rdparty/libtiff) - -# link 3rd party libraries -target_link_libraries(ioplugin_${dirname} zlib) -target_link_libraries(ioplugin_${dirname} tiff) \ No newline at end of file diff --git a/v3d_main/terafly/src/core/iomanager/plugins/tiff3D/tiff3D.cpp b/v3d_main/terafly/src/core/iomanager/plugins/tiff3D/tiff3D.cpp deleted file mode 100644 index 552ebedff3..0000000000 --- a/v3d_main/terafly/src/core/iomanager/plugins/tiff3D/tiff3D.cpp +++ /dev/null @@ -1,382 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* -* Bria, A., Iannello, G., "TeraStitcher - A Tool for Fast 3D Automatic Stitching of Teravoxel-sized Microscopy Images", (2012) BMC Bioinformatics, 13 (1), art. no. 316. -* -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -* 2015-01-02. Giulio. @IMPLEMENTED new plugins interface -*/ - -#include // 2014-09-18. Alessandro. @FIXED compilation issue on gcc compilers. -#include -#include "tiff3D.h" -#include "Tiff3DMngr.h" -#include "VirtualFmtMngr.h" - -// just call this macro to register your plugin -TERASTITCHER_REGISTER_IO_PLUGIN_3D(tiff3D) - -// insert here your plugin description that will be displayed on the user interface -std::string iomanager::tiff3D::desc() -{ - return "******************************************************\n" - "* tiff3D v.1.0 *\n" - "******************************************************\n" - "* *\n" - "* 3D image-based I/O plugin that uses the libtiff *\n" - "* library to read/write multipage tiffs. *\n" - "* *\n" - "* Supported image format extentions: *\n" - "* - TIFF *\n" - "* - TIF *\n" - "* *\n" - "* Accepted configuration parameters: *\n" - "* - none *\n" - "* *\n" - "******************************************************\n"; -} - - -// Return if channels are interleaved (in case the image has just one channel return value is indefinite) -bool - iomanager::tiff3D::isChansInterleaved( ) -{ - return true; -} - - -// read image metadata -void - iomanager::tiff3D::readMetadata( - std::string img_path, // (INPUT) image filepath - int & img_width, // (OUTPUT) image width (in pixels) - int & img_height, // (OUTPUT) image height (in pixels) - int & img_depth, // (OUTPUT) image depth (in pixels) - int & img_bytes_x_chan, // (OUTPUT) number of bytes per channel - int & img_chans, // (OUTPUT) number of channels - const std::string & params) // (INPUT) additional parameters -throw (iom::exception) -{ - /**/iom::debug(iom::LEV3, iom::strprintf("img_path = %s, img_width = %d, img_height = %d, img_depth = %d, img_bytes_x_chan = %d, img_chans = %d, params = \"%s\"", - img_path.c_str(), img_width, img_height, img_depth, img_bytes_x_chan, img_chans, params.c_str()).c_str(), __iom__current__function__); - - // disable warning handler to avoid messages on unrecognized tags - TIFFSetWarningHandler(0); - - TIFF* input=TIFFOpen(img_path.c_str(),"r"); - if (!input) - throw iom::exception(iom::strprintf("unable to open image \"%s\". Possible unsupported format or it isn't an image.\nSupported format is 3DTIFF", img_path.c_str()), __iom__current__function__); - - if (!TIFFGetField(input, TIFFTAG_IMAGEWIDTH, &img_width)) - throw iom::exception(iom::strprintf("unable to determine 'TIFFTAG_IMAGEWIDTH' from image \"%s\". ", img_path.c_str()), __iom__current__function__); - - if (!TIFFGetField(input, TIFFTAG_IMAGELENGTH, &img_height)) - throw iom::exception(iom::strprintf("unable to determine 'TIFFTAG_IMAGELENGTH' from image \"%s\". ", img_path.c_str()), __iom__current__function__); - - if (!TIFFGetField(input, TIFFTAG_BITSPERSAMPLE, &img_bytes_x_chan)) - throw iom::exception(iom::strprintf("unable to determine 'TIFFTAG_BITSPERSAMPLE' from image \"%s\". ", img_path.c_str()), __iom__current__function__); - img_bytes_x_chan /= 8; - - if (!TIFFGetField(input, TIFFTAG_SAMPLESPERPIXEL, &img_chans)) - throw iom::exception(iom::strprintf("unable to determine 'TIFFTAG_SAMPLESPERPIXEL' from image \"%s\". ", img_path.c_str()), __iom__current__function__); - - // Onofri - uint16 cpage; // Current page. We do not actually need it. - uint16 npages; // Number of pages. - int PNcheck=TIFFGetField(input, TIFFTAG_PAGENUMBER, &cpage, &npages); - if (!PNcheck || npages==0) { // the tag has not been read correctly - iom::warning(iom::strprintf("unable to determine 'TIFFTAG_PAGENUMBER' from image file \"%s\". ", img_path.c_str()).c_str(),__iom__current__function__); - img_depth = 0; - do { - img_depth++; - } while (TIFFReadDirectory(input)); - } - else - img_depth = npages; - - TIFFClose(input); -} - - -// Read 3D image data -unsigned char * // (OUTPUT) buffer containing the read image data - iomanager::tiff3D::readData( - std::string img_path, // (INPUT) image filepath - int & img_width, // (INPUT/OUTPUT) image width (in pixels) - int & img_height, // (INPUT/OUTPUT) image height (in pixels) - int & img_depth, // (INPUT/OUTPUT) image depth (in pixels) - int & img_bytes_x_chan, // (INPUT/OUTPUT) number of bytes per channel - int & img_chans, // (INPUT/OUTPUT) number of channels to be read - unsigned char *data, // (INPUT) image data - int z0, // (INPUT) region of interest [x0,x1)[y0,y1)[z0,z1) to be set on the image - int z1, // (INPUT) region of interest [x0,x1)[y0,y1)[z0,z1) to be set on the image - const std::string & params) // (INPUT) additional parameters -throw (iom::exception) -{ - //throw iom::exception(iom::strprintf("not implemented yet"), __iom__current__function__); - - /**/iom::debug(iom::LEV3, iom::strprintf("img_path = %s, img_width = %d, img_height = %d, img_depth = %d, img_bytes_x_chan = %d, img_chans = %d, data = %p, z0 = %d, z1 = %d, params = \"%s\"", - img_path.c_str(), img_width, img_height, img_depth, img_bytes_x_chan, img_chans, data, z0, z1, params.c_str()).c_str(), __iom__current__function__); - - //disable warning handler to avoid messages on unrecognized tags - TIFFSetWarningHandler(0); - - unsigned int _width; - unsigned int _height; - unsigned int _depth; - int _bytes_x_chan; - unsigned int _chans; - int b_swap; - void *fhandle; - int header_len; - char *err_Tiff3Dfmt; - - if ( !data ) { // recover the metadata, allocate the buffer and set parameters - if ( (err_Tiff3Dfmt = loadTiff3D2Metadata((char *)img_path.c_str(),_width,_height,_depth,_chans,_bytes_x_chan,b_swap,fhandle,header_len)) != 0 ) { - throw iom::exception(iom::strprintf("(%s) unable to read meta data of tiff file %s",err_Tiff3Dfmt,img_path.c_str()), __iom__current__function__); - } - closeTiff3DFile(fhandle); - - data = new unsigned char[_width * _height * _depth * _chans * _bytes_x_chan]; - img_width = _width; - img_height = _height; - img_depth = _depth; - img_bytes_x_chan = _bytes_x_chan; - img_chans = _chans; - } - - // set the ROI - z0 = (z0 < 0) ? 0: z0; - z1 = (z1 < 0) ? img_depth : z1; - - if ( z0 >= z1 ) - throw iom::exception(iom::strprintf("wrong slice indices (z0 = %d, z1 = %d)",z0, z1), __iom__current__function__); - - // get the image - if ( (err_Tiff3Dfmt = readTiff3DFile2Buffer((char *)img_path.c_str(),data,img_width,img_height,z0,z1-1)) != 0 ) { - throw iom::exception(iom::strprintf("(%s) unable to read tiff file %s in page range [%d,%d]",err_Tiff3Dfmt,img_path.c_str(),z0,z1-1), __iom__current__function__); - } - - return data; -} - - -// Write 3D image data into a single (3D) image file -void - iomanager::tiff3D::writeData( - std::string img_path, // (INPUT) image filepath (it includes the file extension) - unsigned char * raw_img, // (INPUT) image data to be saved into the file - int img_height, // (INPUT) image height (in pixels) - int img_width, // (INPUT) image width (in pixels) - int img_depth, // (INPUT) image depth (in pixels) - int img_bytes_x_chan, // (INPUT) number of bytes per channel - int img_chans, // (INPUT) number of channels - int z0, // (INPUT) region of interest [x0,x1)[y0,y1)[z0,z1) to be set on the image - int z1, // (INPUT) region of interest [x0,x1)[y0,y1)[z0,z1) to be set on the image - int y0, // (INPUT) region of interest [x0,x1)[y0,y1)[z0,z1) to be set on the image - int y1, // (INPUT) region of interest [x0,x1)[y0,y1)[z0,z1) to be set on the image - int x0, // (INPUT) region of interest [x0,x1)[y0,y1)[z0,z1) to be set on the image - int x1, // (INPUT) region of interest [x0,x1)[y0,y1)[z0,z1) to be set on the image - const std::string & params) // (INPUT) additional parameters -throw (iom::exception) -{ - //throw iom::exception(iom::strprintf("not implemented yet"), __iom__current__function__); - - /**/iom::debug(iom::LEV3, iom::strprintf("img_path = %s, img_width = %d, img_height = %d, img_depth = %d, img_bytes_x_chan = %d, img_chans = %d, z0 = %d, z1 = %d, y0 = %d, y1 = %d, x0 = %d, x1 = %d, params = \"%s\"", - img_path.c_str(), img_width, img_height, img_depth, img_bytes_x_chan, img_chans, z0, z1, y0, y1, x0, x1, params.c_str()).c_str(), __iom__current__function__); - - //disable warning handler to avoid messages on unrecognized tags - TIFFSetWarningHandler(0); - - iim::sint64 stridex = img_width * img_chans * img_bytes_x_chan; - iim::sint64 stridexy = stridex * img_height; - unsigned char *buf; // to scan the input buffer - - char *err_Tiff3Dfmt; - - z0 = (z0 < 0) ? 0: z0; - z1 = (z1 < 0) ? img_depth : z1; - y0 = (y0 < 0) ? 0: y0; - y1 = (y1 < 0) ? img_height : y1; - x0 = (x0 < 0) ? 0: x0; - x1 = (x1 < 0) ? img_width : x1; - - if ( z0 >= z1 || y0 >= y1 || x0 >= x1 ) - throw iom::exception(iom::strprintf("wrong ROI (z0 = %d, z1 = %d, y0 = %d, y1 = %d, x0 = %d, x1 = %d)",z0, z1, y0, y1, x0, x1), __iom__current__function__); - - // creates an empty file - if ( (err_Tiff3Dfmt = initTiff3DFile((char *)img_path.c_str(),(x1-x0),(y1-y0),(z1-z0),img_chans,img_bytes_x_chan)) != 0 ) { - throw iom::exception(iom::strprintf("(%s) unable to create an empty tiff file %s",err_Tiff3Dfmt,img_path.c_str()), __iom__current__function__); - } - - // append slice by slice - - buf = raw_img + z0*stridexy + x0*stridex + y0*img_chans*img_bytes_x_chan; // buf points to the first byte to be written - - if ( x0 == 0 && x1 == img_width && y0 == 0 && y1 == img_height ) { // all buffer must be written - for ( int i=0; i<(z1-z0); i++, buf += stridexy ) { - if ( (err_Tiff3Dfmt = appendSlice2Tiff3DFile((char *)img_path.c_str(),i,buf,img_width,img_height)) != 0 ) { - throw iom::exception(iom::strprintf("(%s) unable to write slice %d into file %s",err_Tiff3Dfmt,z0+i,img_path.c_str()), __iom__current__function__); - } - } - } - else { // copy to a sub buffer before writing - iim::sint64 stridex_ROI = (x1-x0) * img_chans * img_bytes_x_chan; - iim::sint64 stridexy_ROI = stridex_ROI * (y1-y0); - unsigned char *raw_img_ROI = new unsigned char[(z1-z0) * (y1-y0) * (x1-x0) * img_chans * img_bytes_x_chan]; - unsigned char *buf_ROI; - - iim::VirtualFmtMngr::copyBlock2SubBuf(buf,raw_img_ROI,(y1-y0),(x1-x0),(z1-z0),img_bytes_x_chan,stridex,stridexy,stridex_ROI,stridexy_ROI); - - buf_ROI = raw_img_ROI; - for ( int i=0; i<(z1-z0); i++, buf_ROI += stridexy_ROI ) { - if ( (err_Tiff3Dfmt = appendSlice2Tiff3DFile((char *)img_path.c_str(),i,buf_ROI,(x1-x0),(y1-y0))) != 0 ) { - throw iom::exception(iom::strprintf("(%s) unable to write slice %d into file %s",err_Tiff3Dfmt,z0+i,img_path.c_str()), __iom__current__function__); - } - } - delete []raw_img_ROI; - } -} - - -// Create an empty 3D image -void - iomanager::tiff3D::create3Dimage( - std::string img_path, // (INPUT) image filepath (it includes the file extension) - int img_height, // (INPUT) image height (in pixels) - int img_width, // (INPUT) image width (in pixels) - int img_depth, // (INPUT) image depth (in pixels) - int img_bytes_x_chan, // (INPUT) number of bytes per channel - int img_chans, // (INPUT) number of channels - const std::string & params) // (INPUT) additional parameters -throw (iom::exception) -{ - //throw iom::exception(iom::strprintf("not implemented yet"), __iom__current__function__); - - /**/iom::debug(iom::LEV3, iom::strprintf("img_path = %s, img_width = %d, img_height = %d, img_depth = %d, img_bytes_x_chan = %d, img_chans = %d, params = \"%s\"", - img_path.c_str(), img_width, img_height, img_depth, img_bytes_x_chan, img_chans, params.c_str()).c_str(), __iom__current__function__); - - // disable warning handler to avoid messages on unrecognized tags - TIFFSetWarningHandler(0); - - char *err_Tiff3Dfmt; - - // creates an empty file - if ( (err_Tiff3Dfmt = initTiff3DFile((char *)img_path.c_str(),img_width,img_height,img_depth,img_chans,img_bytes_x_chan)) != 0 ) { - throw iom::exception(iom::strprintf("(%s) unable to create an empty tiff file %s",err_Tiff3Dfmt,img_path.c_str()), __iom__current__function__); - } -} - - -// Append a single slice at the bottom of a 3D image file -void - iomanager::tiff3D::appendSlice( - std::string img_path, // (INPUT) image filepath (it includes the file extension) - unsigned char * raw_img, // (INPUT) slice to be saved into the file - int img_height, // (INPUT) slice height (in pixels) - int img_width, // (INPUT) slice width (in pixels) - int img_bytes_x_chan, // (INPUT) number of bytes per channel - int img_chans, // (INPUT) number of channels - int y0, // (INPUT) region of interest [x0,x1)[y0,y1) to be set on the image - int y1, // (INPUT) region of interest [x0,x1)[y0,y1) to be set on the image - int x0, // (INPUT) region of interest [x0,x1)[y0,y1) to be set on the image - int x1, // (INPUT) region of interest [x0,x1)[y0,y1) to be set on the image - int slice, // (INPUT) slice index - const std::string & params) // (INPUT) additional parameters -throw (iom::exception) -{ - //throw iom::exception(iom::strprintf("not implemented yet"), __iom__current__function__); - - /**/iom::debug(iom::LEV3, iom::strprintf("img_path = %s, img_width = %d, img_height = %d, img_bytes_x_chan = %d, img_chans = %d, y0 = %d, y1 = %d, x0 = %d, x1 = %d, params = \"%s\"", - img_path.c_str(), img_width, img_height, img_bytes_x_chan, img_chans, y0, y1, x0, x1, params.c_str()).c_str(), __iom__current__function__); - - //disable warning handler to avoid messages on unrecognized tags - TIFFSetWarningHandler(0); - - iim::sint64 stridex = img_width * img_chans * img_bytes_x_chan; - unsigned char *buf; // to scan the input buffer - - char *err_Tiff3Dfmt; - - y0 = (y0 < 0) ? 0: y0; - y1 = (y1 < 0) ? img_height : y1; - x0 = (x0 < 0) ? 0: x0; - x1 = (x1 < 0) ? img_width : x1; - - if ( y0 >= y1 || x0 >= x1 ) - throw iom::exception(iom::strprintf("wrong ROI (y0 = %d, y1 = %d, x0 = %d, x1 = %d)", y0, y1, x0, x1), __iom__current__function__); - - // append a slice - - buf = raw_img + x0*stridex + y0*img_chans*img_bytes_x_chan; // buf points to the first byte to be written - - if ( x0 == 0 && x1 == img_width && y0 == 0 && y1 == img_height ) { // all buffer must be written - if ( (err_Tiff3Dfmt = appendSlice2Tiff3DFile((char *)img_path.c_str(),slice,buf,img_width,img_height)) != 0 ) { - throw iom::exception(iom::strprintf("(%s) unable to write slice %d into file %s",err_Tiff3Dfmt,slice,img_path.c_str()), __iom__current__function__); - } - } - else { // copy to a sub buffer before writing - iim::sint64 stridex_ROI = (x1-x0) * img_chans * img_bytes_x_chan; - iim::sint64 stridexy_ROI = stridex_ROI * (y1-y0); // just because required by 'copyBlock2SubBuf', not actually used - iim::sint64 stridexy = stridex * img_height; // just because required by 'copyBlock2SubBuf', not actually used - unsigned char *raw_img_ROI = new unsigned char[(y1-y0) * (x1-x0) * img_chans * img_bytes_x_chan]; - - iim::VirtualFmtMngr::copyBlock2SubBuf(buf,raw_img_ROI,(y1-y0),(x1-x0),1,img_bytes_x_chan,stridex,stridexy,stridex_ROI,stridexy_ROI); - - if ( (err_Tiff3Dfmt = appendSlice2Tiff3DFile((char *)img_path.c_str(),slice,raw_img_ROI,(x1-x0),(y1-y0))) != 0 ) { - throw iom::exception(iom::strprintf("(%s) unable to write slice %d into file %s",err_Tiff3Dfmt,slice,img_path.c_str()), __iom__current__function__); - } - delete []raw_img_ROI; - } -} - - -// read image data -void - iomanager::tiff3D::readData( - char *finName, // image filepath - int XSIZE, // image width (in pixels) - int YSIZE, // image height (in pixels) - unsigned char *data, // (OUTPUT) image data - int first, // selects a range [first, last] of files to be loaded - int last, // selects a range [first, last] of files to be loaded - const std::string & params) // (INPUT) additional parameters -throw (iom::exception) -{ - throw iom::exception(iom::strprintf("no more available"), __iom__current__function__); - - /**/iom::debug(iom::LEV3, iom::strprintf("finName = %s, XSIZE = %d, YSIZE = %d, first = %d, last = %d, params = \"%s\"", - finName, XSIZE, YSIZE, first, last, params.c_str()).c_str(), __iom__current__function__); - - //disable warning handler to avoid messages on unrecognized tags - TIFFSetWarningHandler(0); - - char *err_Tiff3Dfmt; - if ( (err_Tiff3Dfmt = readTiff3DFile2Buffer(finName,data,XSIZE,YSIZE,first,last)) != 0 ) { - throw iom::exception(iom::strprintf("(%s) unable to read tiff file %s in page range [%d,%d]",err_Tiff3Dfmt,finName,first,last), __iom__current__function__); - } -} \ No newline at end of file diff --git a/v3d_main/terafly/src/core/iomanager/plugins/tiff3D/tiff3D.h b/v3d_main/terafly/src/core/iomanager/plugins/tiff3D/tiff3D.h deleted file mode 100755 index d32cd3103b..0000000000 --- a/v3d_main/terafly/src/core/iomanager/plugins/tiff3D/tiff3D.h +++ /dev/null @@ -1,8 +0,0 @@ -#ifndef _TIFF3D_FORMAT_H -#define _TIFF3D_FORMAT_H - -#include "../../IOPluginAPI.h" - -TERASTITCHER_CREATE_IO_PLUGIN_3D(tiff3D) - -#endif //_TIFF3D_FORMAT_H \ No newline at end of file diff --git a/v3d_main/terafly/src/core/stitcher/CMakeLists.txt b/v3d_main/terafly/src/core/stitcher/CMakeLists.txt deleted file mode 100644 index 200b96fc3c..0000000000 --- a/v3d_main/terafly/src/core/stitcher/CMakeLists.txt +++ /dev/null @@ -1,22 +0,0 @@ -# CmakeLists.txt in Stitcher dir - -# Make sure the compiler can find include files of other modules. -include_directories (${CMAKE_SOURCE_DIR}/3rdparty/zlib) -include_directories (${CMAKE_BINARY_DIR}/3rdparty/zlib) -include_directories (${CMAKE_SOURCE_DIR}/3rdparty/libtiff) -include_directories (${CMAKE_BINARY_DIR}/3rdparty/libtiff) -include_directories (${TeraStitcher_SOURCE_DIR}/imagemanager) -include_directories (${TeraStitcher_SOURCE_DIR}/iomanager) -include_directories (${TeraStitcher_SOURCE_DIR}/tinyxml) -include_directories (${TeraStitcher_SOURCE_DIR}/volumemanager) -include_directories (${TeraStitcher_SOURCE_DIR}/crossmips) - -#disabling annoying warnings -warnings_disable(CMAKE_CXX_FLAGS /wd4290) # vs2012: can't properly handle exceptions -warnings_disable(CMAKE_CXX_FLAGS /wd4996) # vs2012: complains about unsafe standard C++ functions - - -# Adds a library called stitcher (stitcher.a under Linux, stitcher.lib under Windows) from the all .h and .cpp files -file(GLOB stitcher_headers *.h) -file(GLOB stitcher_sources *.cpp) -add_library(stitcher STATIC ${stitcher_headers} ${stitcher_sources}) \ No newline at end of file diff --git a/v3d_main/terafly/src/core/stitcher/Displacement.cpp b/v3d_main/terafly/src/core/stitcher/Displacement.cpp deleted file mode 100644 index f3f599db2a..0000000000 --- a/v3d_main/terafly/src/core/stitcher/Displacement.cpp +++ /dev/null @@ -1,106 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* -* Bria, A., Iannello, G., "TeraStitcher - A Tool for Fast 3D Automatic Stitching of Teravoxel-sized Microscopy Images", (2012) BMC Bioinformatics, 13 (1), art. no. 316. -* -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -#include "Displacement.h" -#include "DisplacementMIPNCC.h" -#include "S_config.h" -#include - -Displacement::Displacement(void) -{ - #if S_VERBOSE>5 - printf("..........in Displacement::Displacement(void)\n"); - #endif - - TYPE = -1; - VHD_def_coords[0] = VHD_def_coords[1] = VHD_def_coords [2] = std::numeric_limits::max(); -} - -Displacement* Displacement::getDisplacementFromXML(TiXmlElement *displ_node) throw (iom::exception) -{ - #if S_VERBOSE>5 - printf("..........in Displacement::getDisplacementFromXML(int displ_type=%d, TiXmlElement *displ_node)\n",displ_type); - #endif - - const char *displ_type = displ_node->Attribute("TYPE"); - if (strcmp(displ_type, "MIP_NCC") == 0) - return (Displacement*)(new DisplacementMIPNCC(displ_node)); - else - { - char err_msg[200]; - sprintf(err_msg, "in Displacement::getDisplacementFromXML(....): unsupported displacement type (\"%s\")", displ_type); - throw iom::exception(err_msg); - } -} - -//instances a displacement which is a deep copy of the given displacement -Displacement* Displacement::instance(Displacement* displacement) throw (iom::exception) -{ - #if S_VERBOSE>5 - printf("..........in Displacement::instance(displacement)\n"); - #endif - - if (displacement->TYPE == S_MIP_NCC_DISPL_TYPE) - { - DisplacementMIPNCC* displ_MIPNCC = (DisplacementMIPNCC*)displacement; - return (Displacement*)(new DisplacementMIPNCC(*displ_MIPNCC)); - } - else - { - char err_msg[200]; - sprintf(err_msg, "in Displacement::instance(displacement): unsupported displacement type (\"%d\")", displacement->TYPE); - throw iom::exception(err_msg); - } -} - -/************************************************************************************************************* -* The given vector of redundant displacements along D is projected into the displacement which embeds the most -* reliable parameters. After this operation, the given vector will contain only the projected displacement. -**************************************************************************************************************/ -void Displacement::projectDisplacements(std::vector &displacements) throw (iom::exception) -{ - #if S_VERBOSE>2 - printf("....in Displacement::projectDisplacements(displacements[size=%d])\n",displacements.size()); - #endif - - if(displacements.size() <= 0) - throw iom::exception("in Displacement::projectDisplacements(...): the given vector of displacements is EMPTY. Nothing to project."); - - //performing projection pairwise. At the end of this process, the last - //displacement will contain the displacement resulting from projection. - for(int i=0; icombine(*displacements[i+1]); - - //the current displacement is now useless - delete displacements[i]; - } - Displacement* projected_displ = displacements[displacements.size()-1]; - displacements.clear(); - displacements.push_back(projected_displ); -} diff --git a/v3d_main/terafly/src/core/stitcher/Displacement.h b/v3d_main/terafly/src/core/stitcher/Displacement.h deleted file mode 100644 index fb7d9122db..0000000000 --- a/v3d_main/terafly/src/core/stitcher/Displacement.h +++ /dev/null @@ -1,105 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* -* Bria, A., Iannello, G., "TeraStitcher - A Tool for Fast 3D Automatic Stitching of Teravoxel-sized Microscopy Images", (2012) BMC Bioinformatics, 13 (1), art. no. 316. -* -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -#ifndef DISPLACEMENT_H -#define DISPLACEMENT_H - -#include "tinyxml.h" -#include -#include "iomanager.config.h" - -enum direction {dir_vertical = 0, dir_horizontal = 1, dir_depth = 2, invalid = -1}; - -class Displacement -{ - protected: - - int TYPE; //type of displacement - int VHD_def_coords[3]; //default VHD displacements as offsets of the second stack with respect to the first one - - public: - - Displacement(void); - virtual ~Displacement(void){}; - - - /*** ABSTRACT METHODS that derived classes must implement ***/ - - //evaluates displacement reliability possibly along the given direction. The result(s) should be stored - //in one or more object members, so that they have to be computed once and then accessed by GET methods - virtual float evalReliability(direction _direction=invalid) throw (iom::exception) = 0; - - //returns the reliability possibly along the given direction. An exception is thrown if the reliability - //index(es) are not computed yet. Values are in [0,1] where 0 = totally unreliable, 1 = reliable - virtual float getReliability(direction _direction=invalid) throw (iom::exception) = 0; - - //returns the displacement along the given direction - virtual int getDisplacement(direction _direction) throw (iom::exception) = 0; - - //sets to default values the displacements with a reliability factor above the given threshold - virtual void threshold(float rel_threshold) throw (iom::exception) = 0; - - //returns the displacement mirrored along the given direction. - virtual Displacement* getMirrored(direction _direction) throw (iom::exception) = 0; - - //combines the parameters of the current and the given displacement so that after this operation - //the two displacements are more reliable (and are EQUAL). - virtual void combine(Displacement& displ) throw (iom::exception) = 0; - - //XML methods: convert/load displacement object into/from XML schema - virtual TiXmlElement* getXML() throw (iom::exception) = 0; - virtual void loadXML(TiXmlElement *displ_node) throw (iom::exception) = 0; - - /*** PUBLIC METHODS that derived classes inherit and can override ***/ - - /************************************************************************************************************* - * Set methods - **************************************************************************************************************/ - void setDefaultV(int V){VHD_def_coords[0] = V;} - void setDefaultH(int H){VHD_def_coords[1] = H;} - void setDefaultD(int D){VHD_def_coords[2] = D;} - - - - //*** CLASS methods *** - - //instances the specified displacement object from an XML element - static Displacement* getDisplacementFromXML(TiXmlElement *displ_node) throw (iom::exception); - - //instances a displacement which is a deep copy of the given displacement - static Displacement* instance(Displacement* displacement) throw (iom::exception); - - /************************************************************************************************************* - * The given vector of redundant displacements along D is projected into the displacement which embeds the most - * reliable parameters. After this operation, the given vector will contain only the projected displacement. - **************************************************************************************************************/ - static void projectDisplacements(std::vector &displacements) throw (iom::exception); - -}; - -#endif /*DISPLACEMENT_H*/ - diff --git a/v3d_main/terafly/src/core/stitcher/DisplacementMIPNCC.cpp b/v3d_main/terafly/src/core/stitcher/DisplacementMIPNCC.cpp deleted file mode 100644 index 15a6149cf7..0000000000 --- a/v3d_main/terafly/src/core/stitcher/DisplacementMIPNCC.cpp +++ /dev/null @@ -1,367 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* -* Bria, A., Iannello, G., "TeraStitcher - A Tool for Fast 3D Automatic Stitching of Teravoxel-sized Microscopy Images", (2012) BMC Bioinformatics, 13 (1), art. no. 316. -* -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -#include "DisplacementMIPNCC.h" -#include "S_config.h" -#include - -DisplacementMIPNCC::DisplacementMIPNCC(void) : Displacement() -{ - #if S_VERBOSE>5 - printf("..........in DisplacementMIPNCC::DisplacementMIPNCC(void)\n"); - #endif - - VHD_coords[0] = VHD_coords[1] = VHD_coords [2] = std::numeric_limits::max(); - NCC_maxs[0] = NCC_maxs[1] = NCC_maxs[2] = -1.0F; - NCC_widths[0] = NCC_widths[1] = NCC_widths[2] = -1; - rel_factors[0] = rel_factors[1] = rel_factors[2] = -1.0F; - delays[0] = delays[1] = delays[2]= -1; - wRangeThrs[0] = wRangeThrs[1] = wRangeThrs[2] = -1; - invWidths[0] = invWidths[1] = invWidths[2] = -1; - TYPE = S_MIP_NCC_DISPL_TYPE; -} - -DisplacementMIPNCC::DisplacementMIPNCC(NCC_descr_t &mip_ncc_descr) : Displacement() -{ - #if S_VERBOSE>5 - printf("..........in DisplacementMIPNCC::DisplacementMIPNCC(NCC_descr_t &mip_ncc_descr)\n"); - #endif - - VHD_coords[0] = mip_ncc_descr.coord[0]; - VHD_coords[1] = mip_ncc_descr.coord[1]; - VHD_coords[2] = mip_ncc_descr.coord[2]; - NCC_maxs[0] = mip_ncc_descr.NCC_maxs[0]; - NCC_maxs[1] = mip_ncc_descr.NCC_maxs[1]; - NCC_maxs[2] = mip_ncc_descr.NCC_maxs[2]; - NCC_widths[0] = mip_ncc_descr.NCC_widths[0]; - NCC_widths[1] = mip_ncc_descr.NCC_widths[1]; - NCC_widths[2] = mip_ncc_descr.NCC_widths[2]; - rel_factors[0] = rel_factors[1] = rel_factors[2] = -1.0F; - delays[0] = delays[1] = delays[2]= -1; - wRangeThrs[0] = wRangeThrs[1] = wRangeThrs[2] = -1; - invWidths[0] = invWidths[1] = invWidths[2] = -1; - TYPE = S_MIP_NCC_DISPL_TYPE; -} - - -DisplacementMIPNCC::DisplacementMIPNCC(int Vnominal, int Hnominal, int Dnominal) : Displacement() -{ - #if S_VERBOSE>5 - printf("..........in DisplacementMIPNCC::DisplacementMIPNCC(int Vnominal, int Hnominal, int Dnominal)\n"); - #endif - - NCC_maxs[0] = NCC_maxs[1] = NCC_maxs[2] = 0.0F; - NCC_widths[0] = NCC_widths[1] = NCC_widths[2] = S_NCC_WIDTH_MAX; - delays[0] = delays[1] = delays[2]= -1; - wRangeThrs[0] = wRangeThrs[1] = wRangeThrs[2] = S_NCC_WIDTH_MAX - 1; - invWidths[0] = invWidths[1] = invWidths[2] = S_NCC_WIDTH_MAX; - rel_factors[0] = rel_factors[1] = rel_factors[2] = 0.0F; - VHD_def_coords[0] = VHD_coords[0] = Vnominal; - VHD_def_coords[1] = VHD_coords[1] = Hnominal; - VHD_def_coords[2] = VHD_coords[2] = Dnominal; - TYPE = S_MIP_NCC_DISPL_TYPE; -} - -DisplacementMIPNCC::DisplacementMIPNCC(const DisplacementMIPNCC &ex_instance) -{ - #if S_VERBOSE>5 - printf("..........in DisplacementMIPNCC::DisplacementMIPNCC(const DisplacementMIPNCC &ex_instance)\n"); - #endif - - TYPE = ex_instance.TYPE; - for(int i=0; i<3; i++) - { - VHD_coords[i] = ex_instance.VHD_coords[i]; - VHD_def_coords[i] = ex_instance.VHD_def_coords[i]; - NCC_maxs[i] = ex_instance.NCC_maxs[i]; - NCC_widths[i] = ex_instance.NCC_widths[i]; - rel_factors[i] = ex_instance.rel_factors[i]; - delays[i] = ex_instance.delays[i]; - wRangeThrs[i] = ex_instance.wRangeThrs[i]; - invWidths[i] = ex_instance.invWidths[i]; - } -} - -DisplacementMIPNCC::DisplacementMIPNCC(TiXmlElement *displ_node) : Displacement() -{ - #if S_VERBOSE>5 - printf("..........in DisplacementMIPNCC::DisplacementMIPNCC(TiXmlElement *displ_node)\n"); - #endif - - TYPE = S_MIP_NCC_DISPL_TYPE; - this->loadXML(displ_node); -} - -//evaluates displacement reliability possibly along the given direction. The result(s) should be stored -//in one or more object members, so that they have to be computed once and then accessed by GET methods -float DisplacementMIPNCC::evalReliability(direction _direction) throw (iom::exception) -{ - #if S_VERBOSE>4 - printf("........in DisplacementMIPNCC::evalReliability(direction _direction = %d)\n", _direction); - #endif - - if(_direction == 0 || _direction == 1 || _direction == 2) - { - float NCC_width_normalized = (100.0F - (NCC_widths[_direction] * 100.0F / invWidths[_direction]))/100.0F; - rel_factors[_direction] = (float) sqrt( S_NCC_WIDTH_WEIGHT*NCC_width_normalized*NCC_width_normalized + S_NCC_PEAK_WEIGHT*NCC_maxs[_direction]*NCC_maxs[_direction]); - } - else if(_direction == -1) - throw iom::exception("in DisplacementMIPNCC::evalReliability(void): feature not yet supported"); - else - throw iom::exception("in DisplacementMIPNCC::evalReliability(...): wrong direction value"); - - return rel_factors[_direction]; -} - -//returns the reliability possibly along the given direction. An exception is thrown if the reliability -//index(es) are not computed yet. -float DisplacementMIPNCC::getReliability(direction _direction) throw (iom::exception) -{ - #if S_VERBOSE>4 - printf("........in DisplacementMIPNCC::getReliability(direction _direction = %d)\n", _direction); - #endif - - if( (_direction == 0 || _direction == 1 || _direction == 2) && rel_factors[_direction] == -1.0F) - throw iom::exception("in DisplacementMIPNCC::evalReliability(direction _direction): reliability factor not yet computed"); - else if(_direction == -1) - throw iom::exception("in DisplacementMIPNCC::evalReliability(void): feature not yet supported"); - else if( !(_direction == 0 || _direction == 1 || _direction == 2) ) - { - char errMsg[1000]; - sprintf(errMsg, "in DisplacementMIPNCC::evalReliability(...): wrong direction value ( = %d )", _direction); - throw iom::exception(errMsg); - } - - return rel_factors[_direction]; -} - -//returns the displacement along the given direction -int DisplacementMIPNCC::getDisplacement(direction _direction) throw (iom::exception) -{ - #if S_VERBOSE>4 - printf("\t\t\t\t\tin DisplacementMIPNCC::getDisplacement(direction _direction = %d)\n", _direction); - #endif - - if( _direction != 0 && _direction != 1 && _direction != 2) - throw iom::exception("in DisplacementMIPNCC::getDisplacement(...): wrong direction value"); - else if(VHD_coords[_direction] == std::numeric_limits::max()) - throw iom::exception("in DisplacementMIPNCC::getDisplacement(...): displacement not computed yet"); - - return VHD_coords[_direction]; -} - -//sets to default values the displacements with a reliability factor above the given threshold -void DisplacementMIPNCC::threshold(float rel_threshold) throw (iom::exception) -{ - #if S_VERBOSE>4 - printf("........in DisplacementMIPNCC::threshold(rel_threshold = %.4f)\n", rel_threshold); - #endif - - evalReliability(dir_vertical); - evalReliability(dir_horizontal); - evalReliability(dir_depth); - - for(int i=0; i<3; i++) - if(rel_factors[i] < rel_threshold) - { - VHD_coords[i] = VHD_def_coords[i]; - NCC_maxs[i] = 0; - NCC_widths[i] = invWidths[i]; - evalReliability(direction(i)); - } -} - -//returns the displacement mirrored along the given direction. -Displacement* DisplacementMIPNCC::getMirrored(direction _direction) throw (iom::exception) -{ - #if S_VERBOSE>4 - printf("........in DisplacementMIPNCC::getMirrored(direction _direction = %d)\n", _direction); - #endif - - DisplacementMIPNCC *mirrored = new DisplacementMIPNCC(); - if(_direction == dir_vertical) - { - mirrored->VHD_coords[0] = -VHD_coords[0]; - mirrored->VHD_def_coords[0] = -VHD_def_coords[0]; - mirrored->VHD_coords[1] = VHD_coords[1]; - mirrored->VHD_def_coords[1] = VHD_def_coords[1]; - mirrored->VHD_coords[2] = VHD_coords[2]; - mirrored->VHD_def_coords[2] = VHD_def_coords[2]; - - } - else if(_direction == dir_horizontal) - { - mirrored->VHD_coords[0] = VHD_coords[0]; - mirrored->VHD_def_coords[0] = VHD_def_coords[0]; - mirrored->VHD_coords[1] = -VHD_coords[1]; - mirrored->VHD_def_coords[1] = -VHD_def_coords[1]; - mirrored->VHD_coords[2] = VHD_coords[2]; - mirrored->VHD_def_coords[2] = VHD_def_coords[2]; - } - else if(_direction == dir_depth) - { - mirrored->VHD_coords[0] = VHD_coords[0]; - mirrored->VHD_def_coords[0] = VHD_def_coords[0]; - mirrored->VHD_coords[1] = VHD_coords[1]; - mirrored->VHD_def_coords[1] = VHD_def_coords[1]; - mirrored->VHD_coords[2] = -VHD_coords[2]; - mirrored->VHD_def_coords[2] = -VHD_def_coords[2]; - } - else - throw iom::exception("in DisplacementMIPNCC::getMirrored(...): unsupported or wrong given mirroring direction"); - - mirrored->TYPE = TYPE; - mirrored->NCC_maxs[0] = NCC_maxs[0]; - mirrored->NCC_maxs[1] = NCC_maxs[1]; - mirrored->NCC_maxs[2] = NCC_maxs[2]; - mirrored->NCC_widths[0] = NCC_widths[0]; - mirrored->NCC_widths[1] = NCC_widths[1]; - mirrored->NCC_widths[2] = NCC_widths[2]; - mirrored->rel_factors[0] = rel_factors[0]; - mirrored->rel_factors[1] = rel_factors[1]; - mirrored->rel_factors[2] = rel_factors[2]; - mirrored->wRangeThrs[0] = wRangeThrs[0]; - mirrored->wRangeThrs[1] = wRangeThrs[1]; - mirrored->wRangeThrs[2] = wRangeThrs[2]; - mirrored->invWidths[0] = invWidths[0]; - mirrored->invWidths[1] = invWidths[1]; - mirrored->invWidths[2] = invWidths[2]; - mirrored->delays[0] = delays[0]; - mirrored->delays[1] = delays[1]; - mirrored->delays[2] = delays[2]; - return (Displacement*) mirrored; -} - -//combines the parameters of the current and the given displacement so that after this operation -//the two displacements are more reliable (and are EQUAL). -void DisplacementMIPNCC::combine(Displacement& displ) throw (iom::exception) -{ - #if S_VERBOSE>3 - printf("......in DisplacementMIPNCC::combine(Displacement& displ)\n"); - #endif - - Displacement *displ_ptr = &displ; - DisplacementMIPNCC *displ_MIPNCC = (DisplacementMIPNCC*) displ_ptr; - for(int k=0; k<3; k++) - { - evalReliability(direction(k)); - displ.evalReliability(direction(k)); - if(rel_factors[k] < displ_MIPNCC->rel_factors[k]) - { - rel_factors [k] = displ_MIPNCC->rel_factors [k]; - NCC_maxs [k] = displ_MIPNCC->NCC_maxs [k]; - NCC_widths [k] = displ_MIPNCC->NCC_widths [k]; - VHD_coords [k] = displ_MIPNCC->VHD_coords [k]; - VHD_def_coords[k] = displ_MIPNCC->VHD_def_coords[k]; - delays[k] = displ_MIPNCC->delays[k]; - wRangeThrs[k] = displ_MIPNCC->wRangeThrs[k]; - invWidths[k] = displ_MIPNCC->invWidths[k]; - } - else - { - displ_MIPNCC->rel_factors [k] = rel_factors [k]; - displ_MIPNCC->NCC_maxs [k] = NCC_maxs [k]; - displ_MIPNCC->NCC_widths [k] = NCC_widths [k]; - displ_MIPNCC->VHD_coords [k] = VHD_coords [k]; - displ_MIPNCC->VHD_def_coords[k] = VHD_def_coords[k]; - displ_MIPNCC->delays[k] = delays[k]; - displ_MIPNCC->wRangeThrs[k] = wRangeThrs[k]; - displ_MIPNCC->invWidths[k] = invWidths[k]; - } - } -} - -//XML methods: convert/load displacement object into/from XML schema -TiXmlElement* DisplacementMIPNCC::getXML() throw (iom::exception) -{ - #if S_VERBOSE>5 - printf("\t\t\t\t\tin DisplacementMIPNCC::getXML()\n"); - #endif - - TiXmlElement * xml_representation = new TiXmlElement("Displacement"); - xml_representation->SetAttribute("TYPE","MIP_NCC"); - - for(int i=0; i<3; i++) - { - TiXmlElement* displacement; - if(i==0) - displacement = new TiXmlElement("V"); - else if(i==1) - displacement = new TiXmlElement("H"); - else - displacement = new TiXmlElement("D"); - displacement->SetAttribute("displ",VHD_coords[i]); - displacement->SetAttribute("default_displ",VHD_def_coords[i]); - displacement->SetDoubleAttribute("reliability",rel_factors[i]); - displacement->SetDoubleAttribute("nccPeak",NCC_maxs[i]); - displacement->SetAttribute("nccWidth",NCC_widths[i]); - - // Alessandro - 31/05/2013 - storing additional MIP-NCC parameters - displacement->SetAttribute("nccWRangeThr", wRangeThrs[i]); - displacement->SetAttribute("nccInvWidth", invWidths[i]); - displacement->SetAttribute("delay", delays[i]); - - xml_representation->LinkEndChild(displacement); - } - - return xml_representation; -} -void DisplacementMIPNCC::loadXML(TiXmlElement *displ_node) throw (iom::exception) -{ - #if S_VERBOSE>5 - printf("\t\t\t\t\tin DisplacementMIPNCC::loadXML(displ_node)\n"); - #endif - - TiXmlElement *displElem = displ_node->FirstChildElement("V"); - int displ_index=0; - while(displElem) - { - displElem->QueryIntAttribute("displ", &(VHD_coords[displ_index])); - displElem->QueryIntAttribute("default_displ",&(VHD_def_coords[displ_index])); - displElem->QueryFloatAttribute("reliability", &(rel_factors[displ_index])); - displElem->QueryFloatAttribute("nccPeak", &(NCC_maxs[displ_index])); - displElem->QueryIntAttribute("nccWidth", &(NCC_widths[displ_index])); - - // Alessandro - 31/05/2013 - loading additional MIP-NCC parameters - if(displElem->Attribute("nccWRangeThr") != 0) - displElem->QueryIntAttribute("nccWRangeThr", &wRangeThrs[displ_index]); - else - wRangeThrs[displ_index] = S_NCC_WIDTH_MAX - 1; - if(displElem->Attribute("nccInvWidth") != 0) - displElem->QueryIntAttribute("nccInvWidth", &invWidths[displ_index]); - else - invWidths[displ_index] = S_NCC_WIDTH_MAX; - if(displElem->Attribute("delay") != 0) - displElem->QueryIntAttribute("delay", &delays[displ_index]); - else - delays[displ_index]=-1; - - displElem = displElem->NextSiblingElement(); - displ_index++; - } -} - diff --git a/v3d_main/terafly/src/core/stitcher/DisplacementMIPNCC.h b/v3d_main/terafly/src/core/stitcher/DisplacementMIPNCC.h deleted file mode 100644 index 8ce587fc30..0000000000 --- a/v3d_main/terafly/src/core/stitcher/DisplacementMIPNCC.h +++ /dev/null @@ -1,93 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* -* Bria, A., Iannello, G., "TeraStitcher - A Tool for Fast 3D Automatic Stitching of Teravoxel-sized Microscopy Images", (2012) BMC Bioinformatics, 13 (1), art. no. 316. -* -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -#ifndef DISPLACEMENT_MIP_NCC_H -#define DISPLACEMENT_MIP_NCC_H - -#include "Displacement.h" -//#include "volumemanager.config.h" -#include "CrossMIPs.h" -#include - -class DisplacementMIPNCC : Displacement -{ - protected: - - //int TYPE; //INHERITED from Displacement - //int VHD_def_coords[3]; //INHERITED from Displacement - int VHD_coords[3]; //VHD displacements as offsets of the second stack with respect to the first one - float NCC_maxs[3]; //first reliability feature: measures the NCC peak, range in [0=unreliable,1=reliable] - int NCC_widths[3]; //second reliability feature: measures the NCC shape width sampled at the 75% of - //the peak, range in [0=reliable, S_NCC_WIDTH_MAX=unreliable] - float rel_factors[3]; //reliability factors of VHD displacements, range in [0=unreliable,1=reliable] - - // Alessandro - 31/05/2013 - storing also MIPNCC parameters - int delays[3]; //half range of NCC search around initial offset along VHD dimensions - int wRangeThrs[3]; //ranges used to evaluate maximum NCC widths (when maximum width is greater or equal to - //this value, width is set to invWidth - int invWidths[3]; //see - - public: - - //COSTRUCTORS - DECONSTRUCTOR - DisplacementMIPNCC(void); - DisplacementMIPNCC(const DisplacementMIPNCC &ex_instance); - DisplacementMIPNCC(NCC_descr_t &mip_ncc_descr); - DisplacementMIPNCC(int Vnominal, int Hnominal, int Dnominal); - DisplacementMIPNCC(TiXmlElement *displ_node); - ~DisplacementMIPNCC(void){} - - //evaluates displacement reliability possibly along the given direction. The result(s) should be stored - //in one or more object members, so that they have to be computed once and then accessed by GET methods - float evalReliability(direction _direction=invalid) throw (iom::exception); - - //returns the reliability possibly along the given direction. An exception is thrown if the reliability - //index(es) are not computed yet. - float getReliability(direction _direction=invalid) throw (iom::exception); - - //returns the displacement along the given direction - int getDisplacement(direction _direction) throw (iom::exception); - - //sets to default values the displacements with a reliability factor above the given threshold - void threshold(float rel_threshold) throw (iom::exception); - - //returns the displacement mirrored along the given direction. - Displacement* getMirrored(direction _direction) throw (iom::exception); - - //XML methods: convert/load displacement object into/from XML schema - TiXmlElement* getXML() throw (iom::exception); - void loadXML(TiXmlElement *displ_node) throw (iom::exception); - - //combines the parameters of the current and the given displacement so that after this operation - //the two displacements are more reliable (and are EQUAL). - void combine(Displacement& displ) throw (iom::exception); - - friend class PDAlgoMIPNCC; -}; - -#endif /* DISPLACEMENT_MIP_NCC_H */ - diff --git a/v3d_main/terafly/src/core/stitcher/MergeTiles.cpp b/v3d_main/terafly/src/core/stitcher/MergeTiles.cpp deleted file mode 100644 index 8851bfd5a1..0000000000 --- a/v3d_main/terafly/src/core/stitcher/MergeTiles.cpp +++ /dev/null @@ -1,1237 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2013 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* -* Bria, A., Iannello, G., "TeraStitcher - A Tool for Fast 3D Automatic Stitching of Teravoxel-sized Microscopy Images", (2012) BMC Bioinformatics, 13 (1), art. no. 316. -* -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -* 2015-08-28. Giulio. @FIXED reference system of the generated image has always V as a first axis and H as a second axis -* 2015-08-26. Giulio. @ADDED stop and resume facility in par mode -* 2015-08-16. Giulio. @ADDED the 'isotropi' parameter (flag) to all methods and the halve_pow2 array to control the halving at different resolutions -* 2015.08.14. Giulio. @FIXED a a bug on the depth used to create directories in the casethe --parallel option is used -* 2015.08.14. Giulio. @ADDED a check on block_depth when the --makedirs and --parallel options are used -* 2015-07-12. Giulio. @ADDED a halving method parameter to MergeTilesVaa3DRaw -* 2015-07-12. Giulio. @FIXED a bug on an int index in MergeTilesVaa3DRaw that should have been sint64 -* 2015-02-26. Giulio. @ADDED release of space allocated to stripesCoords and stripesCorners in mergeTiles -* 2015-02-13. Giulio. @CHANGED 3D ioplugin is called instead of Tiff3DMngr functions -* 2014-12-06. Giulio . @ADDED par_mode parameter in method mergeTilesVaa3DRaw controlling the execution when multiple instances of the function are launched. -* 2014-12-06. Giulio . @ADDED createDirectoryHiererchy method. -* 2014-11-03. Giulio. @FIXED stop and resume facility should be inactive when in test mode -* 2014-10-29. Giulio. @ADDED stop and resume facility - saved_img_format has been used to check if resume parameters have not been changed -* 2014-09-10. Alessandro. @FIXED 'mergeTilesVaa3DRaw' method: set 'imagemanager' module to silent mode. -* 2014-09-10. Alessandro. @CHANGED 'saved_img_format' interpretation in 'mergeTilesVaa3DRaw()' method. -* 2014-09-09. Alessandro. @FIXED missing buffer initialization and reset in 'mergeTiles()' method. -*/ - -# include "StackStitcher.h" - -#include -#include -#include -#include -#include -#include -#include "vmVirtualStack.h" -#include "S_config.h" -#include "StackRestorer.h" -#include "volumemanager.config.h" - -#include "RawFmtMngr.h" -//#include "Tiff3DMngr.h" -#include "../imagemanager/IM_config.h" -#include "../imagemanager/VirtualVolume.h" -#include "../imagemanager/TiledVolume.h" - - -#include "../iomanager/ProgressBar.h" - -#include "resumer.h" // GI_141029: added stop and resume facility - -#include "IOPluginAPI.h" // GI_150213 - -using namespace iomanager; -using namespace volumemanager; - -struct coord_2D{int V,H;}; -struct stripe_2Dcoords{coord_2D up_left, bottom_right;}; -struct stripe_corner{int h,H; bool up;}; -struct stripe_2Dcorners{std::list ups, bottoms, merged;}; -bool compareCorners (stripe_corner first, stripe_corner second); - -//typedef long V3DLONG; - - -void StackStitcher::mergeTilesVaa3DRaw(std::string output_path, int block_height, int block_width, int block_depth, bool* resolutions, - bool exclude_nonstitchable_stacks, int _ROW_START, int _ROW_END, int _COL_START, - int _COL_END, int _D0, int _D1, bool restoreSPIM, int restore_direction, - int blending_algo, int method, bool isotropic, bool test_mode, bool show_progress_bar, - const char* saved_img_format, int saved_img_depth, bool par_mode) throw (iom::exception) -{ -#if S_VERBOSE > 2 - printf("......in StackStitcher::mergeTilesVaa3DRaw(output_path=\"%s\", block_height=%d, block_width=%d, block_depth=%d, exclude_nonstitchable_stacks = %s, " - "_ROW_START=%d, _ROW_END=%d, _COL_START=%d, _COL_END=%d, _D0=%d, _D1=%d, restoreSPIM = %s, restore_direction = %d, test_mode = %s, resolutions = { ", - output_path.c_str(), slice_height, slice_width, slice_depth, (exclude_nonstitchable_stacks ? "true" : "false"), _ROW_START, _ROW_END, - _COL_START, _COL_END, _D0, _D1, (restoreSPIM ? "ENABLED" : "disabled"), restore_direction, (test_mode ? "ENABLED" : "disabled")); - for(int i=0; istart("Multiresolution tile merging"); - ProgressBar::instance()->update(0,"Initializing..."); - ProgressBar::instance()->show(); - } - - //initializing object if restoring is enabled - if(restoreSPIM) - { - char desc_file_path[S_STATIC_STRINGS_SIZE]; - sprintf(desc_file_path, "%s/%s", volume->getSTACKS_DIR(), S_DESC_FILE_NAME); - if(volumemanager::VirtualVolume::fileExists(desc_file_path) && restore_direction != axis_invalid) - stk_rst = new StackRestorer(this->volume, desc_file_path); - else if (!(volumemanager::VirtualVolume::fileExists(desc_file_path)) && restore_direction != axis_invalid) - printf("\n\nWARNING! Restoring is enabled but can't find %s file at %s.\n\t--> Restoring has been DISABLED.\n\n", S_DESC_FILE_NAME, desc_file_path); - } - - //computing dimensions of volume to be stitched - if ( par_mode ) { - // 2015-08-14. Giulio. the depth of the whole volume is computed in any case - this->computeVolumeDims(exclude_nonstitchable_stacks, _ROW_START, _ROW_END, _COL_START, _COL_END, -1, -1); - // 2015-08-14. Giulio. whole_depth is the depth of the whole volume - whole_depth = this->D1-this->D0; - // set a subvolume along D axis, if optional parameters _D0 and _D1 have been used - if(_D0 != -1 && _D0 >= this->D0) - this->D0 = _D0; - if(_D1 != -1 && _D1 <= this->D1) - this->D1 = _D1; - } - else { - this->computeVolumeDims(exclude_nonstitchable_stacks, _ROW_START, _ROW_END, _COL_START, _COL_END, _D0, _D1); - // 2015-08-14. Giulio. whole_depth should not be used - whole_depth = -1; - } - // depth is now the depth of the subvolume to be generated - width = this->H1-this->H0; - height = this->V1-this->V0; - depth = this->D1-this->D0; - - if(par_mode && block_depth == -1) // 2015-08-14. Giulio. if step 6 is parallelized, option --slicedepth must be used to set block_depth - { - char err_msg[5000]; - sprintf(err_msg,"in StackStitcher::mergeTilesVaa3DRaw(...): block_depth is not set in parallel mode"); - throw iom::exception(err_msg); - } - - //activating resolutions - block_height = (block_height == -1 ? (int)height : block_height); - block_width = (block_width == -1 ? (int)width : block_width); - block_depth = (block_depth == -1 ? (int)depth : block_depth); - if(block_height < S_MIN_SLICE_DIM || block_width < S_MIN_SLICE_DIM /* 2014-10-29. Giulio. @REMOVED (|| block_depth < S_MIN_SLICE_DIM) */) - { - char err_msg[5000]; - sprintf(err_msg,"in StackStitcher::mergeTilesVaa3DRaw(...): The minimum dimension for block width, height and depth is %d", S_MIN_SLICE_DIM); - throw iom::exception(err_msg); - } - if(resolutions == NULL) - { - resolutions = new bool; - *resolutions = true; - resolutions_size = 1; - } - else - for(int i=0; igetVXL_V() > 0 ? volume->getVXL_V() : -volume->getVXL_V()); - float vxlsz_Hx2 = 2*(volume->getVXL_H() > 0 ? volume->getVXL_H() : -volume->getVXL_H()); - float vxlsz_D = volume->getVXL_D(); - halve_pow2[0] = 0; - for ( int i=1; i(ceil ( (height/POW_INT(2,res_i)) / (float) block_height )); - n_stacks_H[res_i] = static_cast(ceil ( (width/POW_INT(2,res_i)) / (float) block_width )); - n_stacks_D[res_i] = static_cast(ceil ( (depth/POW_INT(2,halve_pow2[res_i])) / (float) block_depth )); - stacks_height[res_i] = new int **[n_stacks_V[res_i]]; - stacks_width[res_i] = new int **[n_stacks_V[res_i]]; - stacks_depth[res_i] = new int **[n_stacks_V[res_i]]; - for(int stack_row = 0; stack_row < n_stacks_V[res_i]; stack_row++) - { - stacks_height[res_i][stack_row] = new int *[n_stacks_H[res_i]]; - stacks_width [res_i][stack_row] = new int *[n_stacks_H[res_i]]; - stacks_depth [res_i][stack_row] = new int *[n_stacks_H[res_i]]; - for(int stack_col = 0; stack_col < n_stacks_H[res_i]; stack_col++) - { - stacks_height[res_i][stack_row][stack_col] = new int[n_stacks_D[res_i]]; - stacks_width [res_i][stack_row][stack_col] = new int[n_stacks_D[res_i]]; - stacks_depth [res_i][stack_row][stack_col] = new int[n_stacks_D[res_i]]; - for(int stack_sli = 0; stack_sli < n_stacks_D[res_i]; stack_sli++) - { - stacks_height[res_i][stack_row][stack_col][stack_sli] = - ((int)(height/POW_INT(2,res_i))) / n_stacks_V[res_i] + (stack_row < ((int)(height/POW_INT(2,res_i))) % n_stacks_V[res_i] ? 1:0); - stacks_width [res_i][stack_row][stack_col][stack_sli] = - ((int)(width/POW_INT(2,res_i))) / n_stacks_H[res_i] + (stack_col < ((int)(width/POW_INT(2,res_i))) % n_stacks_H[res_i] ? 1:0); - stacks_depth[res_i][stack_row][stack_col][stack_sli] = - ((int)(depth/POW_INT(2,halve_pow2[res_i]))) / n_stacks_D[res_i] + (stack_sli < ((int)(depth/POW_INT(2,halve_pow2[res_i]))) % n_stacks_D[res_i] ? 1 : 0); - } - } - } - //creating volume directory iff current resolution is selected and test mode is disabled - if(resolutions[res_i] == true && !test_mode) - { - if ( par_mode ) { // 2015-08-14. Giulio. uses the depth of the whole volume to generate the directory name - file_path[res_i]<getN_SLICES())/POW_INT(2,halve_pow2[res_i])<<")"; - } - else { - //creating directory that will contain image data at current resolution - file_path[res_i]<saveXML(0, xmlPath); - } - } - } - - //computing VH coordinates of all stripes - stripesCoords = new stripe_2Dcoords[volume->getN_ROWS()]; - for(int row_index=ROW_START; row_index<=ROW_END; row_index++) - { - stripesCoords[row_index].up_left.V = getStripeABS_V(row_index,true); - stripesCoords[row_index].up_left.H = volume->getSTACKS()[row_index][COL_START]->getABS_H(); - stripesCoords[row_index].bottom_right.V = getStripeABS_V(row_index,false); - stripesCoords[row_index].bottom_right.H = volume->getSTACKS()[row_index][COL_END]->getABS_H()+volume->getStacksWidth(); - } - - //computing stripes corners, i.e. corners that result from the overlap between each pair of adjacent stripes - stripesCorners = new stripe_2Dcorners[volume->getN_ROWS()]; - for(int row_index=ROW_START; row_index<=ROW_END; row_index++) - { - stripe_corner tmp; - - //for first VirtualStack of every stripe - tmp.H = volume->getSTACKS()[row_index][COL_START]->getABS_H(); - tmp.h = volume->getSTACKS()[row_index][COL_START]->getABS_V()-stripesCoords[row_index].up_left.V; - tmp.up = true; - stripesCorners[row_index].ups.push_back(tmp); - - tmp.h = stripesCoords[row_index].bottom_right.V - volume->getSTACKS()[row_index][COL_START]->getABS_V() - volume->getStacksHeight(); - tmp.up = false; - stripesCorners[row_index].bottoms.push_back(tmp); - - for(int col_index=COL_START; col_indexgetSTACKS()[row_index][col_index]->getABS_V() < volume->getSTACKS()[row_index][col_index+1]->getABS_V()) - { - tmp.H = volume->getSTACKS()[row_index][col_index]->getABS_H() + volume->getStacksWidth(); - tmp.h = volume->getSTACKS()[row_index][col_index+1]->getABS_V() - stripesCoords[row_index].up_left.V; - tmp.up = true; - stripesCorners[row_index].ups.push_back(tmp); - - tmp.H = volume->getSTACKS()[row_index][col_index+1]->getABS_H(); - tmp.h = stripesCoords[row_index].bottom_right.V - volume->getSTACKS()[row_index][col_index+1]->getABS_V() - volume->getStacksHeight(); - tmp.up = false; - stripesCorners[row_index].bottoms.push_back(tmp); - } - else - { - tmp.H = volume->getSTACKS()[row_index][col_index+1]->getABS_H(); - tmp.h = volume->getSTACKS()[row_index][col_index+1]->getABS_V() - stripesCoords[row_index].up_left.V; - tmp.up = true; - stripesCorners[row_index].ups.push_back(tmp); - - tmp.H = volume->getSTACKS()[row_index][col_index]->getABS_H()+volume->getStacksWidth(); - tmp.h = stripesCoords[row_index].bottom_right.V - volume->getSTACKS()[row_index][col_index+1]->getABS_V() - volume->getStacksHeight(); - tmp.up = false; - stripesCorners[row_index].bottoms.push_back(tmp); - } - } - - //for last VirtualStack of every stripe (h is not set because it doesn't matter) - tmp.H = volume->getSTACKS()[row_index][COL_END]->getABS_H() + volume->getStacksWidth(); - tmp.up = true; - stripesCorners[row_index].ups.push_back(tmp); - - tmp.up = false; - stripesCorners[row_index].bottoms.push_back(tmp); - } - - //ordered merging between ups and bottoms corners for every stripe - for(int row_index = ROW_START+1; row_index<=ROW_END; row_index++) - { - stripesCorners[row_index-1].merged.merge(stripesCorners[row_index-1].bottoms, compareCorners); - stripesCorners[row_index-1].merged.merge(stripesCorners[row_index ].ups, compareCorners); - } - - z_max_res = POW_INT(2,halve_pow2[resolutions_size-1]); - z_ratio= static_cast(depth/z_max_res); - buffer = new iom::real_t[height*width*z_max_res]; - - // 2014-10-29. Giulio. @DELETED - ////slice_start and slice_end of current block depend on the resolution - //for(int res_i=0; res_i< resolutions_size; res_i++) { - // stack_block[res_i] = 0; - // //slice_start[res_i] = this->D0; - // slice_start[res_i] = 0; // indices must start from 0 because they should have relative meaning - // slice_end[res_i] = slice_start[res_i] + stacks_depth[res_i][0][0][0] - 1; - //} - - // 2014-10-29. Giulio. @ADDED stop and resume facility - FILE *fhandle; - sint64 z; - sint64 z_parts; - - // 2014-11-03. Giulio. @FIXED stop and resume facility should inactive in test mode - // 2015-08-26. Giulio. @ADDED stop and resume facility in par mode - if ( !test_mode ) { - // WARNING: uses saved_img_format to check that the operation has been resumed withe the sae parameters - if ( par_mode ) { - output_path_par << output_path << "/" << "D_" << _D0 << "_" << _D1; - make_dir(output_path_par.str().c_str()); // the directory has been created - if ( initResumer(saved_img_format,output_path_par.str().c_str(),resolutions_size,resolutions,block_height,block_width,block_depth,method,saved_img_format,saved_img_depth,fhandle) ) { // halve_pow2 is not saved - readResumerState(fhandle,output_path_par.str().c_str(),resolutions_size,stack_block,slice_start,slice_end,z,z_parts); // halve_pow2 is not saved - } - else { // halve_pow2 is not saved: start form the firs slice - //slice_start and slice_end of current block depend on the resolution - for(int res_i=0; res_i< resolutions_size; res_i++) { - stack_block[res_i] = 0; - slice_start[res_i] = 0; // indices must start from 0 because they should have relative meaning - slice_end[res_i] = slice_start[res_i] + stacks_depth[res_i][0][0][0] - 1; - } - // z must begin from D0 (absolute index into the volume) since it is used to compute tha file names (containing the absolute position along D) - z = this->D0; - z_parts = 1; - } - } - else { // not in parallel mode: use output_path to maintain resume status - if ( initResumer(saved_img_format,output_path.c_str(),resolutions_size,resolutions,block_height,block_width,block_depth,method,saved_img_format,saved_img_depth,fhandle) ) { // halve_pow2 is not saved - readResumerState(fhandle,output_path.c_str(),resolutions_size,stack_block,slice_start,slice_end,z,z_parts); // halve_pow2 is not saved - } - else { // halve_pow2 is not saved: start from first slice - //slice_start and slice_end of current block depend on the resolution - for(int res_i=0; res_i< resolutions_size; res_i++) { - stack_block[res_i] = 0; - slice_start[res_i] = 0; // indices must start from 0 because they should have relative meaning - slice_end[res_i] = slice_start[res_i] + stacks_depth[res_i][0][0][0] - 1; - } - // z must begin from D0 (absolute index into the volume) since it is used to compute tha file names (containing the absolute position along D) - z = this->D0; - z_parts = 1; - } - } - } - else { // test mode - z = this->D0; - z_parts = 1; - } - - #ifdef S_TIME_CALC - double proc_time; - #endif - - // z must begin from D0 (absolute index into the volume) since it is used to compute tha file names (containing the absolute position along D) - for( /* 2014-10-29. Giulio. @DELETED (sint64 z = this->D0, z_parts = 1) */; z < this->D1; z += z_max_res, z_parts++) - { - // 2014-09-09. Alessandro. @FIXED missing buffer initialization and reset in 'mergeTiles()' method. - for(sint64 i=0; iupdate(((float)(z-D0+k+1)*100/(float)depth), progressBarMsg); - ProgressBar::instance()->show(); - } - - //looping on all stripes - for(int row_index=ROW_START; row_index<=ROW_END; row_index++) - { - //loading down stripe - if(row_index==ROW_START) stripe_up = NULL; - stripe_down = this->getStripe(row_index,(int)(z+k), restore_direction, stk_rst, blending_algo); - - #ifdef S_TIME_CALC - proc_time = -TIME(0); - #endif - - if(stripe_up) u_strp_bottom_displ = stripesCoords[row_index-1].bottom_right.V - V0; - d_strp_top_displ = stripesCoords[row_index ].up_left.V - V0; - if(stripe_up) u_strp_top_displ = stripesCoords[row_index-1].up_left.V - V0; - d_strp_left_displ = stripesCoords[row_index ].up_left.H - H0; - if(stripe_up) u_strp_left_displ = stripesCoords[row_index-1].up_left.H - H0; - d_strp_width = stripesCoords[row_index ].bottom_right.H - stripesCoords[row_index ].up_left.H; - if(stripe_up) u_strp_width = stripesCoords[row_index-1].bottom_right.H - stripesCoords[row_index-1].up_left.H; - if(stripe_up) u_strp_d_strp_overlap = u_strp_bottom_displ - d_strp_top_displ; - if(row_index!=ROW_END) - dd_strp_top_displ = stripesCoords[row_index+1].up_left.V - V0; - h_up = h_down = u_strp_d_strp_overlap; - - //overlapping zone - if(row_index!=ROW_START) - { - std::list::iterator cnr_i_next, cnr_i = stripesCorners[row_index-1].merged.begin(); - stripe_corner *cnr_left=&(*cnr_i), *cnr_right; - cnr_i++; - cnr_i_next = cnr_i; - cnr_i_next++; - - while( cnr_i != stripesCorners[row_index-1].merged.end()) - { - //computing h_up, h_overlap, h_down - cnr_right = &(*cnr_i); - if(cnr_i_next == stripesCorners[row_index-1].merged.end()) - { - h_up = cnr_left->up ? u_strp_d_strp_overlap : 0; - h_down = cnr_left->up ? 0 : u_strp_d_strp_overlap; - } - else - if(cnr_left->up) - h_up = cnr_left->h; - else - h_down = cnr_left->h; - - h_overlap = u_strp_d_strp_overlap - h_up - h_down; - - //splitting overlapping zone in sub-regions along H axis - for(sint64 j= cnr_left->H - H0; j < cnr_right->H - H0; j++) - { - delta_angle = PI/(h_overlap-1); - angle = 0; - - //UP stripe zone - buffer_ptr = &buffer[k*height*width+d_strp_top_displ*width+j]; - ustripe_ptr = &stripe_up[(d_strp_top_displ-u_strp_top_displ)*u_strp_width +j - u_strp_left_displ]; - for(sint64 i=d_strp_top_displ; i= 0 ? 0 : h_overlap); i++, buffer_ptr+=width, ustripe_ptr+= u_strp_width) - *buffer_ptr = *ustripe_ptr; - - //OVERLAPPING zone - buffer_ptr = &buffer[k*height*width+(d_strp_top_displ+h_up)*width+j]; - ustripe_ptr = &stripe_up[(d_strp_top_displ+h_up-u_strp_top_displ)*u_strp_width +j - u_strp_left_displ]; - dstripe_ptr = &stripe_down[(d_strp_top_displ+h_up-d_strp_top_displ)*d_strp_width +j - d_strp_left_displ]; - for(sint64 i=d_strp_top_displ+h_up; i= 0 ? h_overlap : 0))*width+j]; - dstripe_ptr = &stripe_down[((d_strp_top_displ+h_up+(h_overlap >= 0 ? h_overlap : 0))-d_strp_top_displ)*d_strp_width +j - d_strp_left_displ]; - for(sint64 i=d_strp_top_displ+h_up+(h_overlap >= 0 ? h_overlap : 0); i= 0 && j - d_strp_left_displ < stripesCoords[row_index].bottom_right.H) - *buffer_ptr = *dstripe_ptr; - } - - //moving to bottom stripe_up - delete stripe_up; - stripe_up=stripe_down; - - #ifdef S_TIME_CALC - proc_time += TIME(0); - StackStitcher::time_merging+=proc_time; - #endif - } - //releasing last stripe_down - delete stripe_down; - } - - //saving current buffer data at selected resolutions and in multitile format - for(int i=0; i< resolutions_size; i++) - { - if(show_progress_bar) - { - sprintf(progressBarMsg, "Generating resolution %d of %d",i+1,ISR_MAX(resolutions_size, resolutions_size)); - ProgressBar::instance()->updateInfo(progressBarMsg); - ProgressBar::instance()->show(); - } - - // check if current block is changed - // D0 must be subtracted because z is an absolute index in volume while slice index should be computed on a relative basis (i.e. starting form 0) - if ( ((z - this->D0) / POW_INT(2,halve_pow2[i])) > slice_end[i] ) { - stack_block[i]++; - slice_start[i] = slice_end[i] + 1; - slice_end[i] += stacks_depth[i][0][0][stack_block[i]]; - } - - // find abs_pos_z at resolution i - std::stringstream abs_pos_z; - abs_pos_z.width(6); - abs_pos_z.fill('0'); - abs_pos_z << (int)(this->getMultiresABS_D(i,0) + // all stacks start at the same D position - //- D0 * volume->getVXL_D() * 10 + // WARNING: D0 is counted twice,both in getMultiresABS_D and in slice_start - (POW_INT(2,halve_pow2[i])*slice_start[i]) * volume->getVXL_D() * 10); - - //compute the number of slice of previous groups at resolution i - //note that z_parts in the number and not an index (starts from 1) - n_slices_pred = (z_parts - 1) * z_max_res / POW_INT(2,halve_pow2[i]); - - //buffer size along D is different when the remainder of the subdivision by z_max_res is considered - sint64 z_size = (z_parts<=z_ratio) ? z_max_res : (depth%z_max_res); - - //halvesampling resolution if current resolution is not the deepest one - if(i!=0) { - if ( halve_pow2[i] == (halve_pow2[i-1]+1) ) { // *modified* - // also D dimension has to be halvesampled - StackStitcher::halveSample(buffer,(int)(height/(POW_INT(2,i-1))),(int)(width/(POW_INT(2,i-1))),(int)(z_size/(POW_INT(2,halve_pow2[i-1]))),method); - } - else if ( halve_pow2[i] == halve_pow2[i-1] ) {// *modified* - // D dimension must not be halvesampled - StackStitcher::halveSample2D(buffer,(int)(height/(POW_INT(2,i-1))),(int)(width/(POW_INT(2,i-1))),(int)(z_size/(POW_INT(2,halve_pow2[i-1]))),method); - } - else { - char err_msg[S_STATIC_STRINGS_SIZE]; - sprintf(err_msg, "in StackStitcher::mergeTilesVaa3DRaw(...): halve sampling level %d not supported at resolution %d\n", halve_pow2[i], i); - throw iom::exception(err_msg); - } - } - - //saving at current resolution if it has been selected and iff buffer is at least 1 voxel (Z) deep - if(resolutions[i] && (z_size/(POW_INT(2,halve_pow2[i]))) > 0) - { - if(show_progress_bar) - { - sprintf(progressBarMsg, "Saving to disc resolution %d",i+1); - ProgressBar::instance()->updateInfo(progressBarMsg); - ProgressBar::instance()->show(); - } - - //storing in 'base_path' the absolute path of the directory that will contain all stacks - std::stringstream base_path; - if ( par_mode ) // 2015-08-14. Giulio. directory name depends on the depth of the whole volume - base_path << output_path << "/RES(" << (int)(height/POW_INT(2,i)) << "x" << - (int)(width/POW_INT(2,i)) << "x" << (int)(whole_depth/POW_INT(2,halve_pow2[i])) << ")/"; - else - base_path << output_path << "/RES(" << (int)(height/POW_INT(2,i)) << "x" << - (int)(width/POW_INT(2,i)) << "x" << (int)(depth/POW_INT(2,halve_pow2[i])) << ")/"; - - //looping on new stacks - for(int stack_row = 0, start_height = 0, end_height = 0; stack_row < n_stacks_V[i]; stack_row++) - { - //incrementing end_height - end_height = start_height + stacks_height[i][stack_row][0][0]-1; - - //computing V_DIR_path and creating the directory the first time it is needed - std::stringstream V_DIR_path; - V_DIR_path << base_path.str() << this->getMultiresABS_V_string(i,start_height); - if(!test_mode && z==D0 && !make_dir(V_DIR_path.str().c_str())) - { - char err_msg[S_STATIC_STRINGS_SIZE]; - sprintf(err_msg, "in StackStitcher::mergeTilesVaa3DRaw(...): unable to create V_DIR = \"%s\"\n", V_DIR_path.str().c_str()); - throw iom::exception(err_msg); - } - - for(int stack_column = 0, start_width=0, end_width=0; stack_column < n_stacks_H[i]; stack_column++) - { - end_width = start_width + stacks_width [i][stack_row][stack_column][0]-1; - - //computing H_DIR_path and creating the directory the first time it is needed - std::stringstream H_DIR_path; - H_DIR_path << V_DIR_path.str() << "/" << this->getMultiresABS_V_string(i,start_height) << "_" << this->getMultiresABS_H_string(i,start_width); - if ( z==D0 ) { - if(!test_mode && !make_dir(H_DIR_path.str().c_str())) - { - char err_msg[S_STATIC_STRINGS_SIZE]; - sprintf(err_msg, "in StackStitcher::mergeTilesVaa3DRaw(...): unable to create H_DIR = \"%s\"\n", H_DIR_path.str().c_str()); - throw iom::exception(err_msg); - } - else { // the directory has been created for the first time - // initialize block files - V3DLONG *sz = new V3DLONG[4]; - int datatype; - char *err_rawfmt; - - sz[0] = stacks_width[i][stack_row][stack_column][0]; - sz[1] = stacks_height[i][stack_row][stack_column][0]; - sz[3] = 1; // onle one channel for now - - if ( saved_img_depth == 16 ) - datatype = 2; - else if ( saved_img_depth == 8 ) - datatype = 1; - else { - char err_msg[S_STATIC_STRINGS_SIZE]; - sprintf(err_msg, "in StackStitcher::mergeTilesVaa3DRaw(...): unknown image depth (%d)", saved_img_depth); - throw iom::exception(err_msg); - } - - int slice_start_temp = 0; - for ( int j=0; j < n_stacks_D[i]; j++ ) { - sz[2] = stacks_depth[i][stack_row][stack_column][j]; - - std::stringstream abs_pos_z_temp; - abs_pos_z_temp.width(6); - abs_pos_z_temp.fill('0'); - abs_pos_z_temp << (int)(this->getMultiresABS_D(i,0) + // all stacks start at the same D position - (POW_INT(2,halve_pow2[i])*(slice_start_temp)) * volume->getVXL_D() * 10); - - std::stringstream img_path_temp; - img_path_temp << H_DIR_path.str() << "/" - << this->getMultiresABS_V_string(i,start_height) << "_" - << this->getMultiresABS_H_string(i,start_width) << "_" - << abs_pos_z_temp.str(); - - // 2014-09-10. Alessandro. @CHANGED 'saved_img_format' interpretation in 'mergeTilesVaa3DRaw()' method. - err_rawfmt = 0; // the plugin does not return a message - if( strcmp(saved_img_format, "tif") == 0 || strcmp(saved_img_format, "tiff") == 0 || strcmp(saved_img_format, "TIF") == 0 || strcmp(saved_img_format, "TIFF") == 0) - //err_rawfmt = initTiff3DFile((char *)img_path_temp.str().c_str(),(uint32)sz[0],(uint32)sz[1],(uint32)sz[2],(uint32)sz[3],datatype); - iom::IOPluginFactory::getPlugin3D(iom::IMOUT_PLUGIN)->create3Dimage((char *)img_path_temp.str().c_str(),(int)sz[1],(int)sz[0],(int)sz[2],datatype,(int)sz[3]); - else if(strcmp(saved_img_format, "v3draw") == 0 || strcmp(saved_img_format, "raw") == 0) - err_rawfmt = initRawFile((char *)img_path_temp.str().c_str(),sz,datatype); - else - throw iom::exception(vm::strprintf("in StackStitcher::mergeTilesVaa3DRaw(): unsupported image format \"%s\"", saved_img_format)); - if(err_rawfmt != 0) - throw iom::exception(vm::strprintf("in StackStitcher::mergeTilesVaa3DRaw(): error in initializing block file (%s)", err_rawfmt)); - - slice_start_temp += (int)sz[2]; - } - delete [] sz; - } - } - - //saving HERE - for(int buffer_z=0; buffer_zgetMultiresABS_V_string(i,start_height) << "_" - << this->getMultiresABS_H_string(i,start_width) << "_"; - - // D0 must be subtracted because z is an absolute index in volume while slice index should be computed on a relative basis (i.e. starting form 0) - if ( ((z - this->D0) / POW_INT(2,halve_pow2[i])+buffer_z) > slice_end[i] ) { // start a new block along z !!! GI_140427 THIS HAS NOT BE CHECKED YET - abs_pos_z_next.width(6); - abs_pos_z_next.fill('0'); - //abs_pos_z_next << (int)(this->getMultiresABS_D(i) + // all stacks start at the same D position - abs_pos_z_next << (int)(this->getMultiresABS_D(i,0) + // all stacks start at the same D position - (POW_INT(2,halve_pow2[i])*(slice_end[i]+1)) * volume->getVXL_D() * 10); - img_path << abs_pos_z_next.str(); - slice_ind = (int)(n_slices_pred - (slice_end[i]+1)) + buffer_z; - } - else { - //img_path - // << abs_pos_z.str(); // Alessandro, 23/03/2013 - bug found: see above - //<< this->getMultiresABS_D_string(0, rel_pos_z); // Alessandro, 23/03/2013 - we pass '0' because rel_pos_z is the relative Z - // pixel coordinate in the HIGHEST (i=0) resolution image space (see above). - img_path << abs_pos_z.str(); - slice_ind = (int)(n_slices_pred - slice_start[i]) + buffer_z; - } - - if(test_mode) - { - img_path.str(""); - img_path << volume->getSTACKS_DIR() << "/test_middle_slice"; - } - - // @FIXED by Alessandro on 2014-06-25: iim::IOException objects must be caught here - try - { - // 2014-09-10. Alessandro. @CHANGED 'saved_img_format' interpretation in 'mergeTilesVaa3DRaw()' method. - std::string iim_format; - if( strcmp(saved_img_format, "tif") == 0 || strcmp(saved_img_format, "tiff") == 0 || strcmp(saved_img_format, "TIF") == 0 || strcmp(saved_img_format, "TIFF") == 0) - iim_format = "Tiff3D"; - else if(strcmp(saved_img_format, "v3draw") == 0 || strcmp(saved_img_format, "raw") == 0) - iim_format = "Vaa3DRaw"; - else - throw iom::exception(vm::strprintf("in StackStitcher::mergeTilesVaa3DRaw(): unsupported image format \"%s\"", saved_img_format)); - - // 2014-09-10. Alessandro. @FIXED 'mergeTilesVaa3DRaw' method: set 'imagemanager' module to silent mode. - iim::DEBUG = iim::NO_DEBUG; - - // 2014-09-10. Alessandro. @CHANGED 'saved_img_format' interpretation in 'mergeTilesVaa3DRaw()' method. - iim::VirtualVolume::saveImage_to_Vaa3DRaw( - slice_ind, - img_path.str(), - buffer + buffer_z*(height/POW_INT(2,i))*(width/POW_INT(2,i)), // adds the stride - (int)height/(POW_INT(2,i)), - (int)width/(POW_INT(2,i)), - start_height,end_height,start_width,end_width, - iim_format.c_str(), saved_img_depth - ); - } - catch( iim::IOException& exception) - { - throw iom::exception(exception.what()); - } - } - start_width += stacks_width [i][stack_row][stack_column][0]; - } - start_height += stacks_height[i][stack_row][0][0]; - } - } - } - - // 2014-10-29. Giulio. @ADDED save next group data - if ( !test_mode ) - // fhandle is correctly set both in non parallel and in parallel mode - saveResumerState(fhandle,resolutions_size,stack_block,slice_start,slice_end,z+z_max_res,z_parts+1); - } - - int n_err = 0; // used to trigger exception in case the .bin file cannot be generated - - if ( !test_mode && !par_mode ) { - // 2014-10-29. Giulio. @ADDED close resume - closeResumer(fhandle,output_path.c_str()); - - // reloads created volumes to generate .bin file descriptors at all resolutions - ref_sys temp = volume->getREF_SYS(); // required by clang compiler - iim::ref_sys reference = *((iim::ref_sys *) &temp); // the cast is needed because there are two ref_sys in different name spaces - // 2015-08-28. Giulio. the generated volume has always V coordinates at the first directory level and H coordinates at the second directory level - if ( reference.first == iim::horizontal || reference.first == iim::inv_horizontal ) { - iim::axis temp = reference.first; - reference.first = reference.second; - reference.second = reference.first; - } - for(int res_i=0; res_i< resolutions_size; res_i++) - { - if(resolutions[res_i]) - { - //---- Alessandro 2013-04-22 partial fix: wrong voxel size computation. In addition, the predefined reference system {1,2,3} may not be the right - //one when dealing with CLSM data. The right reference system is stored in the object. A possible solution to implement - //is to check whether is a pointer to a object, then specialize it to and get its reference - //system. - try - { - iim::DEBUG = iim::NO_DEBUG; - TiledVolume temp_vol(file_path[res_i].str().c_str(),reference, - volume->getVXL_V()*pow(2.0f,res_i), volume->getVXL_H()*pow(2.0f,res_i),volume->getVXL_D()*pow(2.0f,halve_pow2[res_i])); - } - catch (iim::IOException & ex) - { - printf("in StackStitcher::mergeTilesVaa3DRaw: cannot create file mdata.bin in %s [reason: %s]\n\n",file_path[res_i].str().c_str(), ex.what()); - n_err++; - } - catch ( ... ) - { - printf("in StackStitcher::mergeTilesVaa3DRaw: cannot create file mdata.bin in %s [no reason available]\n\n",file_path[res_i].str().c_str()); - n_err++; - } - } - } - } - else if ( par_mode ) { - // 2015-08-26. Giulio. @ADDED close resume in par mode - closeResumer(fhandle,output_path_par.str().c_str()); - // WARNINIG --- the directory should be removed - bool res = remove_dir(output_path_par.str().c_str()); - } - - // deallocate memory - for(int res_i=0; res_i< resolutions_size; res_i++) - { - for(int stack_row = 0; stack_row < n_stacks_V[res_i]; stack_row++) - { - for(int stack_col = 0; stack_col < n_stacks_H[res_i]; stack_col++) - { - delete []stacks_height[res_i][stack_row][stack_col]; - delete []stacks_width [res_i][stack_row][stack_col]; - delete []stacks_depth [res_i][stack_row][stack_col]; - } - delete []stacks_height[res_i][stack_row]; - delete []stacks_width [res_i][stack_row]; - delete []stacks_depth [res_i][stack_row]; - } - delete []stacks_height[res_i]; - delete []stacks_width[res_i]; - delete []stacks_depth[res_i]; - } - - //releasing allocated memory - delete buffer; - if(stk_rst) - delete stk_rst; - delete []stripesCoords; - for ( int i=0; igetN_ROWS(); i++ ) { - stripesCorners[i].ups.clear(); - stripesCorners[i].bottoms.clear(); - stripesCorners[i].merged.clear(); - } - delete []stripesCorners; - - if ( n_err ) { // errors in mdat.bin creation - char err_msg[2000]; - sprintf(err_msg,"StackStitcher::mergeTilesVaa3DRaw: %d errors in creating mdata.bin files", n_err); - throw iom::exception(err_msg); - } -} - - -void StackStitcher::createDirectoryHierarchy(std::string output_path, int block_height, int block_width, int block_depth, bool* resolutions, - bool exclude_nonstitchable_stacks, int _ROW_START, int _ROW_END, int _COL_START, - int _COL_END, int _D0, int _D1, bool restoreSPIM, int restore_direction, - int blending_algo, int method, bool isotropic, bool test_mode, bool show_progress_bar, - const char* saved_img_format, int saved_img_depth, bool par_mode) throw (iom::exception) -{ -#if S_VERBOSE > 2 - printf("......in StackStitcher::createDirectoryHierarchy(output_path=\"%s\", block_height=%d, block_width=%d, block_depth=%d, exclude_nonstitchable_stacks = %s, " - "_ROW_START=%d, _ROW_END=%d, _COL_START=%d, _COL_END=%d, _D0=%d, _D1=%d, restoreSPIM = %s, restore_direction = %d, test_mode = %s, resolutions = { ", - output_path.c_str(), slice_height, slice_width, slice_depth, (exclude_nonstitchable_stacks ? "true" : "false"), _ROW_START, _ROW_END, - _COL_START, _COL_END, _D0, _D1, (restoreSPIM ? "ENABLED" : "disabled"), restore_direction, (test_mode ? "ENABLED" : "disabled")); - for(int i=0; icomputeVolumeDims(exclude_nonstitchable_stacks, _ROW_START, _ROW_END, _COL_START, _COL_END, _D0, _D1); - width = this->H1-this->H0; - height = this->V1-this->V0; - depth = this->D1-this->D0; - - if(block_depth == -1) // 2015-08-14. Giulio. if step 6 is parallelized, option --slicedepth must be used to set block_depth - { - char err_msg[5000]; - sprintf(err_msg,"in StackStitcher::mergeTilesVaa3DRaw(...): block_depth is not set in makedirs mode"); - throw iom::exception(err_msg); - } - - //activating resolutions - block_height = (block_height == -1 ? (int)height : block_height); - block_width = (block_width == -1 ? (int)width : block_width); - block_depth = (block_depth == -1 ? (int)depth : block_depth); - if(block_height < S_MIN_SLICE_DIM || block_width < S_MIN_SLICE_DIM /* 2014-10-29. Giulio. @REMOVED (|| block_depth < S_MIN_SLICE_DIM) */) - { - char err_msg[5000]; - sprintf(err_msg,"The minimum dimension for block width, height and depth is %d", S_MIN_SLICE_DIM); - throw iom::exception(err_msg); - } - if(resolutions == NULL) - { - resolutions = new bool; - *resolutions = true; - resolutions_size = 1; - } - else - for(int i=0; igetVXL_V() > 0 ? volume->getVXL_V() : -volume->getVXL_V()); - float vxlsz_Hx2 = 2*(volume->getVXL_H() > 0 ? volume->getVXL_H() : -volume->getVXL_H()); - float vxlsz_D = volume->getVXL_D(); - halve_pow2[0] = 0; - for ( int i=1; i(ceil ( (height/POW_INT(2,res_i)) / (float) block_height )); - n_stacks_H[res_i] = static_cast(ceil ( (width/POW_INT(2,res_i)) / (float) block_width )); - n_stacks_D[res_i] = static_cast(ceil ( (depth/POW_INT(2,halve_pow2[res_i])) / (float) block_depth )); - stacks_height[res_i] = new int **[n_stacks_V[res_i]]; - stacks_width[res_i] = new int **[n_stacks_V[res_i]]; - stacks_depth[res_i] = new int **[n_stacks_V[res_i]]; - for(int stack_row = 0; stack_row < n_stacks_V[res_i]; stack_row++) - { - stacks_height[res_i][stack_row] = new int *[n_stacks_H[res_i]]; - stacks_width [res_i][stack_row] = new int *[n_stacks_H[res_i]]; - stacks_depth [res_i][stack_row] = new int *[n_stacks_H[res_i]]; - for(int stack_col = 0; stack_col < n_stacks_H[res_i]; stack_col++) - { - stacks_height[res_i][stack_row][stack_col] = new int[n_stacks_D[res_i]]; - stacks_width [res_i][stack_row][stack_col] = new int[n_stacks_D[res_i]]; - stacks_depth [res_i][stack_row][stack_col] = new int[n_stacks_D[res_i]]; - for(int stack_sli = 0; stack_sli < n_stacks_D[res_i]; stack_sli++) - { - stacks_height[res_i][stack_row][stack_col][stack_sli] = - ((int)(height/POW_INT(2,res_i))) / n_stacks_V[res_i] + (stack_row < ((int)(height/POW_INT(2,res_i))) % n_stacks_V[res_i] ? 1:0); - stacks_width [res_i][stack_row][stack_col][stack_sli] = - ((int)(width/POW_INT(2,res_i))) / n_stacks_H[res_i] + (stack_col < ((int)(width/POW_INT(2,res_i))) % n_stacks_H[res_i] ? 1:0); - stacks_depth[res_i][stack_row][stack_col][stack_sli] = - ((int)(depth/POW_INT(2,halve_pow2[res_i]))) / n_stacks_D[res_i] + (stack_sli < ((int)(depth/POW_INT(2,halve_pow2[res_i]))) % n_stacks_D[res_i] ? 1:0); - } - } - } - //creating volume directory iff current resolution is selected and test mode is disabled - if(resolutions[res_i] == true && !test_mode) - { - //creating directory that will contain image data at current resolution - file_path[res_i]<saveXML(0, xmlPath); - } - } - - - //saving current buffer data at selected resolutions and in multitile format - for(int i=0; i< resolutions_size; i++) - { - // find abs_pos_z at resolution i - std::stringstream abs_pos_z; - abs_pos_z.width(6); - abs_pos_z.fill('0'); - abs_pos_z << (int)(this->getMultiresABS_D(i,0) + // all stacks start at the same D position - //- D0 * volume->getVXL_D() * 10 + // WARNING: D0 is counted twice,both in getMultiresABS_D and in slice_start - (POW_INT(2,halve_pow2[i])*slice_start[i]) * volume->getVXL_D() * 10); - - //saving at current resolution if it has been selected and iff buffer is at least 1 voxel (Z) deep - if(resolutions[i]) - { - //storing in 'base_path' the absolute path of the directory that will contain all stacks - std::stringstream base_path; - base_path << output_path << "/RES(" << (int)(height/POW_INT(2,i)) << "x" << - (int)(width/POW_INT(2,i)) << "x" << (int)(depth/POW_INT(2,halve_pow2[i])) << ")/"; - - //looping on new stacks - for(int stack_row = 0, start_height = 0, end_height = 0; stack_row < n_stacks_V[i]; stack_row++) - { - //incrementing end_height - end_height = start_height + stacks_height[i][stack_row][0][0]-1; - - //computing V_DIR_path and creating the directory the first time it is needed - std::stringstream V_DIR_path; - V_DIR_path << base_path.str() << this->getMultiresABS_V_string(i,start_height); - if(!test_mode && !make_dir(V_DIR_path.str().c_str())) - { - char err_msg[S_STATIC_STRINGS_SIZE]; - sprintf(err_msg, "in StackStitcher::createDirectoryHierarchy(...): unable to create V_DIR = \"%s\"\n", V_DIR_path.str().c_str()); - throw iom::exception(err_msg); - } - - for(int stack_column = 0, start_width=0, end_width=0; stack_column < n_stacks_H[i]; stack_column++) - { - end_width = start_width + stacks_width [i][stack_row][stack_column][0]-1; - - //computing H_DIR_path and creating the directory the first time it is needed - std::stringstream H_DIR_path; - H_DIR_path << V_DIR_path.str() << "/" << this->getMultiresABS_V_string(i,start_height) << "_" << this->getMultiresABS_H_string(i,start_width); - if(!test_mode && !make_dir(H_DIR_path.str().c_str())) - { - char err_msg[S_STATIC_STRINGS_SIZE]; - sprintf(err_msg, "in StackStitcher::createDirectoryHierarchy(...): unable to create H_DIR = \"%s\"\n", H_DIR_path.str().c_str()); - throw iom::exception(err_msg); - } - start_width += stacks_width [i][stack_row][stack_column][0]; - } - start_height += stacks_height[i][stack_row][0][0]; - } - } - } - -} - - -void StackStitcher::mdataGenerator (std::string output_path, int block_height, int block_width, int block_depth, bool* resolutions, - bool exclude_nonstitchable_stacks, int _ROW_START, int _ROW_END, int _COL_START, - int _COL_END, int _D0, int _D1, bool restoreSPIM, int restore_direction, - int blending_algo, int method, bool isotropic, bool test_mode, bool show_progress_bar, - const char* saved_img_format, int saved_img_depth, bool par_mode) throw (iom::exception) -{ -#if S_VERBOSE > 2 - printf("......in StackStitcher::mdataGenerator(output_path=\"%s\", block_height=%d, block_width=%d, block_depth=%d, exclude_nonstitchable_stacks = %s, " - "_ROW_START=%d, _ROW_END=%d, _COL_START=%d, _COL_END=%d, _D0=%d, _D1=%d, restoreSPIM = %s, restore_direction = %d, test_mode = %s, resolutions = { ", - output_path.c_str(), slice_height, slice_width, slice_depth, (exclude_nonstitchable_stacks ? "true" : "false"), _ROW_START, _ROW_END, - _COL_START, _COL_END, _D0, _D1, (restoreSPIM ? "ENABLED" : "disabled"), restore_direction, (test_mode ? "ENABLED" : "disabled")); - for(int i=0; icomputeVolumeDims(exclude_nonstitchable_stacks, _ROW_START, _ROW_END, _COL_START, _COL_END, _D0, _D1); - width = this->H1-this->H0; - height = this->V1-this->V0; - depth = this->D1-this->D0; - - if(resolutions == NULL) - { - resolutions = new bool; - *resolutions = true; - resolutions_size = 1; - } - else - for(int i=0; igetVXL_V() > 0 ? volume->getVXL_V() : -volume->getVXL_V()); - float vxlsz_Hx2 = 2*(volume->getVXL_H() > 0 ? volume->getVXL_H() : -volume->getVXL_H()); - float vxlsz_D = volume->getVXL_D(); - halve_pow2[0] = 0; - for ( int i=1; igetREF_SYS(); // required by clang compiler - iim::ref_sys reference = *((iim::ref_sys *) &temp); // the cast is needed because there are two ref_sys in different name spaces - // 2015-08-28. Giulio. the generated volume has always V coordinates at the first directory level and H coordinates at the second directory level - if ( reference.first == iim::horizontal || reference.first == iim::inv_horizontal ) { - iim::axis temp = reference.first; - reference.first = reference.second; - reference.second = reference.first; - } - for(int res_i=0; res_i< resolutions_size; res_i++) - { - if(resolutions[res_i]) - { - //---- Alessandro 2013-04-22 partial fix: wrong voxel size computation. In addition, the predefined reference system {1,2,3} may not be the right - //one when dealing with CLSM data. The right reference system is stored in the object. A possible solution to implement - //is to check whether is a pointer to a object, then specialize it to and get its reference - //system. - try - { - iim::DEBUG = iim::NO_DEBUG; - TiledVolume temp_vol(file_path[res_i].str().c_str(),reference, - volume->getVXL_V()*pow(2.0f,res_i), volume->getVXL_H()*pow(2.0f,res_i),volume->getVXL_D()*pow(2.0f,halve_pow2[res_i])); - } - catch (iim::IOException & ex) - { - printf("n StackStitcher::mdataGenerator: cannot create file mdata.bin in %s [reason: %s]\n\n",file_path[res_i].str().c_str(), ex.what()); - n_err++; - } - catch ( ... ) - { - printf("in StackStitcher::mdataGenerator: cannot create file mdata.bin in %s [no reason available]\n\n",file_path[res_i].str().c_str()); - n_err++; - } - } - } - } - - - //releasing allocated memory - if ( n_err ) { // errors in mdat.bin creation - char err_msg[2000]; - sprintf(err_msg,"StackStitcher::mdataGenerator: %d errors in creating mdata.bin files", n_err); - throw iom::exception(err_msg); - } -} \ No newline at end of file diff --git a/v3d_main/terafly/src/core/stitcher/PDAlgo.cpp b/v3d_main/terafly/src/core/stitcher/PDAlgo.cpp deleted file mode 100644 index 8232808277..0000000000 --- a/v3d_main/terafly/src/core/stitcher/PDAlgo.cpp +++ /dev/null @@ -1,48 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* -* Bria, A., Iannello, G., "TeraStitcher - A Tool for Fast 3D Automatic Stitching of Teravoxel-sized Microscopy Images", (2012) BMC Bioinformatics, 13 (1), art. no. 316. -* -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -#include "PDAlgo.h" -#include "PDAlgoMIPNCC.h" - -//static method which is responsible to instance and return the algorithm of the given type -PDAlgo* PDAlgo::instanceAlgorithm(int _type) -{ - #if S_VERBOSE>4 - printf("........in PDAlgo::instanceAlgorithm(int _type)\n",_type); - #endif - - if (_type == S_NCC_MODE) - return (PDAlgo*)(new PDAlgoMIPNCC()); - //else if(displ_type == S_PC_DISPL_TYPE) - //return (Displacement*)(new DisplacementPC(displ_type)); - else - { - char err_msg[200]; - sprintf(err_msg, "in PDAlgo::instanceAlgorithm(....): unsupported algorithm type (\"%d\")", _type); - throw iom::exception(err_msg); - } -} diff --git a/v3d_main/terafly/src/core/stitcher/PDAlgo.h b/v3d_main/terafly/src/core/stitcher/PDAlgo.h deleted file mode 100644 index b5a262774e..0000000000 --- a/v3d_main/terafly/src/core/stitcher/PDAlgo.h +++ /dev/null @@ -1,68 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* -* Bria, A., Iannello, G., "TeraStitcher - A Tool for Fast 3D Automatic Stitching of Teravoxel-sized Microscopy Images", (2012) BMC Bioinformatics, 13 (1), art. no. 316. -* -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -#ifndef PAIRWISE_DISPLACEMENT_ALGORITHM_H -#define PAIRWISE_DISPLACEMENT_ALGORITHM_H - -#include "Displacement.h" -#include "iomanager.config.h" - -class PDAlgo -{ - protected: - - int TYPE; //type of algorithm - - public: - - PDAlgo(void){} - ~PDAlgo(void){} - - /************************************************************************************************************* - * Abstract method that all derived classes must implement. - * : image stacks stored in row-wise in a monodimensional array - * <[]_dim[]> : VHD dimensions of - * : maximum displacements along VHD of respect to taking the given over- - * lap as reference. These parameters, together with , can be used to identify - * the region of interest where the correspondence between the given stacks has to be - * found. When used, these parameters have to be tuned with respect to the precision of - * the motorized stages. - * : direction of overlapping (see type definition for further details) - * : expected overlap between the given stacks along the given direction. This value can - * be used to determine the region of interest where the overlapping occurs. - **************************************************************************************************************/ - virtual Displacement* execute(iom::real_t *stk_A, iom::uint32 A_dim_V, iom::uint32 A_dim_H, iom::uint32 A_dim_D, - iom::real_t *stk_B, iom::uint32 B_dim_V, iom::uint32 B_dim_H, iom::uint32 B_dim_D, - iom::uint32 displ_max_V, iom::uint32 displ_max_H, iom::uint32 displ_max_D, - direction overlap_direction, iom::uint32 overlap) throw (iom::exception) = 0; - - //static method which is responsible to instance and return the algorithm of the given type - static PDAlgo* instanceAlgorithm(int _type); -}; - -#endif /* PAIRWISE_DISPLACEMENT_ALGORITHM_H */ - diff --git a/v3d_main/terafly/src/core/stitcher/PDAlgoMIPNCC.cpp b/v3d_main/terafly/src/core/stitcher/PDAlgoMIPNCC.cpp deleted file mode 100644 index 5b79af3d0d..0000000000 --- a/v3d_main/terafly/src/core/stitcher/PDAlgoMIPNCC.cpp +++ /dev/null @@ -1,109 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* -* Bria, A., Iannello, G., "TeraStitcher - A Tool for Fast 3D Automatic Stitching of Teravoxel-sized Microscopy Images", (2012) BMC Bioinformatics, 13 (1), art. no. 316. -* -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -* 2015-03-20. Giulio. @ADDED intialization of new fields wRangeThr_i, wRangeThr_j, wRangeThr_k of struct NCC_parms_t in execute -*/ - -#include "PDAlgoMIPNCC.h" -#include "CrossMIPs.h" -#include "DisplacementMIPNCC.h" - -using namespace iom; - -/************************************************************************************************************* -* Implements abstract method declared in superclass -* : image stacks stored in row-wise in a monodimensional array -* <[]_dim[]> : VHD dimensions of -* : maximum displacements along VHD of respect to taking the given over- -* lap as reference. These parameters, together with , can be used to identify -* the region of interest where the correspondence between the given stacks has to be -* found. When used, these parameters have to be tuned with respect to the precision of -* the motorized stages. -* : direction of overlapping (see type definition for further details) -* : expected overlap between the given stacks along the given direction. This value can -* be used to determine the region of interest where the overlapping occurs. -**************************************************************************************************************/ -Displacement* PDAlgoMIPNCC::execute(iom::real_t *stk_A, uint32 A_dim_V, uint32 A_dim_H, uint32 A_dim_D, - iom::real_t *stk_B, uint32 B_dim_V, uint32 B_dim_H, uint32 B_dim_D, - uint32 displ_max_V, uint32 displ_max_H, uint32 displ_max_D, - direction overlap_direction, uint32 overlap) throw (iom::exception) -{ - #if S_VERBOSE>3 - printf("\t\t\t\tin PDAlgoMIPNCC::execute(..., A_dim_V = %d, A_dim_H = %d, A_dim_D = %d, B_dim_V = %d, B_dim_H = %d, B_dim_D = %d, displ_max_V = %d, displ_max_H = %d, displ_max_D = %d, overlap_direction = %d, overlap = %d)\n", - A_dim_V, A_dim_H, A_dim_D, B_dim_V, B_dim_H, B_dim_D, displ_max_V, displ_max_H, displ_max_D, overlap_direction, overlap); - #endif - - //some checks - if(A_dim_V != B_dim_V || A_dim_H != B_dim_H || A_dim_D != B_dim_D) - throw iom::exception("in PDAlgoMIPNCC::execute(...): stacks A and B don't have the same dimensions"); - if(overlap_direction != dir_horizontal && overlap_direction != dir_vertical) - throw iom::exception("in PDAlgoMIPNCC::execute(...): unsupported overlapping direction"); - - // Alessandro & Giulio - 21/08/2013 - to handle 2D stitching - // (the more general case of thinner stacks is not managed since the CrossMIPs library has not been tested when the delay parameters are different) - // - // Alessandro - 21/08/2013 at 20:24: setting displ_max_D to 0 causes also wRangeThr to be set to 0 (otherwise another check in CrossMIPs will throw an exception) - // then it is better to handle this special case inside CrossMIPs, at the moment. - //if(A_dim_D == 1 && B_dim_D == 1) - //displ_max_D = 0; - - // Alessandro - 31/05/2013 - parameters MUST be passed (and controlled) by the caller - NCC_parms_t params; - params.enhance = false; - params.maxIter = 2; - params.maxThr = 0.10f; - params.UNR_NCC = S_NCC_PEAK_MIN; - //params.wRangeThr = MIN(std::min(std::min(displ_max_V, displ_max_H), displ_max_D), S_NCC_WIDTH_MAX-1); - params.wRangeThr_i = MIN(displ_max_V, S_NCC_WIDTH_MAX-1); - params.wRangeThr_j = MIN(displ_max_H, S_NCC_WIDTH_MAX-1); - params.wRangeThr_k = MIN(displ_max_D, S_NCC_WIDTH_MAX-1); - params.INF_W = MAX(params.wRangeThr_i,MAX(params.wRangeThr_j,params.wRangeThr_k)) + 1; - params.widthThr = 0.75f; - params.INV_COORD = 0; - - NCC_descr_t* descr = norm_cross_corr_mips(stk_A, stk_B, A_dim_D, A_dim_V, A_dim_H, 0, overlap_direction == dir_vertical ? A_dim_V - overlap : 0, - overlap_direction == dir_horizontal ? A_dim_H - overlap: 0, displ_max_D, displ_max_V, displ_max_H, overlap_direction, ¶ms); - - // Alessandro - 31/05/2013 - storing parameters - DisplacementMIPNCC *displ = new DisplacementMIPNCC(*descr); - displ->delays[0] = displ_max_V; - displ->delays[1] = displ_max_H; - displ->delays[2] = displ_max_D; - displ->wRangeThrs[0] = params.wRangeThr_i; - displ->wRangeThrs[1] = params.wRangeThr_j; - displ->wRangeThrs[2] = params.wRangeThr_k; - displ->invWidths[0] = params.INF_W; - displ->invWidths[1] = params.INF_W; - displ->invWidths[2] = params.INF_W; - - delete descr; - - return (Displacement*)displ; -} diff --git a/v3d_main/terafly/src/core/stitcher/PDAlgoMIPNCC.h b/v3d_main/terafly/src/core/stitcher/PDAlgoMIPNCC.h deleted file mode 100644 index 2d7a889603..0000000000 --- a/v3d_main/terafly/src/core/stitcher/PDAlgoMIPNCC.h +++ /dev/null @@ -1,53 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* -* Bria, A., Iannello, G., "TeraStitcher - A Tool for Fast 3D Automatic Stitching of Teravoxel-sized Microscopy Images", (2012) BMC Bioinformatics, 13 (1), art. no. 316. -* -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -#ifndef PD_ALGO_MIPNCC_H -#define PD_ALGO_MIPNCC_H - -#include "S_config.h" -#include "PDAlgo.h" - -class PDAlgoMIPNCC : PDAlgo -{ - protected: - - //int TYPE; //type of algorithm (INHERITED) - - public: - - PDAlgoMIPNCC(void){TYPE = S_NCC_MODE;}; - ~PDAlgoMIPNCC(void){}; - - //implements abstract method declared in superclass - Displacement* execute(iom::real_t *stk_A, iom::uint32 A_dim_V, iom::uint32 A_dim_H, iom::uint32 A_dim_D, - iom::real_t *stk_B, iom::uint32 B_dim_V, iom::uint32 B_dim_H, iom::uint32 B_dim_D, - iom::uint32 displ_max_V, iom::uint32 displ_max_H, iom::uint32 displ_max_D, - direction overlap_direction, iom::uint32 overlap) throw (iom::exception); -}; - -#endif /* PD_ALGO_MIPNCC_H */ - diff --git a/v3d_main/terafly/src/core/stitcher/S_config.h b/v3d_main/terafly/src/core/stitcher/S_config.h deleted file mode 100644 index 7de640a16c..0000000000 --- a/v3d_main/terafly/src/core/stitcher/S_config.h +++ /dev/null @@ -1,88 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* -* Bria, A., Iannello, G., "TeraStitcher - A Tool for Fast 3D Automatic Stitching of Teravoxel-sized Microscopy Images", (2012) BMC Bioinformatics, 13 (1), art. no. 316. -* -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -#ifndef S_CONFIG_H -#define S_CONFIG_H - -#define S_VERBOSE 0 -#define S_PI 3.14159265 -#define S_STATIC_STRINGS_SIZE 3000 - -//*** DISPLACEMENTS COMPUTATION PHASE*** -#define S_NCC_MODE 0 -#define S_NCC_NAME "MIPNCC" -#define S_PHASE_CORRELATION_MODE 1 -#define S_PC_NAME "PC" -#define S_DISPL_COMP_MODE S_NCC_MODE -#define S_MIP_NCC_DISPL_TYPE 1 -#define S_PC_DISPL_TYPE 2 -#define S_DISPL_SEARCH_RADIUS_DEF 25 -#define S_SUBVOL_DIM_D_DEFAULT 200 -#define S_OVERLAP_MIN 40 -#define S_SUBVOL_DIM_D_MIN 50 -# define HALVE_BY_MEAN 1 -# define HALVE_BY_MAX 2 - -//*** FINDING ABSOLUTE TILE POSITIONS PHASE*** -#define S_FATPM_SP_TREE 0 //spanning tree modality for finding absolute tile positions -#define S_FATPM_SP_TREE_NAME "MST" -#define S_FATPM_SCAN_V 1 //vertical scanning modality for finding absolute tile positions -#define S_FATPM_SCAN_V_NAME "SCANV" -#define S_FATPM_SCAN_H 2 //horizontal scanning modality for finding absolute tile positions -#define S_FATPM_SCAN_H_NAME "SCANH" -#define S_FATPM S_FATPM_SP_TREE //selected modality for finding absolute tile positions (FATPM) -#define S_NCC_PEAK_MIN 0 //minimum value of NCC peak -#define S_NCC_PEAK_MAX 1 //maximum value of NCC peak -#define S_NCC_WIDTH_MIN 0 //minimum value of NCC width -#define S_NCC_WIDTH_MAX 30 //maximum value of NCC width -#define S_NCC_PEAK_WEIGHT 0.5 //weight of NCC peak feature in displacements reliability evaluation: must sum to 1 with S_NCC_WIDTH_WEIGHT -#define S_NCC_WIDTH_WEIGHT 0.5 //weight of NCC width feature in displacements reliability evaluation: must sum to 1 with S_NCC_PEAK_WEIGHT -#define S_UNRELIABLE_WEIGHT 1000 //value returned by displacements error evaluating function when error is above the given threshold - -//*** MERGING PHASE*** -#define S_NO_BLENDING 0 //id associated to a function which does not perform any blending -#define S_NO_BLENDING_NAME "NOBLEND" -#define S_SINUSOIDAL_BLENDING 1 //ID associated to sinusoidal blending function -#define S_SINUSOIDAL_BLENDING_NAME "SINBLEND" -#define S_SHOW_STACK_MARGIN 2 -#define S_SHOW_STACK_MARGIN_NAME "STACKMARGIN" -#define S_ENHANCED_NO_BLENDING 3 //ID associated to inverse sinusoidal blending function enhancing margins -#define S_ENHANCED_NO_BLENDING_NAME "ENHNOBLEND" -#define S_SAVED_TIFF_BIT_DEPTH 8 //bit depth of saved images -#define S_MAX_MULTIRES 8 //in multiresolution mode, images will be downsampled up to 2^(S_MAX_MULTIRES) -#define S_MIN_SLICE_DIM 100 - -//*** RESTORING PHASE*** -#define S_RESTORE_V_DIRECTION 1 //association of IDs to restoring directions -#define S_RESTORE_H_DIRECTION 2 // '' -#define S_RESTORE_Z_DIRECTION 3 // '' -#define S_DEFAULT_RESTORE_DIRECTION 1 //enabled restoring direction -//#define S_RESTORE_VZ //if defined, restoring along Z will be performed contextually to vertical direction -#define S_MIN_PROF_VAL ((iom::real_t) 1e-5) // minimum profile value (to be used when profile is null) -#define S_DESC_FILE_NAME "stk_descs.dsc"//file name of illumination maps to load/save from/to disc - -#endif diff --git a/v3d_main/terafly/src/core/stitcher/StackRestorer.cpp b/v3d_main/terafly/src/core/stitcher/StackRestorer.cpp deleted file mode 100644 index 58efcb8552..0000000000 --- a/v3d_main/terafly/src/core/stitcher/StackRestorer.cpp +++ /dev/null @@ -1,625 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* -* Bria, A., Iannello, G., "TeraStitcher - A Tool for Fast 3D Automatic Stitching of Teravoxel-sized Microscopy Images", (2012) BMC Bioinformatics, 13 (1), art. no. 316. -* -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -#include "StackRestorer.h" -#include "vmVirtualStack.h" -#include -#include "S_config.h" - -using namespace volumemanager; - -StackRestorer::StackRestorer(VirtualVolume* stk_org) -{ - this->STK_ORG = stk_org; - N_ROWS = stk_org->getN_ROWS(); - N_COLS = stk_org->getN_COLS(); - - this->STKS_DESCRIPTORS = new vol_descr_t*[N_ROWS]; - for(int i=0; i < N_ROWS; i++) - STKS_DESCRIPTORS[i] = new vol_descr_t[N_COLS]; - - this->SUBSTKS_DESCRIPTORS = NULL; -} - - -StackRestorer::StackRestorer(VirtualVolume* stk_org, char* file_path) -{ - this->STK_ORG = stk_org; - N_ROWS = stk_org->getN_ROWS(); - N_COLS = stk_org->getN_COLS(); - - this->STKS_DESCRIPTORS = new vol_descr_t*[N_ROWS]; - for(int i=0; i < N_ROWS; i++) - STKS_DESCRIPTORS[i] = new vol_descr_t[N_COLS]; - - this->SUBSTKS_DESCRIPTORS = NULL; - - load(file_path); -} - -StackRestorer::StackRestorer(VirtualVolume* stk_org, int D_subvols) -{ - this->STK_ORG = stk_org; - N_ROWS = stk_org->getN_ROWS(); - N_COLS = stk_org->getN_COLS(); - - this->STKS_DESCRIPTORS = new vol_descr_t*[N_ROWS]; - for(int i=0; i < N_ROWS; i++) - STKS_DESCRIPTORS[i] = new vol_descr_t[N_COLS]; - - SD_DIM_i = N_ROWS; - SD_DIM_j = N_COLS; - SD_DIM_k = D_subvols; - - this->SUBSTKS_DESCRIPTORS = new vol_descr_t**[SD_DIM_i]; - for(int i=0; i < SD_DIM_i; i++) - { - SUBSTKS_DESCRIPTORS[i] = new vol_descr_t *[SD_DIM_j]; - for(int j=0; j < SD_DIM_j; j++) - SUBSTKS_DESCRIPTORS[i][j] = new vol_descr_t[SD_DIM_k]; - } -} - -StackRestorer::~StackRestorer(void) -{ - if(SUBSTKS_DESCRIPTORS) - { - for(int i=0; i < SD_DIM_i; i++) - { - for(int j=0; j < SD_DIM_j; j++) - delete[] SUBSTKS_DESCRIPTORS[i][j]; - delete[] SUBSTKS_DESCRIPTORS[i]; - } - delete[] SUBSTKS_DESCRIPTORS; - } - if(STKS_DESCRIPTORS) - { - for(int i=0; i < N_ROWS; i++) - delete[] STKS_DESCRIPTORS[i]; - delete[] STKS_DESCRIPTORS; - } -} - -void StackRestorer::computeSubvolDescriptors(iom::real_t* data, VirtualStack* stk_p, int subvol_idx, int subvol_D_dim) throw (iom::exception) -{ - int i = stk_p->getROW_INDEX(); - int j = stk_p->getCOL_INDEX(); - SUBSTKS_DESCRIPTORS[i][j][subvol_idx].init(stk_p, true, stk_p->getHEIGHT(), stk_p->getWIDTH(), subvol_D_dim); - SUBSTKS_DESCRIPTORS[i][j][subvol_idx].computeSubvolDescriptors(data); -} - -void StackRestorer::computeStackDescriptors(VirtualStack* stk_p) throw (iom::exception) -{ - int i = stk_p->getROW_INDEX(); - int j = stk_p->getCOL_INDEX(); - - if(!SUBSTKS_DESCRIPTORS || !SUBSTKS_DESCRIPTORS[i] || !SUBSTKS_DESCRIPTORS[i][j]) - { - char err_msg[1000]; - sprintf(err_msg, "in StackRestorer::computeStackDescriptors(VirtualStack[%d,%d]): no computed subvol descriptors found.\n", i, j); - throw iom::exception(err_msg); - } - - int D_dim_acc = 0; - for(int k=0; k< SD_DIM_k; k++) - if(SUBSTKS_DESCRIPTORS[i][j][k].isSubvolDescriptor() && SUBSTKS_DESCRIPTORS[i][j][k].isFinalized()) - D_dim_acc+= SUBSTKS_DESCRIPTORS[i][j][k].D_dim; - else - { - char err_msg[1000]; - sprintf(err_msg, "in StackRestorer::computeStackDescriptors(VirtualStack[%d,%d]): no computed subvol descriptors found.\n", i, j); - throw iom::exception(err_msg); - } - - STKS_DESCRIPTORS[i][j].init(SUBSTKS_DESCRIPTORS[i][j][0].stk_p, false, SUBSTKS_DESCRIPTORS[i][j][0].V_dim, SUBSTKS_DESCRIPTORS[i][j][0].H_dim, D_dim_acc); - STKS_DESCRIPTORS[i][j].computeStackDescriptors(SUBSTKS_DESCRIPTORS[i][j], SD_DIM_k); -} - -void StackRestorer::finalizeAllDescriptors() -{ - for(int i=0; igetSTACKS()[i][j]); -} - -void StackRestorer::printSubvolDescriptors(VirtualStack* stk_p, int subvol_idx) -{ - int i = stk_p->getROW_INDEX(); - int j = stk_p->getCOL_INDEX(); - SUBSTKS_DESCRIPTORS[i][j][subvol_idx].print(); -} - -void StackRestorer::printVolDescriptors(VirtualStack* stk_p) -{ - int i = stk_p->getROW_INDEX(); - int j = stk_p->getCOL_INDEX(); - STKS_DESCRIPTORS[i][j].print(); -} - -void StackRestorer::save(char* file_path) throw (iom::exception) -{ - if(STKS_DESCRIPTORS) - { - //some checks - bool ready_to_save = true; - for(int i=0; igetID(); - //file.write((char*)&ID, sizeof(int)); - file.write((char*)&N_ROWS, sizeof(int)); - file.write((char*)&N_COLS, sizeof(int)); - for(int i=0; igetSTACKS()[i][j]; - STKS_DESCRIPTORS[i][j].V_profile = new iom::real_t[STKS_DESCRIPTORS[i][j].V_dim]; - STKS_DESCRIPTORS[i][j].H_profile = new iom::real_t[STKS_DESCRIPTORS[i][j].H_dim]; - STKS_DESCRIPTORS[i][j].D_profile = new iom::real_t[STKS_DESCRIPTORS[i][j].D_dim]; - STKS_DESCRIPTORS[i][j].V_MIP = new iom::real_t[STKS_DESCRIPTORS[i][j].V_dim]; - STKS_DESCRIPTORS[i][j].H_MIP = new iom::real_t[STKS_DESCRIPTORS[i][j].H_dim]; - STKS_DESCRIPTORS[i][j].D_MIP = new iom::real_t[STKS_DESCRIPTORS[i][j].D_dim]; - - for(int ii=0; iigetROW_INDEX(); - int col = stk_p->getCOL_INDEX(); - int v_dim = stk_p->getHEIGHT(); - int h_dim = stk_p->getWIDTH(); - vol_descr_t *vol_desc = &(STKS_DESCRIPTORS[row][col]); - iom::real_t *V_profile = vol_desc->V_profile; - iom::real_t *H_profile = vol_desc->H_profile; - iom::real_t *V_MIP = vol_desc->V_MIP; - iom::real_t *H_MIP = vol_desc->H_MIP; - - switch ( direction ) - { - case S_RESTORE_V_DIRECTION: - { - //correct pixels - for ( i=0; i max_val) - max_val = V_MIP[i] / V_profile[i]; - break; - } - case S_RESTORE_H_DIRECTION: - { - //correct pixels - for ( i=0; i max_val) - max_val = H_MIP[i] / H_profile[i]; - break; - } - } - - // rescale VirtualStack - corr_fact = ISR_MIN((vol_desc->mean_val),(1 / max_val)); - p_scanpxl = data; - for ( i=0; iD_profile; - p_scanpxl = data; - for ( i=0; imean_val; - #endif -} - -void StackRestorer::repairStack(iom::real_t* data, VirtualStack* stk_p, int direction) throw (iom::exception) -{ - //some checks - bool ready_to_repair = true; - for(int i=0; igetROW_INDEX(); - int col = stk_p->getCOL_INDEX(); - int v_dim = stk_p->getHEIGHT(); - int h_dim = stk_p->getWIDTH(); - int d_dim = stk_p->getDEPTH(); - vol_descr_t *vol_desc = &(STKS_DESCRIPTORS[row][col]); - iom::real_t *V_profile = vol_desc->V_profile; - iom::real_t *H_profile = vol_desc->H_profile; - iom::real_t *V_MIP = vol_desc->V_MIP; - iom::real_t *H_MIP = vol_desc->H_MIP; - - switch ( direction ) - { - case S_RESTORE_V_DIRECTION: - { - //correct pixels - for( k=0; k max_val) - max_val = V_MIP[i] / V_profile[i]; - break; - } - case S_RESTORE_H_DIRECTION: - { - //correct pixels - for( k=0; k max_val) - max_val = H_MIP[i] / H_profile[i]; - break; - } - } - - // rescale VirtualStack - corr_fact = ISR_MIN((vol_desc->mean_val),(1 / max_val)); - p_scanpxl = data; - for( k=0; kstk_p = NULL; - - this->max_val = 0; - this->mean_val = 0; - this->V_dim = -1; - this->H_dim = -1; - this->D_dim = -1; - - this->V_profile = NULL; - this->H_profile = NULL; - this->D_profile = NULL; - - this->V_MIP = NULL; - this->H_MIP = NULL; - this->D_MIP = NULL; - - this->is_subvol_descriptor = false; - this->is_finalized = false; -} - -void StackRestorer::vol_descr_t::init(VirtualStack *new_stk_p, bool is_subvol_desc, int new_V_dim, int new_H_dim, int new_D_dim) -{ - this->stk_p = new_stk_p; - - this->V_dim = new_V_dim; - this->H_dim = new_H_dim; - this->D_dim = new_D_dim; - - this->V_profile = new iom::real_t[V_dim]; - this->H_profile = new iom::real_t[H_dim]; - this->D_profile = new iom::real_t[D_dim]; - - this->V_MIP = new iom::real_t[V_dim]; - this->H_MIP = new iom::real_t[H_dim]; - this->D_MIP = new iom::real_t[D_dim]; - - this->is_subvol_descriptor = is_subvol_desc; -} - -StackRestorer::vol_descr_t::~vol_descr_t() -{ - if(V_profile) - delete[] V_profile; - if(H_profile) - delete[] H_profile; - if(D_profile) - delete[] D_profile; - if(V_MIP) - delete[] V_MIP; - if(H_MIP) - delete[] H_MIP; - if(D_MIP) - delete[] D_MIP; -} - -void StackRestorer::vol_descr_t::computeSubvolDescriptors(iom::real_t *subvol) throw (iom::exception) -{ - //initialization of MIPs and profiles - for(int i=0; i V_MIP[i]) - V_MIP[i] = val; - if(val > H_MIP[j]) - H_MIP[j] = val; - if(val > D_MIP[k]) - D_MIP[k] = val; - } - - //computing max value as the maximum of maxs - for(int i=0; i max_val) - max_val = V_MIP[i]; - for(int j=0; j max_val) - max_val = H_MIP[j]; - for(int k=0; k max_val) - max_val = D_MIP[k]; - - this->is_finalized = true; -} - - -void StackRestorer::vol_descr_t::computeStackDescriptors(vol_descr_t *subvol_desc, int D_subvols) throw (iom::exception) -{ - //initialization of MIPs and profiles (that are mean intensity projections) - for(int i=0; i V_MIP[i]) - V_MIP[i] = subvol_desc[k].V_MIP[i]; - } - for(int j=0; j H_MIP[j]) - H_MIP[j] = subvol_desc[k].H_MIP[j]; - } - for(int kk=d_acc; kk max_val) - max_val = subvol_desc[k].max_val; - - this->is_finalized = true; -} - -void StackRestorer::vol_descr_t::print() -{ - printf("\tvol_decr[%d,%d] PRINTING:\n", stk_p->getROW_INDEX(), stk_p->getCOL_INDEX()); - printf("\tDIMS = %d(V) x %d(H) x %d(D)\n", V_dim, H_dim, D_dim); - printf("\tmean = %.5f\n", mean_val); - printf("\tmax = %.5f\n", max_val); - printf("\tarray data:\n\n"); - for(int i=0; i object - vol_descr_t ***SUBSTKS_DESCRIPTORS; //3D array of relative to substack descriptors - int SD_DIM_i, SD_DIM_j, SD_DIM_k; //dimensions of SUBSTKS_DESCRIPTORS - vol_descr_t **STKS_DESCRIPTORS; //2D array of relative to entire VirtualStack descriptors - int N_ROWS, N_COLS; //dimensions of STKS_DESCRIPTORS - - StackRestorer(void){}; - - public: - - StackRestorer(vm::VirtualVolume* stk_org); - StackRestorer(vm::VirtualVolume* stk_org, int D_subvols); - StackRestorer(vm::VirtualVolume* stk_org, char* file_path); - ~StackRestorer(void); - - void computeSubvolDescriptors(iom::real_t* data, vm::VirtualStack* stk_p, int subvol_idx, int subvol_D_dim) throw (iom::exception); - void computeStackDescriptors(vm::VirtualStack* stk_p) throw (iom::exception); - void finalizeAllDescriptors(); - - void repairSlice(iom::real_t* data, int slice_idx, vm::VirtualStack* stk_p, int direction) throw (iom::exception); - void repairStack(iom::real_t* data, vm::VirtualStack* stk_p, int direction) throw (iom::exception); - - void printSubvolDescriptors(vm::VirtualStack* stk_p, int subvol_idx); - void printVolDescriptors(vm::VirtualStack* stk_p); - void save(char* file_path) throw (iom::exception); - void load(char* file_path) throw (iom::exception); -}; - -#endif diff --git a/v3d_main/terafly/src/core/stitcher/StackStitcher.cpp b/v3d_main/terafly/src/core/stitcher/StackStitcher.cpp deleted file mode 100644 index 0a9f585369..0000000000 --- a/v3d_main/terafly/src/core/stitcher/StackStitcher.cpp +++ /dev/null @@ -1,1754 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* -* Bria, A., Iannello, G., "TeraStitcher - A Tool for Fast 3D Automatic Stitching of Teravoxel-sized Microscopy Images", (2012) BMC Bioinformatics, 13 (1), art. no. 316. -* -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -* 2015-08-28. Giulio. @FIXED reference system of the generated image has always V as a first axis and H as a second axis -* 2015-08-16. Giulio. @ADDED method for halvesampling only V and H dimensions -* 2015-07-12. Giulio. @ADDED a halving method parameter to MergeTilesVaa3DRaw -* 2015-07-12. Giulio. @FIXED a bug on an int index in MergeTiles that should have been sint64 -* 2015-07-12. Giulio. @FIXED a bug on int indices in halveSample that should have been sint64 -* 2015-02-26. Giulio. @ADDED release of space allocated to stripesCoords and stripesCorners in mergeTiles -* 2015-02-26. Giulio. @ADDED an empty destructor to class StackStitcher -* 2015-02-14. Giulio. @CHANGED saveImage is called again since it now calls the plugin -* 2015-02-03. Alessandro. @ADDED check of invalid stitched image dimensions -* 2014-11-25. Giluio. @CHANGED in test mode the "tiff2D" plugin is explicitly used to write the test slice to avoid conflict with plugin used for saving the stitched volume -* 2014-11-03. Giulio. @FIXED stop and resume facility should be inactive when in test mode -* 2014-10-31. Giulio. @ADDED stop and resume facility - saved_img_format has been used to check if resume parameters have not been changed -* 2014-09-09. Alessandro. @FIXED missing buffer initialization and reset in 'mergeTiles()' method. -* 2014-09-09. Alessandro. @FIXED missing buffer initialization in 'getStripe()' method. -* 2014-09-09. Alessandro. @FIXED 'mergeTiles()' method: propagate iim::IOException from the imagemanager module (otherwise it will crash...) and disable iim::DEBUG -*/ - - -#include -#include -#include -#include "StackStitcher.h" -#include -#include -#include - -#include "../iomanager/ProgressBar.h" -#include "S_config.h" -#include "PDAlgo.h" -#include "TPAlgo.h" -#include "StackRestorer.h" -#include "volumemanager.config.h" -#include "DisplacementMIPNCC.h" - -#include "../imagemanager/IM_config.h" -#include "../imagemanager/VirtualVolume.h" -#include "../imagemanager/StackedVolume.h" -#include "../iomanager/IOPluginAPI.h" - -#include "resumer.h" // GI_141029: added stop and resume facility - - -using namespace iomanager; -using namespace volumemanager; - -//initialization of class members -double StackStitcher::time_displ_comp=0; -double StackStitcher::time_merging=0; -double StackStitcher::time_stack_desc=0; -double StackStitcher::time_stack_restore=0; -double StackStitcher::time_multiresolution=0; -double StackStitcher::stack_marging_old_val=std::numeric_limits::max(); -bool StackStitcher::blank_line_drawn = false; - - -struct coord_2D{int V,H;}; -struct stripe_2Dcoords{coord_2D up_left, bottom_right;}; -struct stripe_corner{int h,H; bool up;}; -struct stripe_2Dcorners{std::list ups, bottoms, merged;}; -bool compareCorners (stripe_corner first, stripe_corner second) -{ return ( first.H < second.H ); } - -StackStitcher::StackStitcher(volumemanager::VirtualVolume* _volume) -{ - #if S_VERBOSE > 2 - printf("\t\t\t\t......in StackStitcher::StackStitcher(VirtualVolume* _volume)\n"); - #endif - volume = _volume; - V0 = V1 = H0 = H1 = D0 = D1 = ROW_START = ROW_END = COL_START = COL_END = -1; -} - - -StackStitcher::~StackStitcher(void) { -} - -// compute pairwise displacements -// 2014-09-12. Alessandro. @ADDED [z0, z1] subdata selection along Z in the 'computeDisplacements()' method. -void StackStitcher::computeDisplacements( - int algorithm_type, // ID of the pairwise displacement algorithm to be used. - int row0 /*= -1*/, // subdata selection along X: [row0, row1] rows will be processed only - int col0 /*= -1*/, // subdata selection along Y: [col0, col1] cols will be processed only - int row1 /*= -1*/, // subdata selection along X: [row0, row1] rows will be processed only - int col1 /*= -1*/, // subdata selection along Y: [col0, col1] cols will be processed only - int overlap_V /*= -1*/, // overlaps along V and H directions. If not given, default values are ... - int overlap_H /*=-1*/, // ... computed using the members of the object. - int displ_max_V/*=S_DISPL_SEARCH_RADIUS_DEF*/, // maximum displacements along VHD between two adjacent stacks. ... - int displ_max_H/*=S_DISPL_SEARCH_RADIUS_DEF*/, // ... If not given, value S_DISPL_SEARCH_RADIUS_DEF is assigned. - int displ_max_D/*=S_DISPL_SEARCH_RADIUS_DEF*/, - int subvol_DIM_D /*= S_SUBVOL_DIM_D_DEFAULT*/, // dimension of layers obtained by dividing the volume along D. - bool restoreSPIM/*=false*/, // enable SPIM artifacts removal (zebrated patterns) ... - int restore_direction/*=-1*/, // ... along the given direction. - bool show_progress_bar/*=true*/, // enable/disable progress bar with estimated time remaining - int z0/*=-1*/, // subdata selection along Z: [z0, z1] slices will be processed only - int z1/*=-1*/) // subdata selection along Z: [z0, z1] slices will be processed only -throw (iom::exception) -{ - #if S_VERBOSE>2 - printf("\t\t\t....in StackStitcher::computeDisplacements(..., overlap_V = %d, overlap_H = %d, displ_max_V = %d, displ_max_H = %d, displ_max_D = %d, start_row = %d, start_col = %d, end_row = %d, end_col = %d, subvol_DIM_D = %d, restoreSPIM=%s, restore_dir=%d)\n", - overlap_V, overlap_H, displ_max_V, displ_max_H, displ_max_D, row0, col0, row1, col1, subvol_DIM_D, (restoreSPIM ? "ENABLED" : "disabled"), restore_direction); - #endif - - //LOCAL VARIABLES - char buffer[S_STATIC_STRINGS_SIZE]; - int n_subvols; //number of subvolumes along D axis - int subvol_DIM_D_actual; //actual subvolumes dimension along D axis. Maybe slightly different from - int subvol_DIM_D_k; - bool row_wise; //used to decide if processing stacks row-wise or column-wise - int displ_computations; //stores the number of displacement computations (used for progress bar) - int displ_computations_idx; //counter for displacements computations - int i,j,k; //loop variables - PDAlgo *algorithm; //stores the reference to the algorithm to be used for pairwise displacement computation - VirtualStack *stk_A, *stk_B; //store references of each pair of adjacent stacks where follows along V or H - - //checks of parameters - overlap_V = overlap_V == -1 ? volume->getOVERLAP_V() : overlap_V; - overlap_H = overlap_H == -1 ? volume->getOVERLAP_H() : overlap_H; - row0 = row0 == -1 ? 0 : row0; - col0 = col0 == -1 ? 0 : col0; - row1 = row1 == -1 ? volume->getN_ROWS() -1 : row1; - col1 = col1 == -1 ? volume->getN_COLS() -1 : col1; - if(row0 < 0 || row0 > row1 || row1 >= volume->getN_ROWS() ||col0 < 0 || col0 > col1 || col1 >= volume->getN_COLS()) - { - sprintf(buffer, "in StackStitcher::computeDisplacements(...): selected portion of volume stacks ROWS[%d,%d] COLS[%d,%d] must be in ROWS[0,%d] COLS[0,%d]", - row0, row1, col0, col1, volume->getN_ROWS() -1, volume->getN_COLS() -1); - throw iom::exception(buffer); - } - if((overlap_V < S_OVERLAP_MIN || overlap_V > volume->getStacksHeight()) && volume->getN_ROWS() > 1) - { - sprintf(buffer, "in StackStitcher::computeDisplacements(...): overlap_V(=%d) must be in [%d,%d]", overlap_V, S_OVERLAP_MIN, volume->getStacksHeight()); - throw iom::exception(buffer); - } - if((overlap_H < S_OVERLAP_MIN || overlap_H > volume->getStacksWidth()) && volume->getN_COLS() > 1) - { - sprintf(buffer, "in StackStitcher::computeDisplacements(...): overlap_H(=%d) must be in [%d,%d]", overlap_H,S_OVERLAP_MIN, volume->getStacksWidth()); - throw iom::exception(buffer); - } - /*if(subvol_DIM_D < S_SUBVOL_DIM_D_MIN || subvol_DIM_D > volume->getN_SLICES()) - { - sprintf(buffer, "in StackStitcher::computeDisplacements(...): subvol_DIM_D(=%d) must be in [%d,%d]", subvol_DIM_D, S_SUBVOL_DIM_D_MIN, volume->getN_SLICES()); - throw iom::iom::exception(buffer); - }*/ - - // 2014-09-12. Alessandro. @ADDED [z0, z1] subdata selection along Z in the 'computeDisplacements()' method. - z0 = z0 == -1 ? 0 : z0; - z1 = z1 == -1 ? volume->getN_SLICES()-1 : z1; - if(z0 < 0 || z0 > z1) - throw iom::exception(iom::strprintf("in StackStitcher::computeDisplacements(): incorrect subdata selection [%d,%d] along Z", z0, z1).c_str()); - if(z1 >= volume->getN_SLICES()) - throw iom::exception(iom::strprintf("in StackStitcher::computeDisplacements(): incorrect subdata selection [%d,%d] along Z", z0, z1).c_str()); - int z_size = z1 - z0 + 1; - - //Pairwise Displacement Algorithm initialization - algorithm = PDAlgo::instanceAlgorithm(algorithm_type); - - //computing subvolumes partitioning parameters - // 2014-09-12. Alessandro. @ADDED [z0, z1] subdata selection along Z in the 'computeDisplacements()' method. - n_subvols = (int) ceil( ( (float) z_size )/ ( (float) subvol_DIM_D)); - subvol_DIM_D_actual = (int) floor( ( (float) z_size ) / ( (float) n_subvols)); - int z_start=z0; //necessary due to to 'z_start' parameter of 'alignStacks' method - - //initializing Restorer module - StackRestorer *stk_rst = NULL; - if(restoreSPIM) - stk_rst = new StackRestorer(volume, n_subvols); - - //initializing the progress bar - ProgressBar::instance(); - if(show_progress_bar) - { - ProgressBar::instance()->start("Pairwise displacement computation"); - ProgressBar::instance()->update(0,"Initializing..."); - ProgressBar::instance()->show(); - displ_computations = n_subvols*(2*(row1-row0+1)*(col1-col0+1)-((row1-row0+1)+(col1-col0+1))); - displ_computations_idx = 1; - } - - //processing first N%mod(n_subvols) LAYERS that are 'subvol_DIM_D_actual +1' long - row_wise = row1-row0>=col1-col0; - for(k = 1; k <= n_subvols; k++) - { - subvol_DIM_D_k = k <= z_size%n_subvols ? subvol_DIM_D_actual + 1 : subvol_DIM_D_actual; - - // load first substack in the range - // 2014-09-09. @ADDED sparse tile support: incomplete or empty substacks are not processed. - stk_A = volume->getSTACKS()[row0][col0]; - if(stk_A->isComplete(z_start,z_start+subvol_DIM_D_k-1)) - stk_A->loadImageStack(z_start,z_start+subvol_DIM_D_k-1); - - //scanning LAYER through columns OR through rows depending on row_wise value - for(i=(row_wise ? row0 : col0); i<=(row_wise ? row1 : col1); i++) - { - for(j=(row_wise ? col0 : row0); j<=(row_wise ? col1 : row1); j++) - { - stk_A = volume->getSTACKS()[(row_wise? i : j )][(row_wise ? j: i)]; - - //if #rows>=#columns, checking if eastern VirtualStack exists, otherwise checking if southern VirtualStack exists - if(j!=(row_wise ? col1 : row1)) - { - stk_B = volume->getSTACKS()[(row_wise? i : j+1)][(row_wise ? j+1: i)]; - - //if #rows>=#columns, checking if we are at first row. If so, allocating eastern VirtualStack - //if #rows<#columns, checking if we are at first column. If so, allocating southern VirtualStack - // 2014-09-09. @ADDED sparse tile support: incomplete or empty substacks are not processed. - if(i== (row_wise ? row0 : col0 ) && stk_B->isComplete(z_start,z_start+subvol_DIM_D_k-1)) - stk_B->loadImageStack(z_start, z_start+subvol_DIM_D_k-1); - - if(show_progress_bar) - { - sprintf(buffer, "Displacement computation %d of %d", displ_computations_idx, displ_computations); - ProgressBar::instance()->update((100.0f/displ_computations)*displ_computations_idx, buffer); - ProgressBar::instance()->show(); - } - - // 2014-09-09. @ADDED sparse tile support: incomplete or empty substacks are not processed. - if(stk_A->isComplete(z_start, z_start+subvol_DIM_D_k-1) && stk_B->isComplete(z_start, z_start+subvol_DIM_D_k-1) ) - { - #ifdef S_TIME_CALC - double proc_time = -TIME(0); - #endif - volume->insertDisplacement(stk_A, stk_B, - algorithm->execute(stk_A->getSTACKED_IMAGE(), stk_A->getHEIGHT(), stk_A->getWIDTH(), subvol_DIM_D_k, - stk_B->getSTACKED_IMAGE(), stk_B->getHEIGHT(), stk_B->getWIDTH(), subvol_DIM_D_k, displ_max_V, - displ_max_H, displ_max_D, row_wise ? dir_horizontal : dir_vertical, row_wise ? overlap_H : overlap_V )); - displ_computations_idx++; - #ifdef S_TIME_CALC - proc_time += TIME(0); - StackStitcher::time_displ_comp+=proc_time; - proc_time = -TIME(0); - #endif - } - } - //if #rows>=#columns, checking if southern VirtualStack exists, otherwise checking if eastern VirtualStack exists - if(i!=(row_wise ? row1 : col1)) - { - stk_B = volume->getSTACKS()[(row_wise? i+1 : j)][(row_wise ? j: i+1)]; - - //allocating southern/eastern VirtualStack - // 2014-09-09. @ADDED sparse tile support: incomplete or empty substacks are not processed. - if(stk_B->isComplete(z_start, z_start+subvol_DIM_D_k-1)) - stk_B->loadImageStack(z_start, z_start+subvol_DIM_D_k-1); - - if(show_progress_bar) - { - sprintf(buffer, "Displacement computation %d of %d", displ_computations_idx, displ_computations); - ProgressBar::instance()->update((100.0f/displ_computations)*displ_computations_idx, buffer); - ProgressBar::instance()->show(); - } - - // 2014-09-09. @ADDED sparse tile support: incomplete or empty substacks are not processed. - if(stk_A->isComplete(z_start, z_start+subvol_DIM_D_k-1) && stk_B->isComplete(z_start, z_start+subvol_DIM_D_k-1) ) - { - #ifdef S_TIME_CALC - double proc_time = -TIME(0); - #endif - volume->insertDisplacement(stk_A, stk_B, - algorithm->execute(stk_A->getSTACKED_IMAGE(), stk_A->getHEIGHT(), stk_A->getWIDTH(), subvol_DIM_D_k, - stk_B->getSTACKED_IMAGE(), stk_B->getHEIGHT(), stk_B->getWIDTH(), subvol_DIM_D_k, displ_max_V, - displ_max_H, displ_max_D, row_wise ? dir_vertical : dir_horizontal, row_wise ? overlap_V : overlap_H )); - displ_computations_idx++; - #ifdef S_TIME_CALC - proc_time += TIME(0); - StackStitcher::time_displ_comp+=proc_time; - proc_time = -TIME(0); - #endif - } - } - - // 2014-09-09. @ADDED sparse tile support: incomplete or empty substacks are not processed. - if(restoreSPIM && stk_A->isComplete(z_start, z_start+subvol_DIM_D_k-1)) - { - #ifdef S_TIME_CALC - double proc_time = -TIME(0); - #endif - stk_rst->computeSubvolDescriptors(stk_A->getSTACKED_IMAGE(), stk_A, k-1, subvol_DIM_D_k); - #ifdef S_TIME_CALC - proc_time += TIME(0); - StackStitcher::time_stack_desc+=proc_time; - #endif - } - - //deallocating current VirtualStack - stk_A->releaseImageStack(); - } - } - - //increasing z_start and decreasing remainder due to properly layer scanning - z_start = z_start + subvol_DIM_D_k; - } - - if(restoreSPIM) - { - #ifdef S_TIME_CALC - double proc_time = -TIME(0); - #endif - stk_rst->finalizeAllDescriptors(); - char desc_file_path[5000]; - sprintf(desc_file_path, "%s/%s", volume->getSTACKS_DIR(), S_DESC_FILE_NAME); - stk_rst->save(desc_file_path); - delete stk_rst; - #ifdef S_TIME_CALC - proc_time += TIME(0); - StackStitcher::time_stack_desc+=proc_time; - #endif - } - - if(show_progress_bar) - { - ProgressBar::instance()->update(100, "Ended!"); - ProgressBar::instance()->show(); - } -} - -/************************************************************************************************************* -* Computes final stitched volume dimensions assuming that current object contains the correct -* stack coordinates. The given parameters identify the possible VOI (Volume Of Interest). If these are not us- -* ed, the whole volume is considered and the parameter is used to discard rows -* or columns with no stitchable stacks -**************************************************************************************************************/ -void StackStitcher::computeVolumeDims(bool exclude_nonstitchable_stacks, int _ROW_START, int _ROW_END, - int _COL_START, int _COL_END, int _D0, int _D1) throw (iom::exception) -{ - #if S_VERBOSE >2 - printf("\t\t\t....in StackStitcher::computeVolumeDims(exclude_nonstitchable_stacks = %s, _ROW_START=%d, _ROW_END=%d, _COL_START=%d, _COL_END=%d, _D0=%d, _D1=%d)\n", - exclude_nonstitchable_stacks ? "true" : "false", _ROW_START, _ROW_END, _COL_START, _COL_END, _D0, _D1); - #endif - - char errMsg[2000]; - - // @FIXED by Alessandro on 2014-06-26: throw an expcetion if no stitchable stacks are found in the selected stacks range - // @FIXED by Alessandro on 2014-06-26: added ROW_START, ROW_END, COL_START, COL_END initialization - // @FIXED by Alessandro on 2014-06-25: removed additional increment of ROW_START/ROW_END/COL_START/COL_END when = true - - // check for valid stack range selection - if(_ROW_START == -1) - ROW_START = 0; - else if(_ROW_START >= 0 && _ROW_START < volume->getN_ROWS()) - ROW_START = _ROW_START; - else - { - sprintf(errMsg, "in StackStitcher::computeVolumeDims(...): _ROW_START (=%d) out of range [%d,%d]", _ROW_START, 0, volume->getN_ROWS()-1); - throw iom::exception(errMsg); - } - /**/ - if(_COL_START == -1) - COL_START = 0; - else if(_COL_START >= 0 && _COL_START < volume->getN_COLS()) - COL_START = _COL_START; - else - { - sprintf(errMsg, "in StackStitcher::computeVolumeDims(...): _COL_START (=%d) out of range [%d,%d]", _COL_START, 0, volume->getN_COLS()-1); - throw iom::exception(errMsg); - } - /**/ - if(_ROW_END == -1) - ROW_END = volume->getN_ROWS() -1; - else if(_ROW_END >= ROW_START && _ROW_END < volume->getN_ROWS()) - ROW_END = _ROW_END; - else - { - sprintf(errMsg, "in StackStitcher::computeVolumeDims(...): _ROW_END (=%d) out of range [%d,%d]", _ROW_END, ROW_START, volume->getN_ROWS()-1); - throw iom::exception(errMsg); - } - /**/ - if(_COL_END == -1) - COL_END = volume->getN_COLS() -1; - else if(_COL_END >= COL_START && _COL_END < volume->getN_COLS()) - COL_END = _COL_END; - else - { - sprintf(errMsg, "in StackStitcher::computeVolumeDims(...): _COL_END (=%d) out of range [%d,%d]", _COL_END, COL_START, volume->getN_COLS()-1); - throw iom::exception(errMsg); - } - //printf("\nAfter check, range is rows=[%d,%d] and cols=[%d,%d]\n", ROW_START, ROW_END, COL_START, COL_END); - - // if requested, exclude rows and columns that contain nonstitchable stacks only - if(exclude_nonstitchable_stacks) - { - int i=0, j=0; - bool stitchable_sequence = false; - - for(i=ROW_START, stitchable_sequence = false; i <= ROW_END && !stitchable_sequence; i++) - { - ROW_START = i; - for(j=COL_START; j <= COL_END && !stitchable_sequence; j++) - stitchable_sequence = volume->getSTACKS()[i][j]->isStitchable(); - } - if(!stitchable_sequence) - { - sprintf(errMsg, "in StackStitcher::computeVolumeDims(...): no stitchable stacks found in the selected stack range"); - throw iom::exception(errMsg); - } - - - for(j=COL_START, stitchable_sequence = false; j <= COL_END && !stitchable_sequence; j++) - { - COL_START = j; - for(i=ROW_START; i <= ROW_END && !stitchable_sequence; i++) - stitchable_sequence = volume->getSTACKS()[i][j]->isStitchable(); - } - if(!stitchable_sequence) - { - sprintf(errMsg, "in StackStitcher::computeVolumeDims(...): no stitchable stacks found in the selected stack range"); - throw iom::exception(errMsg); - } - - - for(i=ROW_END, stitchable_sequence = false; i>=ROW_START && !stitchable_sequence; i--) - { - ROW_END = i; - for(j=COL_START; j <= COL_END && !stitchable_sequence; j++) - stitchable_sequence = volume->getSTACKS()[i][j]->isStitchable(); - } - if(!stitchable_sequence) - { - sprintf(errMsg, "in StackStitcher::computeVolumeDims(...): no stitchable stacks found in the selected stack range"); - throw iom::exception(errMsg); - } - - - for(j=COL_END, stitchable_sequence = false; j>=COL_START && !stitchable_sequence; j--) - { - COL_END = j; - for(int i=ROW_START; i <= ROW_END && !stitchable_sequence; i++) - stitchable_sequence = volume->getSTACKS()[i][j]->isStitchable(); - } - if(!stitchable_sequence) - { - sprintf(errMsg, "in StackStitcher::computeVolumeDims(...): no stitchable stacks found in the selected stack range"); - throw iom::exception(errMsg); - } - } - //printf("The range of stacks to be stitched is rows[%d,%d] and cols[%d,%d]\n", ROW_START, ROW_END, COL_START, COL_END); - - // compute volume dimensions using the range of stacks computed so far - V0=std::numeric_limits::max(); - V1=std::numeric_limits::min(); - H0=std::numeric_limits::max(); - H1=std::numeric_limits::min(); - D0=std::numeric_limits::min(); - D1=std::numeric_limits::max(); - for(int j=COL_START; j<=COL_END; j++) - { - if(volume->getSTACKS()[ROW_START][j]->getABS_V()getSTACKS()[ROW_START][j]->getABS_V(); - - if(volume->getSTACKS()[ROW_END][j]->getABS_V()>V1) - V1 = volume->getSTACKS()[ROW_END][j]->getABS_V(); - } - for(int i=ROW_START; i<=ROW_END; i++) - { - if(volume->getSTACKS()[i][COL_START]->getABS_H()getSTACKS()[i][COL_START]->getABS_H(); - - if(volume->getSTACKS()[i][COL_END]->getABS_H()>H1) - H1 = volume->getSTACKS()[i][COL_END]->getABS_H(); - } - for(int i=ROW_START; i<=ROW_END; i++) - { - for(int j=COL_START; j<=COL_END; j++) - { - if(volume->getSTACKS()[i][j]->getABS_D()>D0) - D0 = volume->getSTACKS()[i][j]->getABS_D(); - - if(volume->getSTACKS()[i][j]->getABS_D()getSTACKS()[i][j]->getABS_D(); - } - } - H1+=volume->getStacksWidth(); - V1+=volume->getStacksHeight(); - D1+=volume->getN_SLICES(); - //printf("\t\t\t....in StackStitcher::computeVolumeDims(): volume range (before selection) is V[%d,%d], H[%d,%d], D[%d,%d]\n", V0, V1, H0, H1, D0, D1); - - // set a subvolume along D axis, if optional parameters _D0 and _D1 have been used - if(_D0 != -1 && _D0 >= D0) - D0 = _D0; - if(_D1 != -1 && _D1 <= D1) - D1 = _D1; - - #if S_VERBOSE >2 - printf("\t\t\t....in StackStitcher::computeVolumeDims(): volume range (AFTER selection) is V[%d,%d], H[%d,%d], D[%d,%d]\n", V0, V1, H0, H1, D0, D1); - #endif - - //*** FINAL CHECK *** - if(V0 > V1 || H0 > H1 || D0 > D1) - { - sprintf(errMsg, "in StackStitcher::computeVolumeDims(...): invalid volume ranges V[%d,%d], H[%d,%d], D[%d,%d]", V0, V1, H0, H1, D0, D1); - throw iom::exception(errMsg); - } -} - -/************************************************************************************************************* -* Returns the (up = true -> TOP, up = false -> BOTTOM) V coordinate of the virtual stripe at row. -**************************************************************************************************************/ -int StackStitcher::getStripeABS_V(int row_index, bool up) -{ - #if S_VERBOSE >4 - printf("\t\t\t\t\t...in StackStitcher::getStripeABS_V(int row_index=%d, bool up=%s)\n", row_index, up ? "true" : "false"); - #endif - - //computing absolute V coordinates of stripe by simple 'min' or 'max' over absolute V-coordinates of stacks - if(up) - { - int top_x_stripe=volume->getSTACKS()[row_index][COL_START]->getABS_V(); - - for(int j=COL_START+1; j<=COL_END; j++) - if(volume->getSTACKS()[row_index][j]->getABS_V()getSTACKS()[row_index][j]->getABS_V(); - - return top_x_stripe; - } - else - { - int bottom_x_stripe=volume->getSTACKS()[row_index][COL_START]->getABS_V(); - - for(int j=COL_START+1; j<=COL_END; j++) - if(volume->getSTACKS()[row_index][j]->getABS_V()>bottom_x_stripe) - bottom_x_stripe = volume->getSTACKS()[row_index][j]->getABS_V(); - bottom_x_stripe += volume->getStacksHeight(); - - return bottom_x_stripe; - } -} - - -/************************************************************************************************************* -* Merges all slices of the given row at the given depth index, so obtaining the stripe that is returned. -* Uses [...]_blending() functions to blend pixels in overlapping zones. The appropriate blending function is -* selected by the [blending_algo] parameter. If a object has been passed, each slice is re- -* stored before it is combined into the final stripe. -**************************************************************************************************************/ -iom::real_t* StackStitcher::getStripe(int row_index, int d_index, int restore_direction, StackRestorer* stk_rst, - int blending_algo) throw (iom::exception) -{ - #if S_VERBOSE >2 - printf("........in StackStitcher::getStripe(short row_index=%d, short d_index=%d, restore_direction=%d, blending_algo=%d)\n", - row_index, d_index, restore_direction, blending_algo); - #endif - - //LOCAL VARIABLES - iom::real_t* stripe = NULL; //stripe, the result of merging all VirtualStack's of a row - int width=0; //width of stripe - int height=0; //height of stripe - int stripe_V_top; //top V(ertical) coordinate of current stripe - int stripe_V_bottom; //bottom V(ertical) coordinate of current stripe - int stripe_H_right; //right H(orizontal) coordinate of current stripe - int stripe_H_left; //left H(orizontal) coordinate of current stripe - int r_stk_top_displ , l_stk_top_displ; //displacements of right and left stack from respectively - int rr_stk_left_displ; //displacement of right-right stack from - int l_stk_right_displ; //displacement of left stack from - int r_stk_left_displ, l_stk_left_displ; //displacements of right and left stack from respectively - int stack_width = volume->getStacksWidth(); //stacks H dimension - int stack_height = volume->getStacksHeight(); //stacks V dimension - VirtualStack *l_stk = NULL, *r_stk, *rr_stk; //pointers to left stack, right stack and right-right stack respectively - iom::real_t *slice_left = NULL, *slice_right; //"iterating" images, because current method merges images 2-by-2 - double angle=0; //angle between 0 and PI - double delta_angle; //angle step used to sample the overlapping zone in [0,PI] - char errMsg[5000]; //buffer where to store error messages - iom::real_t *stripe_ptr; //buffer where to store the resulting stripe - iom::real_t *rslice_ptr, *lslice_ptr; //buffers where to store each loaded pair of right and left slices - sint64 i,j; //pixel indexes - iom::real_t (*blending)(double& angle, iom::real_t& pixel1, iom::real_t& pixel2); //pointer to blending function - - //retrieving blending function - if(blending_algo == S_SINUSOIDAL_BLENDING) - blending = sinusoidal_blending; - else if(blending_algo == S_NO_BLENDING) - blending = no_blending; - else if(blending_algo == S_SHOW_STACK_MARGIN) - blending = stack_margin; - else - throw iom::exception("in StackStitcher::getStripe(...): unrecognized blending function"); - - //checking that is not out of bounds - if(row_index>=volume->getN_ROWS() || row_index < 0) - { - sprintf(errMsg, "in StackStitcher::getStripe(...): row %d to be merged is out of bounds [%d,%d]", row_index, 0, volume->getN_ROWS()-1); - throw iom::exception(errMsg); - } - - //checking that is not out of bounds - if(!(d_index>=D0 && d_indexgetSTACKS()[row_index][COL_START]->getABS_V(); - stripe_V_bottom = stripe_V_top; - stripe_H_left = volume->getSTACKS()[row_index][COL_START]->getABS_H(); - stripe_H_right = volume->getSTACKS()[row_index][COL_END]->getABS_H() + volume->getStacksWidth(); - for(int j=COL_START+1; j<=COL_END; j++) - { - if(volume->getSTACKS()[row_index][j]->getABS_V() < stripe_V_top) - stripe_V_top = volume->getSTACKS()[row_index][j]->getABS_V(); - - if(volume->getSTACKS()[row_index][j]->getABS_V() > stripe_V_bottom) - stripe_V_bottom = volume->getSTACKS()[row_index][j]->getABS_V(); - } - stripe_V_bottom += volume->getStacksHeight(); - height=stripe_V_bottom-stripe_V_top; - width=stripe_H_right-stripe_H_left; - - //ALLOCATING once for all the MEMORY SPACE for current stripe - stripe = new iom::real_t[height*width]; - - // 2014-09-09. Alessandro. @FIXED missing buffer initialization in 'getStripe()' method. - for(int i=0; igetSTACKS()[row_index][column_index-1] : NULL; - r_stk = volume->getSTACKS()[row_index][column_index]; - rr_stk = column_index !=COL_END ? volume->getSTACKS()[row_index][column_index+1] : NULL; - - r_stk_top_displ = r_stk->getABS_V() - stripe_V_top; - if(l_stk) l_stk_top_displ = l_stk->getABS_V() - stripe_V_top; - r_stk_left_displ = r_stk->getABS_H() - stripe_H_left; - if(l_stk) l_stk_left_displ = l_stk->getABS_H() - stripe_H_left; - if(l_stk) l_stk_right_displ = l_stk->getABS_H() - stripe_H_left + stack_width; - if(rr_stk) rr_stk_left_displ = rr_stk->getABS_H() - stripe_H_left; - - //loading right slice (slice_right) into memory - slice_right = r_stk->loadImageStack(d_index-r_stk->getABS_D(), d_index-r_stk->getABS_D()); - - #ifdef S_TIME_CALC - double proc_time = -TIME(0); - #endif - - //restoring right slice if restoring is enabled - if(stk_rst) - stk_rst->repairSlice(slice_right,d_index-r_stk->getABS_D(), r_stk,restore_direction); - #ifdef S_TIME_CALC - proc_time += TIME(0); - StackStitcher::time_stack_restore+=proc_time; - proc_time = -TIME(0); - #endif - - //setting delta_angle - if(l_stk) delta_angle = PI/((l_stk->getABS_H()+stack_width-r_stk->getABS_H())-1); - angle = 0; - - //for every pair of adjacent slices, writing 2 different zones - for(j=(l_stk ? r_stk_left_displ : 0); j<(rr_stk? rr_stk_left_displ : width); j++) - { - //FIRST ZONE: overlapping zone (iff l_stk exists) - if(l_stk && j < l_stk_right_displ) - { - stripe_ptr = &stripe[j]; - lslice_ptr = &slice_left [-l_stk_top_displ*stack_width+j-l_stk_left_displ]; - rslice_ptr = &slice_right[-r_stk_top_displ*stack_width+j-r_stk_left_displ]; - for(i=0; i= 0 && i - r_stk_top_displ < stack_height && i - l_stk_top_displ >= 0 && i - l_stk_top_displ < stack_height) - *stripe_ptr = blending(angle,*lslice_ptr,*rslice_ptr); - else if (i - r_stk_top_displ >= 0 && i - r_stk_top_displ < stack_height) - *stripe_ptr=*rslice_ptr; - else if (i - l_stk_top_displ >= 0 && i - l_stk_top_displ < stack_height) - *stripe_ptr= *lslice_ptr; - - angle=angle+delta_angle; - } - - //SECOND ZONE: slice_right remainder by excluding overlapping zone between previous slice and overlapping zone between next slice - else - { - rslice_ptr = &slice_right[-r_stk_top_displ*stack_width+j-r_stk_left_displ]; - for(i=0, stripe_ptr = &stripe[j]; i= 0 && i - r_stk_top_displ < stack_height) - *stripe_ptr=*rslice_ptr; - } - } - - #ifdef S_TIME_CALC - proc_time += TIME(0); - StackStitcher::time_merging+=proc_time; - #endif - - //releasing memory allocated for last left VirtualStack - slice_left = NULL; - if(l_stk) - l_stk->releaseImageStack(); - - //moving to right slice_left - slice_left=slice_right; - } - - //releasing memory allocated for last right VirtualStack - slice_right = NULL; - volume->getSTACKS()[row_index][COL_END]->releaseImageStack(); - - //iomanager::IOManager::saveImage(vm::strprintf("C:/debug/stripe_Z%04d_R%02d.tif", d_index, row_index), stripe, height, width); - //system("pause"); - - return stripe; -} - -/************************************************************************************************************* -* Method to be called for tile merging. <> parameters are mandatory, while [] are optional. -* : absolute directory path where merged tiles have to be stored. -* [slice_height/width] : desired dimensions of tiles slices after merging. It is actually an upper-bound of -* the actual slice dimensions, which will be computed in such a way that all tiles di- -* mensions can differ by 1 pixel only along both directions. If not given, the maximum -* allowed dimensions will be set, which will result in a volume composed by one large -* tile only. -* [resolutions] : pointer to an array of S_MAX_MULTIRES size which boolean entries identify the acti- -* vaction/deactivation of the i-th resolution. If not given, all resolutions will be -* activated. -* [exclude_nonstitc...] -* [_...START/END] -* [_D0/_D1] : identify the possible VOI (Volume Of Interest). If these are not used, the whole vo- -* lume is considered and the parameter is used to dis- -* card rows or columns with no stitchable stacks. -* [restoreSPIM] : enables SPIM artifacts removal (zebrated patterns) along the given direction. -* [restore_direction] : direction of SPIM zebrated patterns to be removed. -* [blending_algo] : ID of the blending algorithm to be used in the overlapping regions. -* [test_mode] : if enabled, the middle slice of the whole volume will be stitched and and saved lo- -* cally. Stage coordinates will be used, s o this can be used to test their precision -* as well as the selected reference system. -* [show_progress_bar] : enables/disables progress bar with estimated time remaining. -* [saved_img_format] : determines saved images format ("png","tif","jpeg", etc.). -* [saved_img_depth] : determines saved images bitdepth (16 or 8). -**************************************************************************************************************/ -void StackStitcher::mergeTiles(std::string output_path, int slice_height, int slice_width, bool* resolutions, - bool exclude_nonstitchable_stacks, int _ROW_START, int _ROW_END, int _COL_START, - int _COL_END, int _D0, int _D1, bool restoreSPIM, int restore_direction, - int blending_algo, int method, bool test_mode, bool show_progress_bar, - const char* saved_img_format, int saved_img_depth) throw (iom::exception) -{ - #if S_VERBOSE > 2 - printf("......in StackStitcher::mergeTiles(output_path=\"%s\", slice_height=%d, slice_width=%d, exclude_nonstitchable_stacks = %s, " - "_ROW_START=%d, _ROW_END=%d, _COL_START=%d, _COL_END=%d, _D0=%d, _D1=%d, restoreSPIM = %s, restore_direction = %d, test_mode = %s, resolutions = { ", - output_path.c_str(), slice_height, slice_width, (exclude_nonstitchable_stacks ? "true" : "false"), _ROW_START, _ROW_END, - _COL_START, _COL_END, _D0, _D1, (restoreSPIM ? "ENABLED" : "disabled"), restore_direction, (test_mode ? "ENABLED" : "disabled")); - for(int i=0; istart("Multiresolution tile merging"); - ProgressBar::instance()->update(0,"Initializing..."); - ProgressBar::instance()->show(); - } - - //initializing object if restoring is enabled - if(restoreSPIM) - { - char desc_file_path[S_STATIC_STRINGS_SIZE]; - sprintf(desc_file_path, "%s/%s", volume->getSTACKS_DIR(), S_DESC_FILE_NAME); - if(volumemanager::VirtualVolume::fileExists(desc_file_path) && restore_direction != axis_invalid) - stk_rst = new StackRestorer(this->volume, desc_file_path); - else if (!(volumemanager::VirtualVolume::fileExists(desc_file_path)) && restore_direction != axis_invalid) - printf("\n\nWARNING! Restoring is enabled but can't find %s file at %s.\n\t--> Restoring has been DISABLED.\n\n", S_DESC_FILE_NAME, desc_file_path); - } - - //computing dimensions of volume to be stitched - this->computeVolumeDims(exclude_nonstitchable_stacks, _ROW_START, _ROW_END, _COL_START, _COL_END, _D0, _D1); - width = this->H1-this->H0; - height = this->V1-this->V0; - depth = this->D1-this->D0; - - // 2015-02-03. Alessandro. @ADDED check of invalid stitched image dimensions - if(width <= 0) - throw iom::exception(iom::strprintf("The stitched image has invalid x-dimension (= %d)", width)); - if(height <= 0) - throw iom::exception(iom::strprintf("The stitched image has invalid y-dimension (= %d)", height)); - if(depth <= 0) - throw iom::exception(iom::strprintf("The stitched image has invalid z-dimension (= %d)", depth)); - - //activating resolutions - slice_height = (int)(slice_height == -1 ? height : slice_height); - slice_width = (int)(slice_width == -1 ? width : slice_width); - if(slice_height < S_MIN_SLICE_DIM || slice_width < S_MIN_SLICE_DIM) - { - char err_msg[5000]; - sprintf(err_msg,"The minimum dimension for both slice width and height is %d", S_MIN_SLICE_DIM); - throw iom::exception(err_msg); - } - if(resolutions == NULL) - { - resolutions = new bool; - *resolutions = true; - resolutions_size = 1; - } - else - for(int i=0; isaveXML(0, xmlPath); - } - } - - //computing VH coordinates of all stripes - stripesCoords = new stripe_2Dcoords[volume->getN_ROWS()]; - for(int row_index=ROW_START; row_index<=ROW_END; row_index++) - { - stripesCoords[row_index].up_left.V = getStripeABS_V(row_index,true); - stripesCoords[row_index].up_left.H = volume->getSTACKS()[row_index][COL_START]->getABS_H(); - stripesCoords[row_index].bottom_right.V = getStripeABS_V(row_index,false); - stripesCoords[row_index].bottom_right.H = volume->getSTACKS()[row_index][COL_END]->getABS_H()+volume->getStacksWidth(); - } - - //computing stripes corners, i.e. corners that result from the overlap between each pair of adjacent stripes - stripesCorners = new stripe_2Dcorners[volume->getN_ROWS()]; - for(int row_index=ROW_START; row_index<=ROW_END; row_index++) - { - stripe_corner tmp; - - //for first VirtualStack of every stripe - tmp.H = volume->getSTACKS()[row_index][COL_START]->getABS_H(); - tmp.h = volume->getSTACKS()[row_index][COL_START]->getABS_V()-stripesCoords[row_index].up_left.V; - tmp.up = true; - stripesCorners[row_index].ups.push_back(tmp); - - tmp.h = stripesCoords[row_index].bottom_right.V - volume->getSTACKS()[row_index][COL_START]->getABS_V() - volume->getStacksHeight(); - tmp.up = false; - stripesCorners[row_index].bottoms.push_back(tmp); - - for(int col_index=COL_START; col_indexgetSTACKS()[row_index][col_index]->getABS_V() < volume->getSTACKS()[row_index][col_index+1]->getABS_V()) - { - tmp.H = volume->getSTACKS()[row_index][col_index]->getABS_H() + volume->getStacksWidth(); - tmp.h = volume->getSTACKS()[row_index][col_index+1]->getABS_V() - stripesCoords[row_index].up_left.V; - tmp.up = true; - stripesCorners[row_index].ups.push_back(tmp); - - tmp.H = volume->getSTACKS()[row_index][col_index+1]->getABS_H(); - tmp.h = stripesCoords[row_index].bottom_right.V - volume->getSTACKS()[row_index][col_index+1]->getABS_V() - volume->getStacksHeight(); - tmp.up = false; - stripesCorners[row_index].bottoms.push_back(tmp); - } - else - { - tmp.H = volume->getSTACKS()[row_index][col_index+1]->getABS_H(); - tmp.h = volume->getSTACKS()[row_index][col_index+1]->getABS_V() - stripesCoords[row_index].up_left.V; - tmp.up = true; - stripesCorners[row_index].ups.push_back(tmp); - - tmp.H = volume->getSTACKS()[row_index][col_index]->getABS_H()+volume->getStacksWidth(); - tmp.h = stripesCoords[row_index].bottom_right.V - volume->getSTACKS()[row_index][col_index+1]->getABS_V() - volume->getStacksHeight(); - tmp.up = false; - stripesCorners[row_index].bottoms.push_back(tmp); - } - } - - //for last VirtualStack of every stripe (h is not set because it doesn't matter) - tmp.H = volume->getSTACKS()[row_index][COL_END]->getABS_H() + volume->getStacksWidth(); - tmp.up = true; - stripesCorners[row_index].ups.push_back(tmp); - - tmp.up = false; - stripesCorners[row_index].bottoms.push_back(tmp); - } - - //ordered merging between ups and bottoms corners for every stripe - for(int row_index = ROW_START+1; row_index<=ROW_END; row_index++) - { - stripesCorners[row_index-1].merged.merge(stripesCorners[row_index-1].bottoms, compareCorners); - stripesCorners[row_index-1].merged.merge(stripesCorners[row_index ].ups, compareCorners); - } - - //ALLOCATING the MEMORY SPACE for image buffer - z_max_res = POW_INT(2,resolutions_size-1); - z_ratio= (int) depth/z_max_res; - buffer = new iom::real_t[height*width*z_max_res]; - - // 2014-10-31. Giulio. @ADDED stop and resume facility - FILE *fhandle; - sint64 z; - sint64 z_parts; - int dummy[S_MAX_MULTIRES]; // the resume facility requires parameters that are not used by the 2D series representation - - // 2014-11-03. Giulio. @FIXED stop and resume facility should inactive in test mode - if ( !test_mode ) { - // WARNING: uses saved_img_format to check that the operation has been resumed withe the sae parameters - if ( initResumer(saved_img_format,output_path.c_str(),resolutions_size,resolutions,0,0,0,HALVE_BY_MEAN,saved_img_format,saved_img_depth,fhandle) ) { - readResumerState(fhandle,output_path.c_str(),resolutions_size,dummy,dummy,dummy,z,z_parts); - } - else { - // dummy is initialized to zeros: substitutes parameters not used in the 2D case - memset(dummy,0,sizeof(int)*S_MAX_MULTIRES); - z = this->D0; - z_parts = 1; - } - } - else { // test mode - z = this->D0; - z_parts = 1; - } - - #ifdef S_TIME_CALC - double proc_time; - #endif - - for(/* 2014-10-31. Giulio. @DELETED (sint64 z = this->D0, z_parts = 1) */; z < this->D1; z += z_max_res, z_parts++) - { - // 2014-09-09. Alessandro. @FIXED missing buffer initialization and reset in 'mergeTiles()' method. - for(sint64 i=0; iupdate(((float)(z-D0+k+1)*100/(float)depth), progressBarMsg); - ProgressBar::instance()->show(); - } - - //looping on all stripes - for(int row_index=ROW_START; row_index<=ROW_END; row_index++) - { - //loading down stripe - if(row_index==ROW_START) stripe_up = NULL; - stripe_down = this->getStripe(row_index,(int)(z+k), restore_direction, stk_rst, blending_algo); - - #ifdef S_TIME_CALC - proc_time = -TIME(0); - #endif - - if(stripe_up) u_strp_bottom_displ = stripesCoords[row_index-1].bottom_right.V - V0; - d_strp_top_displ = stripesCoords[row_index ].up_left.V - V0; - if(stripe_up) u_strp_top_displ = stripesCoords[row_index-1].up_left.V - V0; - d_strp_left_displ = stripesCoords[row_index ].up_left.H - H0; - if(stripe_up) u_strp_left_displ = stripesCoords[row_index-1].up_left.H - H0; - d_strp_width = stripesCoords[row_index ].bottom_right.H - stripesCoords[row_index ].up_left.H; - if(stripe_up) u_strp_width = stripesCoords[row_index-1].bottom_right.H - stripesCoords[row_index-1].up_left.H; - if(stripe_up) u_strp_d_strp_overlap = u_strp_bottom_displ - d_strp_top_displ; - if(row_index!=ROW_END) - dd_strp_top_displ = stripesCoords[row_index+1].up_left.V - V0; - h_up = h_down = u_strp_d_strp_overlap; - - //overlapping zone - if(row_index!=ROW_START) - { - std::list::iterator cnr_i_next, cnr_i = stripesCorners[row_index-1].merged.begin(); - stripe_corner *cnr_left=&(*cnr_i), *cnr_right; - cnr_i++; - cnr_i_next = cnr_i; - cnr_i_next++; - - while( cnr_i != stripesCorners[row_index-1].merged.end()) - { - //computing h_up, h_overlap, h_down - cnr_right = &(*cnr_i); - if(cnr_i_next == stripesCorners[row_index-1].merged.end()) - { - h_up = cnr_left->up ? u_strp_d_strp_overlap : 0; - h_down = cnr_left->up ? 0 : u_strp_d_strp_overlap; - } - else - if(cnr_left->up) - h_up = cnr_left->h; - else - h_down = cnr_left->h; - - h_overlap = u_strp_d_strp_overlap - h_up - h_down; - - //splitting overlapping zone in sub-regions along H axis - for(sint64 j= cnr_left->H - H0; j < cnr_right->H - H0; j++) - { - delta_angle = PI/(h_overlap-1); - angle = 0; - - //UP stripe zone - buffer_ptr = &buffer[k*height*width+d_strp_top_displ*width+j]; - ustripe_ptr = &stripe_up[(d_strp_top_displ-u_strp_top_displ)*u_strp_width +j - u_strp_left_displ]; - for(sint64 i=d_strp_top_displ; i= 0 ? 0 : h_overlap); i++, buffer_ptr+=width, ustripe_ptr+= u_strp_width) - *buffer_ptr = *ustripe_ptr; - - //OVERLAPPING zone - buffer_ptr = &buffer[k*height*width+(d_strp_top_displ+h_up)*width+j]; - ustripe_ptr = &stripe_up[(d_strp_top_displ+h_up-u_strp_top_displ)*u_strp_width +j - u_strp_left_displ]; - dstripe_ptr = &stripe_down[(d_strp_top_displ+h_up-d_strp_top_displ)*d_strp_width +j - d_strp_left_displ]; - for(sint64 i=d_strp_top_displ+h_up; i= 0 ? h_overlap : 0))*width+j]; - dstripe_ptr = &stripe_down[((d_strp_top_displ+h_up+(h_overlap >= 0 ? h_overlap : 0))-d_strp_top_displ)*d_strp_width +j - d_strp_left_displ]; - for(sint64 i=d_strp_top_displ+h_up+(h_overlap >= 0 ? h_overlap : 0); i= 0 && j - d_strp_left_displ < stripesCoords[row_index].bottom_right.H) - *buffer_ptr = *dstripe_ptr; - } - - //moving to bottom stripe_up - delete stripe_up; - stripe_up=stripe_down; - - #ifdef S_TIME_CALC - proc_time += TIME(0); - StackStitcher::time_merging+=proc_time; - #endif - } - //releasing last stripe_down - delete stripe_down; - } - - //saving current buffer data at selected resolutions and in multitile format - for(int i=0; i< resolutions_size; i++) - { - if(show_progress_bar) - { - sprintf(progressBarMsg, "Generating resolution %d of %d",i+1,ISR_MAX(resolutions_size, resolutions_size)); - ProgressBar::instance()->updateInfo(progressBarMsg); - ProgressBar::instance()->show(); - } - - //buffer size along D is different when the remainder of the subdivision by z_max_res is considered - int z_size = (z_parts<=z_ratio) ? z_max_res : (depth%z_max_res); - - //halvesampling resolution if current resolution is not the deepest one - if(i!=0) - StackStitcher::halveSample(buffer,(int)(height/(POW_INT(2,i-1))),(int)(width/(POW_INT(2,i-1))),(int)(z_size/(POW_INT(2,i-1))),method); - - //saving at current resolution if it has been selected and iff buffer is at least 1 voxel (Z) deep - if(resolutions[i] && (z_size/(POW_INT(2,i))) > 0) - { - if(show_progress_bar) - { - sprintf(progressBarMsg, "Saving to disc resolution %d",i+1); - ProgressBar::instance()->updateInfo(progressBarMsg); - ProgressBar::instance()->show(); - } - - //storing in 'base_path' the absolute path of the directory that will contain all stacks - std::stringstream base_path; - base_path << output_path << "/RES(" << (int)(height/POW_INT(2,i)) << "x" << (int)(width/POW_INT(2,i)) << "x" << (int)(depth/POW_INT(2,i)) << ")/"; - - //looping on new stacks - for(int stack_row = 0, start_height = 0, end_height = 0; stack_row < n_stacks_V[i]; stack_row++) - { - //incrementing end_height - end_height = start_height + stacks_height[i][stack_row][0]-1; - - //computing V_DIR_path and creating the directory the first time it is needed - std::stringstream V_DIR_path; - V_DIR_path << base_path.str() << this->getMultiresABS_V_string(i,start_height); - if(!test_mode && z==D0 && !make_dir(V_DIR_path.str().c_str())) - { - char err_msg[S_STATIC_STRINGS_SIZE]; - sprintf(err_msg, "in mergeTiles(...): unable to create V_DIR = \"%s\"\n", V_DIR_path.str().c_str()); - throw iom::exception(err_msg); - } - - for(int stack_column = 0, start_width=0, end_width=0; stack_column < n_stacks_H[i]; stack_column++) - { - end_width = start_width + stacks_width [i][stack_row][stack_column]-1; - - //computing H_DIR_path and creating the directory the first time it is needed - std::stringstream H_DIR_path; - H_DIR_path << V_DIR_path.str() << "/" << this->getMultiresABS_V_string(i,start_height) << "_" << this->getMultiresABS_H_string(i,start_width); - if(!test_mode && z==D0 && !make_dir(H_DIR_path.str().c_str())) - { - char err_msg[S_STATIC_STRINGS_SIZE]; - sprintf(err_msg, "in mergeTiles(...): unable to create H_DIR = \"%s\"\n", H_DIR_path.str().c_str()); - throw iom::exception(err_msg); - } - - //saving HERE - for(int buffer_z=0; buffer_zgetMultiresABS_V_string(i,start_height) << "_" - << this->getMultiresABS_H_string(i,start_width) << "_" - // << abs_pos_z.str(); // Alessandro, 23/03/2013 - bug found: see above - << this->getMultiresABS_D_string(0, rel_pos_z); // Alessandro, 23/03/2013 - we pass '0' because rel_pos_z is the relative Z - // pixel coordinate in the HIGHEST (i=0) resolution image space (see above). - if(test_mode) - { - img_path.str(""); - img_path << volume->getSTACKS_DIR() << "/test_middle_slice"; - // // 2014-11-25. Giulio. @CHANGED the "tiff2D" plugin is explicitly used because in test mode the output plugin may not be a 2D plugin - // //iomanager::IOPluginFactory::getPlugin2D("tiff2D")->writeData( - // iim::VirtualVolume::saveImage( - // img_path.str(), - // buffer + buffer_z*(height/POW_INT(2,i))*(width/POW_INT(2,i)), - // (int)(height/(POW_INT(2,i))), - // (int)(width/(POW_INT(2,i))), - // start_height, - // end_height, - // start_width, - // end_width, - // saved_img_format, - // saved_img_depth); - } - //else { - // 2015-02-14. Giulio. restored call to saveImage which now calls the plugin - // 2014-09-10. Alessandro. @FIXED 'mergeTiles()' method to include plugin support. - //iomanager::IOPluginFactory::getPlugin2D(iomanager::IMOUT_PLUGIN)->writeData( - iim::VirtualVolume::saveImage( - img_path.str(), - buffer + buffer_z*(height/POW_INT(2,i))*(width/POW_INT(2,i)), - (int)(height/(POW_INT(2,i))), - (int)(width/(POW_INT(2,i))), - start_height, - end_height, - start_width, - end_width, - saved_img_format, - saved_img_depth); - //} - } - start_width += stacks_width [i][stack_row][stack_column]; - } - start_height += stacks_height[i][stack_row][0]; - } - } - } - - // 2014-10-31. Giulio. @ADDED save next group data - if ( !test_mode ) - saveResumerState(fhandle,resolutions_size,dummy,dummy,dummy,z+z_max_res,z_parts+1); - } - - if ( !test_mode ) { - // 2014-10-31. Giulio. @ADDED close resume - closeResumer(fhandle,output_path.c_str()); - - // reloads created volumes to generate .bin file descriptors at all resolutions - ref_sys temp = volume->getREF_SYS(); // required by clang compiler - iim::ref_sys reference = *((iim::ref_sys *) &temp); // the cast is needed because there are two ref_sys in different name spaces - // 2015-08-28. Giulio. the generated volume has always V coordinates at the first directory level and H coordinates at the second directory level - if ( reference.first == iim::horizontal || reference.first == iim::inv_horizontal ) { - iim::axis temp = reference.first; - reference.first = reference.second; - reference.second = reference.first; - } - for(int res_i=0; res_i< resolutions_size; res_i++) { - if(resolutions[res_i]) - { - //---- Alessandro 2013-04-22 partial fix: wrong voxel size computation. In addition, the predefined reference system {1,2,3} may not be the right - //one when dealing with CLSM data. The right reference system is stored in the object. A possible solution to implement - //is to check whether is a pointer to a object, then specialize it to and get its reference - //system. - //---- Giulio 2013-08-23 fixed - // 2014-09-09. Alessandro. @FIXED: propagate iim::IOException (otherwise it will crash...) and disable iim::DEBUG - try - { - iim::DEBUG = iim::NO_DEBUG; - iim::StackedVolume temp_vol(file_path[res_i].str().c_str(),reference, - volume->getVXL_V()*pow(2.0f,res_i), volume->getVXL_H()*pow(2.0f,res_i),volume->getVXL_D()*pow(2.0f,res_i)); - } - catch(iim::IOException & ioex) - { - throw iom::exception(ioex.what()); - } - - } - } - } - - - // deallocate memory - for(int res_i=0; res_i< resolutions_size; res_i++) - { - for(int stack_row = 0; stack_row < n_stacks_V[res_i]; stack_row++) - { - delete []stacks_height[res_i][stack_row]; - delete []stacks_width [res_i][stack_row]; - } - delete []stacks_height[res_i]; - delete []stacks_width[res_i]; - } - - //releasing allocated memory - delete buffer; - if(stk_rst) - delete stk_rst; - delete []stripesCoords; - for ( int i=0; igetN_ROWS(); i++ ) { - stripesCorners[i].ups.clear(); - stripesCorners[i].bottoms.clear(); - stripesCorners[i].merged.clear(); - } delete []stripesCorners; -} - -/************************************************************************************************************* -* Performs downsampling at a halved frequency on the given 3D image. The given image is overwritten in order -* to store its halvesampled version without allocating any additional resources. -**************************************************************************************************************/ -void StackStitcher::halveSample(iom::real_t* img, int height, int width, int depth, int method) -{ - #ifdef S_TIME_CALC - double proc_time = -TIME(0); - #endif - - float A,B,C,D,E,F,G,H; - - // indices are sint64 because offsets can be larger that 2^31 - 1 - - if ( method == HALVE_BY_MEAN ) { - - for(sint64 z=0; z A ) A = B; - B = img[2*z*width*height + (2*i+1)*width + 2*j]; - if ( B > A ) A = B; - B = img[2*z*width*height + (2*i+1)*width + (2*j+1)]; - if ( B > A ) A = B; - B = img[(2*z+1)*width*height + 2*i*width + 2*j]; - if ( B > A ) A = B; - B = img[(2*z+1)*width*height + 2*i*width + (2*j+1)]; - if ( B > A ) A = B; - B = img[(2*z+1)*width*height + (2*i+1)*width + 2*j]; - if ( B > A ) A = B; - B = img[(2*z+1)*width*height + (2*i+1)*width + (2*j+1)]; - if ( B > A ) A = B; - - //computing mean - img[z*(width/2)*(height/2) + i*(width/2) + j] = A; - } - } - } - - } - else { - char buffer[S_STATIC_STRINGS_SIZE]; - sprintf(buffer,"in halveSample(...): invalid halving method\n"); - throw iom::exception(buffer); - } - #ifdef S_TIME_CALC - proc_time += TIME(0); - StackStitcher::time_multiresolution+=proc_time; - #endif - -} - -/************************************************************************************************************* -* Performs downsampling at a halved frequency on the given 3D image along V and H dimensions only. The given -* image is overwritten in order to store its halvesampled version without allocating any additional resources. -**************************************************************************************************************/ -void StackStitcher::halveSample2D(iom::real_t* img, int height, int width, int depth, int method) -{ - #ifdef S_TIME_CALC - double proc_time = -TIME(0); - #endif - - float A,B,C,D; - - // indices are sint64 because offsets can be larger that 2^31 - 1 - - if ( method == HALVE_BY_MEAN ) { - - for(sint64 z=0; z A ) A = B; - B = img[z*width*height + (2*i+1)*width + 2*j]; - if ( B > A ) A = B; - B = img[z*width*height + (2*i+1)*width + (2*j+1)]; - if ( B > A ) A = B; - - //computing max - img[z*(width/2)*(height/2) + i*(width/2) + j] = A; - } - } - } - - } - else { - char buffer[S_STATIC_STRINGS_SIZE]; - sprintf(buffer,"in halveSample(...): invalid halving method\n"); - throw iom::exception(buffer); - } - #ifdef S_TIME_CALC - proc_time += TIME(0); - StackStitcher::time_multiresolution+=proc_time; - #endif - -} - -/************************************************************************************************************* -* For each stack, the vector of redundant displacements along D is projected into the displacement which embe- -* ds the most reliable parameters. After this operation, such vector will contain only the projected displace- -* ment. Where for a pair of adjacent stacks no displacement is available, a displacement is generated using -* nominal stage coordinates. -**************************************************************************************************************/ -void StackStitcher::projectDisplacements() throw (iom::exception) -{ - #if S_VERBOSE > 3 - printf("......in StackStitcher::projectDisplacements()\n"); - #endif - - VirtualStack *stk; - for(int i=0; igetN_ROWS(); i++) - { - for(int j=0; jgetN_COLS(); j++) - { - stk = volume->getSTACKS()[i][j]; - if(i!= 0) - { - if(stk->getNORTH().size() != 0) - Displacement::projectDisplacements(stk->getNORTH()); - else - { - DisplacementMIPNCC* nominal = new DisplacementMIPNCC(-volume->getDEFAULT_DISPLACEMENT_V(), 0, volume->getDEFAULT_DISPLACEMENT_D()); - stk->getNORTH().push_back((Displacement*)nominal); - } - } - if(j!= volume->getN_COLS() -1) - { - if(stk->getEAST().size() != 0) - Displacement::projectDisplacements(stk->getEAST()); - else - { - DisplacementMIPNCC* nominal = new DisplacementMIPNCC(0, volume->getDEFAULT_DISPLACEMENT_H(), volume->getDEFAULT_DISPLACEMENT_D()); - stk->getEAST().push_back((Displacement*)nominal); - } - } - if(i!= volume->getN_ROWS() -1) - { - if(stk->getSOUTH().size() != 0) - Displacement::projectDisplacements(stk->getSOUTH()); - else - { - DisplacementMIPNCC* nominal = new DisplacementMIPNCC(volume->getDEFAULT_DISPLACEMENT_V(), 0, volume->getDEFAULT_DISPLACEMENT_D()); - stk->getSOUTH().push_back((Displacement*)nominal); - } - } - if(j!= 0) - { - if(stk->getWEST().size() != 0) - Displacement::projectDisplacements(stk->getWEST()); - else - { - DisplacementMIPNCC* nominal = new DisplacementMIPNCC(0, -volume->getDEFAULT_DISPLACEMENT_H(), volume->getDEFAULT_DISPLACEMENT_D()); - stk->getWEST().push_back((Displacement*)nominal); - } - } - } - } -} - -/************************************************************************************************************* -* Assuming that for each pair of adjacent stacks exists one and only one displacement, this displacement is -* thresholded according to the given . When a displacement is not reliable enough, its -* parameters are set to default values (i.e. nominal motorized stage coordinates). -* Moreover, stacks which do not have any reliable single-direction displacements with all 4 neighbors are mar- -* ked as NON STITCHABLE. -**************************************************************************************************************/ -void StackStitcher::thresholdDisplacements(float reliability_threshold) throw (iom::exception) -{ - #if S_VERBOSE > 3 - printf("......in StackStitcher::thresholdDisplacements(reliability_threshold = %.4f)\n", reliability_threshold); - #endif - - VirtualStack *stk; - char errMsg[2000]; - - //checking precondition: one and only one displacement must exist for each pair of adjacent stacks - for(int i=0; igetN_ROWS(); i++) - for(int j=0; jgetN_COLS(); j++) - { - stk = volume->getSTACKS()[i][j]; - - if(i != 0 && stk->getNORTH().size() != 1) - throw iom::exception("in StackStitcher::thresholdDisplacements(...): one and only displacement must exist for each pair of adjacent stacks."); - - if(j != 0 && stk->getWEST().size() != 1) - throw iom::exception("in StackStitcher::thresholdDisplacements(...): one and only displacement must exist for each pair of adjacent stacks."); - - if(i != (volume->getN_ROWS()-1) && stk->getSOUTH().size() != 1) - throw iom::exception("in StackStitcher::thresholdDisplacements(...): one and only displacement must exist for each pair of adjacent stacks."); - - if(j != (volume->getN_COLS()-1) && stk->getEAST().size() != 1) - throw iom::exception("in StackStitcher::thresholdDisplacements(...): one and only displacement must exist for each pair of adjacent stacks."); - } - - //thresholding displacements - for(int i=0; igetN_ROWS(); i++) - for(int j=0; jgetN_COLS(); j++) - { - stk = volume->getSTACKS()[i][j]; - if(i!= 0) { - if(stk->getNORTH().size() == 1) - stk->getNORTH()[0]->threshold(reliability_threshold); - else - { - sprintf(errMsg, "in StackStitcher::thresholdDisplacements(...): stack [%d,%d] must have exactly one displacement at NORTH", i, j); - throw iom::exception(errMsg); - } - } - if(j!= volume->getN_COLS() -1) { - if(stk->getEAST().size() == 1) - stk->getEAST()[0]->threshold(reliability_threshold); - else - { - sprintf(errMsg, "in StackStitcher::thresholdDisplacements(...): stack [%d,%d] must have exactly one displacement at EAST", i, j); - throw iom::exception(errMsg); - } - } - if(i!= volume->getN_ROWS() -1) { - if(stk->getSOUTH().size() == 1) - stk->getSOUTH()[0]->threshold(reliability_threshold); - else - { - sprintf(errMsg, "in StackStitcher::thresholdDisplacements(...): stack [%d,%d] must have exactly one displacement at SOUTH", i, j); - throw iom::exception(errMsg); - } - } - if(j!= 0) { - if(stk->getWEST().size() == 1) - stk->getWEST()[0]->threshold(reliability_threshold); - else - { - sprintf(errMsg, "in StackStitcher::thresholdDisplacements(...): stack [%d,%d] must have exactly one displacement at WEST", i, j); - throw iom::exception(errMsg); - } - } - } - - //find stitchable stacks, i.e. stacks that have at least one reliable single-direction displacement - bool stitchable; - for(int i=0; igetN_ROWS(); i++) - for(int j=0; jgetN_COLS(); j++) - { - stitchable = false; - stk = volume->getSTACKS()[i][j]; - if(i!= 0) - for(int k=0; k<3; k++) - stitchable = stitchable || (stk->getNORTH()[0]->getReliability(direction(k)) >= reliability_threshold); - if(j!= volume->getN_COLS() -1) - for(int k=0; k<3; k++) - stitchable = stitchable || (stk->getEAST()[0]->getReliability(direction(k)) >= reliability_threshold); - if(i!= volume->getN_ROWS() -1) - for(int k=0; k<3; k++) - stitchable = stitchable || (stk->getSOUTH()[0]->getReliability(direction(k)) >= reliability_threshold); - if(j!= 0) - for(int k=0; k<3; k++) - stitchable = stitchable || (stk->getWEST()[0]->getReliability(direction(k)) >= reliability_threshold); - volume->getSTACKS()[i][j]->setStitchable(stitchable); - } -} - -/************************************************************************************************************* -* Executes the compute tiles placement algorithm associated to the given ID -**************************************************************************************************************/ -void StackStitcher::computeTilesPlacement(int algorithm_type) throw (iom::exception) -{ - #if S_VERBOSE > 3 - printf("......in StackStitcher::computeTilesPlacement(algorithm_type = %d)\n", algorithm_type); - #endif - - TPAlgo *algorithm = TPAlgo::instanceAlgorithm(algorithm_type, volume); - algorithm->execute(); -} - -/************************************************************************************************************* -* Functions used to obtain absolute coordinates at different resolutions from relative coordinates -**************************************************************************************************************/ -int StackStitcher::getMultiresABS_V(int res, int REL_V) -{ - if(volume->getVXL_V() > 0) - return (int)ROUND(volume->getABS_V( V0 + REL_V*POW_INT(2,res) )*10); - else - return (int)ROUND(volume->getABS_V( V0 - 1 + REL_V*POW_INT(2,res))*10 + volume->getVXL_V()*POW_INT(2,res)*10); -} -std::string StackStitcher::getMultiresABS_V_string(int res, int REL_V) -{ - std::stringstream multires_merging_x_pos; - multires_merging_x_pos.width(6); - multires_merging_x_pos.fill('0'); - multires_merging_x_pos << this->getMultiresABS_V(res, REL_V); - return multires_merging_x_pos.str(); -} -int StackStitcher::getMultiresABS_H(int res, int REL_H) -{ - if(volume->getVXL_H() > 0) - return (int)ROUND(volume->getABS_H( H0 + REL_H*POW_INT(2,res) )*10); - else - return (int)ROUND(volume->getABS_H( H0 - 1 + REL_H*POW_INT(2,res))*10 + volume->getVXL_H()*POW_INT(2,res)*10); -} -std::string StackStitcher::getMultiresABS_H_string(int res, int REL_H) -{ - std::stringstream multires_merging_y_pos; - multires_merging_y_pos.width(6); - multires_merging_y_pos.fill('0'); - multires_merging_y_pos << this->getMultiresABS_H(res, REL_H); - return multires_merging_y_pos.str(); -} -int StackStitcher::getMultiresABS_D(int res, int REL_D) -{ - if(volume->getVXL_D() > 0) - return (int)ROUND(volume->getABS_D( D0 + REL_D*POW_INT(2,res) )*10); - else - return (int)ROUND(volume->getABS_D( D0 - 1 + REL_D*POW_INT(2,res) )*10 + volume->getVXL_D()*POW_INT(2,res)*10); -} -std::string StackStitcher::getMultiresABS_D_string(int res, int REL_D) -{ - std::stringstream multires_merging_z_pos; - multires_merging_z_pos.width(6); - multires_merging_z_pos.fill('0'); - multires_merging_z_pos << this->getMultiresABS_D(res, REL_D); - return multires_merging_z_pos.str(); -} - -/************************************************************************************************************* -* Functions used to save single phase time performances -**************************************************************************************************************/ -void StackStitcher::saveComputationTimes(const char *filename, volumemanager::VirtualVolume &stk_org, double total_time) -{ - //building filename with local time - time_t rawtime; - struct tm * timeinfo; - time ( &rawtime ); - timeinfo = localtime ( &rawtime ); - char filepath[5000]; - sprintf(filepath, "%s/%s_(%04d_%02d_%02d___%02d%02d).txt", stk_org.getSTACKS_DIR(), filename, timeinfo->tm_year+1900, timeinfo->tm_mon+1, timeinfo->tm_mday, timeinfo->tm_hour, timeinfo->tm_min); - - FILE *file = fopen(filepath, "w"); - if(file) - { - double acc = 0; - if(StackStitcher::time_displ_comp > 0) - { - fprintf(file, "time_displ_comp\t\t\t%.0f minutes,\t%.1f seconds\n", (StackStitcher::time_displ_comp/60), StackStitcher::time_displ_comp); - acc+=StackStitcher::time_displ_comp; - } - if(StackStitcher::time_stack_desc > 0) - { - fprintf(file, "time_stack_desc\t\t\t%.0f minutes,\t%.1f seconds\n", (StackStitcher::time_stack_desc/60), StackStitcher::time_stack_desc); - acc+=StackStitcher::time_stack_desc; - } - if(StackStitcher::time_merging > 0) - { - fprintf(file, "time_merging\t\t\t%.0f minutes,\t%.1f seconds\n", (StackStitcher::time_merging/60), StackStitcher::time_merging); - acc+=StackStitcher::time_merging; - } - if(StackStitcher::time_stack_restore > 0) - { - fprintf(file, "time_stack_restore\t\t%.0f minutes,\t%.1f seconds\n", (StackStitcher::time_stack_restore/60), StackStitcher::time_stack_restore); - acc+=StackStitcher::time_stack_restore; - } - if(StackStitcher::time_multiresolution > 0) - { - fprintf(file, "time_multiresolution\t%.0f minutes,\t%.1f seconds\n", (StackStitcher::time_multiresolution/60), StackStitcher::time_multiresolution); - acc+=StackStitcher::time_multiresolution; - } - if(acc > 0) - { - fprintf(file, "SUM\t\t\t\t\t\t%.0f minutes,\t%.1f seconds\n", (acc/60), acc); - acc+=StackStitcher::time_multiresolution; - } - - if(iomanager::IOPluginFactory::getTimeIO() > 0) - fprintf(file, "\nTIME I/O\t\t\t\t%.0f minutes,\t%.1f seconds\n", (iomanager::IOPluginFactory::getTimeIO()/60), iomanager::IOPluginFactory::getTimeIO()); - if(iomanager::IOPluginFactory::getTimeConversions() > 0) - fprintf(file, "TIME I/O conversions\t%.0f minutes,\t%.1f seconds\n", (iomanager::IOPluginFactory::getTimeConversions()/60), iomanager::IOPluginFactory::getTimeConversions()); - - if(total_time > 0) - { - fprintf(file, "Non-measured TIME\t\t%.0f minutes,\t%.1f seconds\n", ((total_time-iomanager::IOPluginFactory::getTimeIO()-iomanager::IOPluginFactory::getTimeConversions()-acc)/60), (total_time-iomanager::IOPluginFactory::getTimeIO()-iomanager::IOPluginFactory::getTimeConversions()-acc)); - fprintf(file, "TOTAL TIME\t\t\t\t%.0f minutes,\t%.1f seconds\n", (total_time/60), total_time); - } - - fclose(file); - } - -} diff --git a/v3d_main/terafly/src/core/stitcher/StackStitcher.h b/v3d_main/terafly/src/core/stitcher/StackStitcher.h deleted file mode 100644 index d142e78060..0000000000 --- a/v3d_main/terafly/src/core/stitcher/StackStitcher.h +++ /dev/null @@ -1,350 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* -* Bria, A., Iannello, G., "TeraStitcher - A Tool for Fast 3D Automatic Stitching of Teravoxel-sized Microscopy Images", (2012) BMC Bioinformatics, 13 (1), art. no. 316. -* -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -* 2015-08-16. Giulio. @ADDED method for halvesampling only V and H dimensions -* 2015-02-26. Giulio. @ADDED a destructor to class StackStitcher -* 2015-02-18. Giulio. @ADDED declared class UnstitchedVolume as a friend of class StackStitcher -* 2014-12-06. Giulio. @ADDED createDirectoryHiererchy method. -* 2014-09-12. Alessandro. @ADDED [z0, z1] subdata selection along Z in the 'computeDisplacements()' method. -* 2014-09-09. Alessandro. @CHANGED. Black pixels (=0) are ignored in 'sinusoidal_blending()' function (especially useful in 'sparse data' mode). -* 2014-09-02. Alessandro. @FIXED major bug in 'getStripe()' method. Argument 2 ('d_index') has 'short' type, but it should have at least 'int'. -*/ - -#ifndef STACK_STITCHER_H -#define STACK_STITCHER_H - - -#include -#include "S_config.h" -//#include "../VolumeManager/volumemanager.config.h" -#include "iomanager.config.h" - -#ifdef max -#undef max -#endif - -class StackRestorer; - -// #ifndef _VIRTUAL_VOLUME_H -// class volumemanager::VirtualVolume; -// #endif -// #ifndef STACK_H_ -// class VirtualStack; -// #endif - -#include "../volumemanager/vmVirtualStack.h" -#include "../volumemanager/vmVirtualVolume.h" - -class StackStitcher -{ - friend class UnstitchedVolume; // 2015-02-18. Giulio. added unstitched volume - - private: - - /******OBJECT MEMBERS******/ - //StackedVolume *volume; //pointer to the object to be stitched - volumemanager::VirtualVolume *volume; //pointer to the object to be stitched - int V0, V1, H0, H1, D0, D1; //voxel intervals that identify the final stitched volume - int ROW_START, COL_START, ROW_END, COL_END; //stack indexes that identify the stacks involved in stitching - - /******CLASS MEMBERS******/ - static double time_displ_comp; //time employed for pairwise displacements computation - static double time_merging; //time employed to merge stacks - static double time_stack_desc; //time employed to compute stacks descriptions - static double time_stack_restore; //time employed to restore stacks - static double time_multiresolution; //time employed to obtain stitched volume at different resolutions - - - /***OBJECT PRIVATE METHODS****/ - - //default constructor will not be accessible - StackStitcher(void){} - - - /************************************************************************************************************* - * Merges all slices of the given row at the given depth index, so obtaining the stripe that is returned. - * Uses [...]_blending() functions to blend pixels in overlapping zones. The appropriate blending function is - * selected by the [blending_algo] parameter. If a object has been passed, each slice is re- - * stored before it is combined into the final stripe. - **************************************************************************************************************/ - iom::real_t* getStripe(int row_index, int d_index, int restore_direction=-1, StackRestorer* stk_rst=NULL, - int blending_algo=S_SINUSOIDAL_BLENDING) throw (iom::exception); - - /************************************************************************************************************* - * Returns the (up = true -> TOP, up = false -> BOTTOM) V coordinate of the virtual stripe at row. - **************************************************************************************************************/ - int getStripeABS_V(int row_index, bool up); - - - - /***CLASS PRIVATE METHODS****/ - - /************************************************************************************************************* - * Blending functions that returns the value at blending and . - * is in [0, PI] where 0 occurs at the first pixel of the overlapping zone and PI at last pixel of the - * overlapping zone. IMPORTANT: due to efficiency reasons, it is better to handle different types of blending - * functions with function pointers instead of using polymorphism of OOP. - **************************************************************************************************************/ - static inline iom::real_t sinusoidal_blending(double& angle, iom::real_t& pixel1, iom::real_t& pixel2){ - - // 2014-09-09. Alessandro. @CHANGED. Black pixels (=0) are ignored in 'sinusoidal_blending()' function. - if(!pixel1 || !pixel2) - return std::max(pixel1, pixel2); - - return (iom::real_t)( ((cos(angle)+1.0F)*0.5F)*pixel1 + ( 1.0F - ((cos(angle)+1.0F)*0.5F))*pixel2 ); - } - - static inline iom::real_t no_blending(double& angle, iom::real_t& pixel1, iom::real_t& pixel2){ - return (angle <= S_PI/2 ? pixel1 : pixel2); - } - - /************************************************************************************************************* - * This is a special blending function (together with the necessary static variables) which draws blank lines - * along stacks borders without performing any blending. This enables easy checking of motorized stages coordi- - * nates precision. - **************************************************************************************************************/ - static double stack_marging_old_val; - static bool blank_line_drawn; - static inline iom::real_t stack_margin(double& angle, iom::real_t& pixel1, iom::real_t& pixel2) - { - if(angle == stack_marging_old_val && blank_line_drawn){ - stack_marging_old_val = angle; - return 1; - } - else if(angle > S_PI/2.0 && stack_marging_old_val < S_PI/2.0){ - stack_marging_old_val = angle; - blank_line_drawn = true; - return 1; - } - else{ - stack_marging_old_val = angle; - blank_line_drawn = false; - return ( angle <= S_PI/2 ? pixel1 : pixel2); - } - } - - /************************************************************************************************************* - * Performs downsampling at a halved frequency on the given 3D image. The given image is overwritten in order - * to store its halvesampled version without allocating any additional resources. - **************************************************************************************************************/ - static void halveSample(iom::real_t* img, int height, int width, int depth, int method = HALVE_BY_MEAN ); - - /************************************************************************************************************* - * Performs downsampling at a halved frequency on the given 3D image along V and H dimensions only. The given - * image is overwritten in order to store its halvesampled version without allocating any additional resources. - **************************************************************************************************************/ - static void halveSample2D(iom::real_t* img, int height, int width, int depth, int method = HALVE_BY_MEAN ); - - public: - - StackStitcher(volumemanager::VirtualVolume* _volume); - - // WARNING: the distructor does not deallocate the 'volume' field - ~StackStitcher(void); - - // compute pairwise displacements - // 2014-09-12. Alessandro. @ADDED [z0, z1] subdata selection along Z in the 'computeDisplacements()' method. - void computeDisplacements( - int algorithm_type, // ID of the pairwise displacement algorithm to be used. - int row0 = -1, // subdata selection along X: [row0, row1] rows will be processed only - int col0 = -1, // subdata selection along Y: [col0, col1] cols will be processed only - int row1 = -1, // subdata selection along X: [row0, row1] rows will be processed only - int col1 = -1, // subdata selection along Y: [col0, col1] cols will be processed only - int overlap_V = -1, // overlaps along V and H directions. If not given, default values are ... - int overlap_H =-1, // ... computed using the members of the object. - int displ_max_V=S_DISPL_SEARCH_RADIUS_DEF, // maximum displacements along VHD between two adjacent stacks. ... - int displ_max_H=S_DISPL_SEARCH_RADIUS_DEF, // ... If not given, value S_DISPL_SEARCH_RADIUS_DEF is assigned. - int displ_max_D=S_DISPL_SEARCH_RADIUS_DEF, - int subvol_DIM_D = S_SUBVOL_DIM_D_DEFAULT, // dimension of layers obtained by dividing the volume along D. - bool restoreSPIM=false, // enable SPIM artifacts removal (zebrated patterns) ... - int restore_direction=-1, // ... along the given direction. - bool show_progress_bar=true, // enable/disable progress bar with estimated time remaining - int z0=-1, // subdata selection along Z: [z0, z1] slices will be processed only - int z1=-1) // subdata selection along Z: [z0, z1] slices will be processed only - throw (iom::exception); - - - /************************************************************************************************************* - * For each stack, the vector of redundant displacements along D is projected into the displacement which embe- - * ds the most reliable parameters. After this operation, such vector will contain only the projected displace- - * ment. Where for a pair of adjacent stacks no displacement is available, a displacement is generated using - * nominal stage coordinates. - **************************************************************************************************************/ - void projectDisplacements() throw (iom::exception); - - /************************************************************************************************************* - * Assuming that for each pair of adjacent stacks exists one and only one displacement, this displacement is - * thresholded according to the given . When a displacement is not reliable enough, its - * parameters are set to default values (i.e. nominal motorized stage coordinates). - * Moreover, stacks which do not have any reliable single-direction displacements with all 4 neighbors are mar- - * ked as NON STITCHABLE. - **************************************************************************************************************/ - void thresholdDisplacements(float reliability_threshold) throw (iom::exception); - - - /************************************************************************************************************* - * Executes the compute tiles placement algorithm associated to the given ID - **************************************************************************************************************/ - void computeTilesPlacement(int algorithm_type) throw (iom::exception); - - - /************************************************************************************************************* - * Computes final stitched volume dimensions assuming that current object contains the correct - * stack coordinates. The given parameters identify the possible VOI (Volume Of Interest). If these are not us- - * ed, the whole volume is considered and the parameter is used to discard rows - * or columns with no stitchable stacks - **************************************************************************************************************/ - void computeVolumeDims(bool exclude_nonstitchable_stacks = true, int _ROW_START = -1, int _ROW_END = -1, - int _COL_START = -1, int _COL_END = -1, int _D0 = -1, int _D1 = -1) throw (iom::exception); - - /************************************************************************************************************* - * Method to be called for tile merging. <> parameters are mandatory, while [] are optional. - * : absolute directory path where merged tiles have to be stored. - * [slice_height/width] : desired dimensions of tiles slices after merging. It is actually an upper-bound of - * the actual slice dimensions, which will be computed in such a way that all tiles di- - * mensions can differ by 1 pixel only along both directions. If not given, the maximum - * allowed dimensions will be set, which will result in a volume composed by one large - * tile only. - * [resolutions] : pointer to an array of S_MAX_MULTIRES size which boolean entries identify the acti- - * vaction/deactivation of the i-th resolution. If not given, all resolutions will be - * activated. - * [exclude_nonstitc...] - * [_...START/END] - * [_D0/_D1] : identify the possible VOI (Volume Of Interest). If these are not used, the whole vo- - * lume is considered and the parameter is used to dis- - * card rows or columns with no stitchable stacks. - * [restoreSPIM] : enables SPIM artifacts removal (zebrated patterns) along the given direction. - * [restore_direction] : direction of SPIM zebrated patterns to be removed. - * [blending_algo] : ID of the blending algorithm to be used in the overlapping regions. - * [test_mode] : if enabled, the middle slice of the whole volume will be stitched and and saved lo- - * cally. Stage coordinates will be used, s o this can be used to test their precision - * as well as the selected reference system. - * [show_progress_bar] : enables/disables progress bar with estimated time remaining. - * [saved_img_format] : determines saved images format ("png","tif","jpeg", etc.). - * [saved_img_depth] : determines saved images bitdepth (16 or 8). - **************************************************************************************************************/ - void mergeTiles(std::string output_path, int slice_height = -1, int slice_width = -1, bool* resolutions = NULL, - bool exclude_nonstitchable_stacks =true, int _ROW_START=-1, int _ROW_END=-1, int _COL_START=-1, - int _COL_END=-1, int _D0=-1, int _D1=-1, bool restoreSPIM=false, int restore_direction=-1, - int blending_algo=S_SINUSOIDAL_BLENDING, int method = HALVE_BY_MEAN, bool test_mode=false, bool show_progress_bar= true, - const char* saved_img_format=iom::DEF_IMG_FORMAT.c_str(), int saved_img_depth=iom::DEF_BPP) throw (iom::exception); - - - /************************************************************************************************************* - * Functions used to save single phase time performances - **************************************************************************************************************/ - static void saveComputationTimes(const char *filename, volumemanager::VirtualVolume &stk_org, double total_time=-1); - - /************************************************************************************************************* - * Get methods - **************************************************************************************************************/ - int getV0(){return V0;} - int getV1(){return V1;} - int getH0(){return H0;} - int getH1(){return H1;} - int getD0(){return D0;} - int getD1(){return D1;} - int getROW0(){return ROW_START;} - int getROW1(){return ROW_END;} - int getCOL0(){return COL_START;} - int getCOL1(){return COL_END;} - - /************************************************************************************************************* - * Functions used to obtain absolute coordinates at different resolutions from relative coordinates - **************************************************************************************************************/ - int getMultiresABS_V(int res, int REL_V); - std::string getMultiresABS_V_string(int res, int REL_V); - int getMultiresABS_H(int res, int REL_H); - std::string getMultiresABS_H_string(int res, int REL_H); - int getMultiresABS_D(int res, int REL_D); - std::string getMultiresABS_D_string(int res, int REL_D); - - /************************************************************************************************************* - * Method to be called for tile merging. <> parameters are mandatory, while [] are optional. - * : absolute directory path where merged tiles have to be stored. - * [block_height/width/depth]: desired dimensions of tiles slices after merging. It is actually an upper-bound of - * the actual slice dimensions, which will be computed in such a way that all tiles di- - * mensions can differ by 1 pixel only along both directions. If not given, the maximum - * allowed dimensions will be set, which will result in a volume composed by one large - * tile only. - * [resolutions] : pointer to an array of S_MAX_MULTIRES size which boolean entries identify the acti- - * vaction/deactivation of the i-th resolution. If not given, all resolutions will be - * activated. - * [exclude_nonstitc...] - * [_...START/END] - * [_D0/_D1] : identify the possible VOI (Volume Of Interest). If these are not used, the whole vo- - * lume is considered and the parameter is used to dis- - * card rows or columns with no stitchable stacks. - * [restoreSPIM] : enables SPIM artifacts removal (zebrated patterns) along the given direction. - * [restore_direction] : direction of SPIM zebrated patterns to be removed. - * [blending_algo] : ID of the blending algorithm to be used in the overlapping regions. - * [test_mode] : if enabled, the middle slice of the whole volume will be stitched and and saved lo- - * cally. Stage coordinates will be used, s o this can be used to test their precision - * as well as the selected reference system. - * [show_progress_bar] : enables/disables progress bar with estimated time remaining. - * [saved_img_format] : determines saved images format ("png","tif","jpeg", etc.). - * [saved_img_depth] : determines saved images bitdepth (16 or 8). - * [par_mode] : if enabled, do not take into account parameters _D0/_D1 is determining the mane of - * the directories and do not generates the file mdata.bin in the output volume - **************************************************************************************************************/ - - void mergeTilesVaa3DRaw(std::string output_path, int block_height = -1, int block_width = -1, int block_depth = -1, bool* resolutions = NULL, - bool exclude_nonstitchable_stacks =true, int _ROW_START=-1, int _ROW_END=-1, int _COL_START=-1, - int _COL_END=-1, int _D0=-1, int _D1=-1, bool restoreSPIM=false, int restore_direction=-1, - int blending_algo=S_SINUSOIDAL_BLENDING, int method = HALVE_BY_MEAN, bool isotropic=false, bool test_mode=false, bool show_progress_bar= true, - const char* saved_img_format=iom::DEF_IMG_FORMAT.c_str(), int saved_img_depth=iom::DEF_BPP, bool par_mode=false) throw (iom::exception); - - - /************************************************************************************************************* - * Method to be called for creating the directory hierarchy without actually saving image tiles. - * It can be used to perform the mergeTiles operation on different volume portions in parallel - * Has must be called with the same parameters as mergeTilesVaa3DRaw - **************************************************************************************************************/ - void createDirectoryHierarchy (std::string output_path, int block_height = -1, int block_width = -1, int block_depth = -1, bool* resolutions = NULL, - bool exclude_nonstitchable_stacks =true, int _ROW_START=-1, int _ROW_END=-1, int _COL_START=-1, - int _COL_END=-1, int _D0=-1, int _D1=-1, bool restoreSPIM=false, int restore_direction=-1, - int blending_algo=S_SINUSOIDAL_BLENDING, int method = HALVE_BY_MEAN, bool isotropic=false, bool test_mode=false, bool show_progress_bar= true, - const char* saved_img_format=iom::DEF_IMG_FORMAT.c_str(), int saved_img_depth=iom::DEF_BPP, bool par_mode=false) throw (iom::exception); - - /************************************************************************************************************* - * Method to be called for creating the metadata file of the output volume starting from the importad unstitched - * volume. It can be used to perform the mergeTiles operation on different volume portions in parallel - * Has must be called with the same parameters as mergeTilesVaa3DRaw - **************************************************************************************************************/ - void mdataGenerator (std::string output_path, int block_height = -1, int block_width = -1, int block_depth = -1, bool* resolutions = NULL, - bool exclude_nonstitchable_stacks =true, int _ROW_START=-1, int _ROW_END=-1, int _COL_START=-1, - int _COL_END=-1, int _D0=-1, int _D1=-1, bool restoreSPIM=false, int restore_direction=-1, - int blending_algo=S_SINUSOIDAL_BLENDING, int method = HALVE_BY_MEAN, bool isotropic=false, bool test_mode=false, bool show_progress_bar= true, - const char* saved_img_format=iom::DEF_IMG_FORMAT.c_str(), int saved_img_depth=iom::DEF_BPP, bool par_mode=false) throw (iom::exception); -}; - -#endif - - diff --git a/v3d_main/terafly/src/core/stitcher/TPAlgo.cpp b/v3d_main/terafly/src/core/stitcher/TPAlgo.cpp deleted file mode 100644 index 2ded0cc9a4..0000000000 --- a/v3d_main/terafly/src/core/stitcher/TPAlgo.cpp +++ /dev/null @@ -1,56 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* -* Bria, A., Iannello, G., "TeraStitcher - A Tool for Fast 3D Automatic Stitching of Teravoxel-sized Microscopy Images", (2012) BMC Bioinformatics, 13 (1), art. no. 316. -* -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -#include -#include "TPAlgo.h" -#include "TPAlgoMST.h" -#include "S_config.h" - -using namespace volumemanager; - -TPAlgo::TPAlgo(int _TYPE, VirtualVolume * _volume) -{ - TYPE = _TYPE; - volume = _volume; -} - -//static method which is responsible to instance and return the algorithm of the given type -TPAlgo* TPAlgo::instanceAlgorithm(int _type, VirtualVolume * _volume) -{ - #if S_VERBOSE>4 - printf("........in TPAlgo::instanceAlgorithm(int _type, VirtualVolume * _volume)\n",_type); - #endif - - if (_type == S_FATPM_SP_TREE) - return (TPAlgo*)(new TPAlgoMST(_volume)); - else - { - char err_msg[S_STATIC_STRINGS_SIZE]; - sprintf(err_msg, "in TPAlgo::instanceAlgorithm(....): unsupported algorithm type (\"%d\")", _type); - throw iom::exception(err_msg); - } -} diff --git a/v3d_main/terafly/src/core/stitcher/TPAlgo.h b/v3d_main/terafly/src/core/stitcher/TPAlgo.h deleted file mode 100644 index c4a2f3a637..0000000000 --- a/v3d_main/terafly/src/core/stitcher/TPAlgo.h +++ /dev/null @@ -1,57 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* -* Bria, A., Iannello, G., "TeraStitcher - A Tool for Fast 3D Automatic Stitching of Teravoxel-sized Microscopy Images", (2012) BMC Bioinformatics, 13 (1), art. no. 316. -* -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -#ifndef _TILE_PLACEMENT_ALGORITHM_H -#define _TILE_PLACEMENT_ALGORITHM_H - -#include "vmStackedVolume.h" - -class TPAlgo -{ - protected: - - int TYPE; //type of algorithm - volumemanager::VirtualVolume* volume; //pointer to the object on which the current algorithm has to be executed - - public: - - TPAlgo(void){}; - TPAlgo(int _TYPE, volumemanager::VirtualVolume * _volume); - virtual ~TPAlgo(void){}; - - /************************************************************************************************************* - * Abstract method that all derived classes must implement. - * Finds the optimal tile placement on the object member - **************************************************************************************************************/ - virtual void execute() throw (iom::exception) = 0; - - //static method which is responsible to instance and return the algorithm of the given type - static TPAlgo* instanceAlgorithm(int _type, volumemanager::VirtualVolume * _volume); -}; - -#endif /* _TILE_PLACEMENT_ALGORITHM_H */ - diff --git a/v3d_main/terafly/src/core/stitcher/TPAlgoMST.cpp b/v3d_main/terafly/src/core/stitcher/TPAlgoMST.cpp deleted file mode 100644 index fa22bf2c63..0000000000 --- a/v3d_main/terafly/src/core/stitcher/TPAlgoMST.cpp +++ /dev/null @@ -1,268 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* -* Bria, A., Iannello, G., "TeraStitcher - A Tool for Fast 3D Automatic Stitching of Teravoxel-sized Microscopy Images", (2012) BMC Bioinformatics, 13 (1), art. no. 316. -* -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -#include -#include "TPAlgoMST.h" -#include "S_config.h" -#include "volumemanager.config.h" -#include "vmStackedVolume.h" -#include "vmVirtualStack.h" -#include "Displacement.h" - -using namespace volumemanager; -using namespace iomanager; - -//triplet data type definition -typedef struct -{ - float V; - float H; - float D; -}triplet; - -TPAlgoMST::TPAlgoMST(VirtualVolume * _volume) : TPAlgo(S_FATPM_SP_TREE, _volume) -{ - #if S_VERBOSE>4 - printf("........in TPAlgoMST::TPAlgoMST(VirtualVolume * _volume)"); - #endif -} - -/************************************************************************************************************* -* Finds the optimal tile placement on the object member via Minimum Spanning Tree. -* Stacks matrix is considered as a graph where displacements are edges a nd stacks are nodes. The inverse of -* displacements reliability factors are edge weights, so that a totally unreliable displacement has a weight -* 1/0.0 = +inf and a totally reliable displacement has a weight 1/1.0 = 1. Thus, weights will be in [1, +inf]. -* After computing the MST, the absolute tile positions are obtained from a stitchable source stack by means of -* navigating the MST and using the selected displacements. -* PROs: very general method; it ignores bad displacements since they have +inf weight. -* CONs: the best path between two adjacent stacks can pass through many stacks even if the rejected displacem- -* ent is quite reliable, with a very little reliability gain. This implies possible bad absolute posi- -* tions estimations when the path is too long. -**************************************************************************************************************/ -void TPAlgoMST::execute() throw (iom::exception) -{ - #if S_VERBOSE > 2 - printf("....in TPAlgoMST::execute()"); - #endif - - float ***D; //distances matrix for VHD directions - std::pair **predecessors; //predecessor matrix for VHD directions - int src_row=0, src_col=0; //source vertex - - //0) fixing the source as the stitchable VirtualStack nearest to the top-left corner - float min_distance = std::numeric_limits::infinity(); - for(int row=0; rowgetN_ROWS(); row++) - for(int col=0; colgetN_COLS(); col++) - if(volume->getSTACKS()[row][col]->isStitchable() && sqrt((float)(row*row+col*col)) < min_distance ) - { - src_row = row; - src_col = col; - min_distance = sqrt((float)(row*row+col*col)); - } - #if S_VERBOSE > 4 - printf("....in TPAlgoMST::execute(): SOURCE is [%d,%d]\n",src_row,src_col); - #endif - - //1) initializing distance and predecessor matrix - D = new float **[volume->getN_ROWS()]; - predecessors = new std::pair *[volume->getN_ROWS()]; - for(int row=0; rowgetN_ROWS(); row++) - { - D[row] = new float*[volume->getN_COLS()]; - predecessors[row] = new std::pair[volume->getN_COLS()]; - for(int col=0; colgetN_COLS(); col++) - { - D[row][col] = new float[3]; - predecessors[row][col].first = new int[3]; - predecessors[row][col].second = new int[3]; - for(int k=0; k<3; k++) - { - D[row][col][k] = std::numeric_limits::infinity(); - predecessors[row][col].first[k] = predecessors[row][col].second[k] = -1; - } - } - } - D[src_row][src_col][0] = D[src_row][src_col][1] = D[src_row][src_col][2] = 0.0F; - - //2) processing edges in order to obtain distance matrix - for(int vertices=1; vertices <= volume->getN_ROWS()*volume->getN_COLS(); vertices++) - for(int E_row = 0; E_rowgetN_ROWS(); E_row++) - for(int E_col = 0; E_colgetN_COLS(); E_col++) - for(int k=0; k<3; k++) - { - if(E_row != volume->getN_ROWS() -1 ) //NORTH-SOUTH displacements - { - float weight = SAFE_DIVIDE(1, volume->getSTACKS()[E_row ][E_col]->getSOUTH()[0]->getReliability(direction(k)), S_UNRELIABLE_WEIGHT); - if(D[E_row][E_col][k] + weight < D[E_row+1][E_col][k]) - { - D[E_row+1][E_col][k] = D[E_row][E_col][k] + weight; - predecessors[E_row+1][E_col].first[k] = E_row; - predecessors[E_row+1][E_col].second[k] = E_col; - } - if(D[E_row+1][E_col][k] + weight < D[E_row][E_col][k]) - { - D[E_row][E_col][k] = D[E_row+1][E_col][k] + weight; - predecessors[E_row][E_col].first[k] = E_row+1; - predecessors[E_row][E_col].second[k]= E_col; - } - } - if(E_col != volume->getN_COLS() -1 ) //EAST-WEST displacements - { - float weight = SAFE_DIVIDE(1, volume->getSTACKS()[E_row ][E_col]->getEAST()[0]->getReliability(direction(k)), S_UNRELIABLE_WEIGHT); - if(D[E_row][E_col][k] + weight < D[E_row][E_col+1][k]) - { - D[E_row][E_col+1][k] = D[E_row][E_col][k] + weight; - predecessors[E_row][E_col+1].first[k] = E_row; - predecessors[E_row][E_col+1].second[k]= E_col; - } - if(D[E_row][E_col+1][k] + weight < D[E_row][E_col][k]) - { - D[E_row][E_col][k] = D[E_row][E_col+1][k] + weight; - predecessors[E_row][E_col].first[k] = E_row; - predecessors[E_row][E_col].second[k] = E_col+1; - } - } - } - - #if S_VERBOSE > 4 - for(int k=0; k<3; k++) - { - printf("\n\n....in TPAlgoMST::execute(): %d DIRECTION:\n", k); - printf("\n\t"); - for(int col=0; col < volume->getN_COLS(); col++) - printf("[%d]\t\t", col); - printf("\n\n\n"); - for(int row = 0; row < volume->getN_ROWS(); row++) - { - printf("[%d]\t",row); - for(int col= 0; col < volume->getN_COLS(); col++) - printf("(%d,%d)\t", predecessors[row][col].first[k], predecessors[row][col].second[k]); - printf("\n\n\n"); - } - printf("\n"); - printf("\n\t"); - for(int col=0; col < volume->getN_COLS(); col++) - printf("[%d]\t\t", col); - printf("\n\n\n"); - for(int row = 0; row < volume->getN_ROWS(); row++) - { - printf("[%d]\t",row); - for(int col= 0; col < volume->getN_COLS(); col++) - printf("%8.3f\t", D[row][col][k]); - printf("\n\n\n"); - } - printf("\n"); - } - #endif - - //3) resetting to 0 all stacks absolute coordinates - for(int row = 0; rowgetN_ROWS(); row++) - for(int col = 0; colgetN_COLS(); col++) - { - volume->getSTACKS()[row][col]->setABS_V(0); - volume->getSTACKS()[row][col]->setABS_H(0); - volume->getSTACKS()[row][col]->setABS_D(0); - } - - //4) assigning absolute coordinates using predecessors matrix - for(int row = 0; rowgetN_ROWS(); row++) - { - for(int col = 0; colgetN_COLS(); col++) - { - if(!(row == src_row && col == src_col)) - { - for(int k=0; k<3; k++) - { - VirtualStack *source, *dest, *v, *u; - source = volume->getSTACKS()[src_row][src_col]; - dest = volume->getSTACKS()[row][col]; - v = dest; - - #if S_VERBOSE > 4 - printf("S[%d,%d] [%d]_path:\n", k, row, col); - #endif - while (v != source) - { - int u_row, u_col; - u_row = predecessors[v->getROW_INDEX()][v->getCOL_INDEX()].first[k]; - if(u_row>= volume->getN_ROWS() || u_row < 0) - throw iom::exception("...in TPAlgoMST::execute(): error in the predecessor matrix"); - u_col = (int) predecessors[v->getROW_INDEX()][v->getCOL_INDEX()].second[k]; - if(u_col>= volume->getN_COLS() || u_col < 0) - throw iom::exception("...in TPAlgoMST::execute(): error in the predecessor matrix"); - u = volume->getSTACKS()[u_row][u_col ]; - - #if S_VERBOSE > 4 - printf("\t[%d,%d] (ABS_[%d] = %d %+d)\n",u->getROW_INDEX(), u->getCOL_INDEX(), k, dest->getABS(k), u->getDisplacement(v)->getDisplacement(direction(k))); - #endif - dest->setABS(dest->getABS(k) + u->getDisplacement(v)->getDisplacement(direction(k)), k); - v = u; - - if(dest->isStitchable() && !(v->isStitchable())) - printf("\nWARNING! in TPAlgoMST::execute(): direction %d: VirtualStack [%d,%d] is passing through VirtualStack [%d,%d], that is NOT STITCHABLE\n", k, row, col, v->getROW_INDEX(), v->getCOL_INDEX()); - } - #if S_VERBOSE > 4 - printf("\n"); - #endif - } - #if S_VERBOSE > 4 - system("PAUSE"); - #endif - } - } - } - - //5) translating stacks absolute coordinates by choosing VirtualStack[0][0] as the new source - int trasl_X = volume->getSTACKS()[0][0]->getABS_V(); - int trasl_Y = volume->getSTACKS()[0][0]->getABS_H(); - int trasl_Z = volume->getSTACKS()[0][0]->getABS_D(); - for(int row = 0; rowgetN_ROWS(); row++) - { - for(int V_col = 0; V_colgetN_COLS(); V_col++) - { - volume->getSTACKS()[row][V_col]->setABS_V(volume->getSTACKS()[row][V_col]->getABS_V()-trasl_X); - volume->getSTACKS()[row][V_col]->setABS_H(volume->getSTACKS()[row][V_col]->getABS_H()-trasl_Y); - volume->getSTACKS()[row][V_col]->setABS_D(volume->getSTACKS()[row][V_col]->getABS_D()-trasl_Z); - } - } - - - //deallocating distance matrix and predecessor matrix - for(int row=0; rowgetN_ROWS(); row++) - { - for(int col=0; colgetN_COLS(); col++) - { - delete[] D[row][col]; - delete[] predecessors[row][col].first; - delete[] predecessors[row][col].second; - } - delete[] D[row]; - delete[] predecessors[row]; - } - delete[] D; - delete[] predecessors; -} diff --git a/v3d_main/terafly/src/core/stitcher/TPAlgoMST.h b/v3d_main/terafly/src/core/stitcher/TPAlgoMST.h deleted file mode 100644 index 25f595df31..0000000000 --- a/v3d_main/terafly/src/core/stitcher/TPAlgoMST.h +++ /dev/null @@ -1,64 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* -* Bria, A., Iannello, G., "TeraStitcher - A Tool for Fast 3D Automatic Stitching of Teravoxel-sized Microscopy Images", (2012) BMC Bioinformatics, 13 (1), art. no. 316. -* -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -#ifndef _TILE_PLACEMENT_ALGORITHM_MINIMUM_SPANNING_TREE_H -#define _TILE_PLACEMENT_ALGORITHM_MINIMUM_SPANNING_TREE_H - -#include "TPAlgo.h" - -class TPAlgoMST : public TPAlgo -{ - private: - - TPAlgoMST(void){}; //default constructor is inhibited - - protected: - - //int TYPE; //INHERITED from TPAlgo - //StackedVolume* volume; //INHERITED from TPAlgo - - public: - - TPAlgoMST(volumemanager::VirtualVolume * _volume); - ~TPAlgoMST(void){}; - - /************************************************************************************************************* - * Finds the optimal tile placement on the object member via Minimum Spanning Tree. - * Stacks matrix is considered as a graph where displacements are edges a nd stacks are nodes. The inverse of - * displacements reliability factors are edge weights, so that a totally unreliable displacement has a weight - * 1/0.0 = +inf and a totally reliable displacement has a weight 1/1.0 = 1. Thus, weights will be in [1, +inf]. - * After computing the MST, the absolute tile positions are obtained from a stitchable source stack by means of - * navigating the MST and using the selected displacements. - * PROs: very general method; it ignores bad displacements since they have +inf weight. - * CONs: the best path between two adjacent stacks can pass through many stacks even if the rejected displacem- - * ent is quite reliable, with a very little reliability gain. This implies possible bad absolute posi- - * tions estimations when the path is too long. - **************************************************************************************************************/ - void execute() throw (iom::exception); -}; - -#endif /* _TILE_PLACEMENT_ALGORITHM_MINIMUM_SPANNING_TREE_H */ diff --git a/v3d_main/terafly/src/core/stitcher/resumer.cpp b/v3d_main/terafly/src/core/stitcher/resumer.cpp deleted file mode 100644 index ff2f4637a5..0000000000 --- a/v3d_main/terafly/src/core/stitcher/resumer.cpp +++ /dev/null @@ -1,209 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -* 2014-10-29 Giulio. @ADDED fflush after writes -*/ - -#include "resumer.h" - -#ifdef _WIN32 -#include "dirent_win.h" -#else -#include -#endif - -#include -#include - -#define RESUMER_STATUS_FILE_NAME "resume_status.bin" -#define RECORD_LENGTH(resolutions_size) ( \ - sizeof(int) + \ - sizeof(int)*resolutions_size + \ - sizeof(int)*resolutions_size + \ - sizeof(int)*resolutions_size + \ - sizeof(sint64) + \ - sizeof(sint64) \ -) - -using namespace std; -using namespace iim; - - -bool initResumer ( const char *out_fmt, const char *output_path, int resolutions_size, bool* resolutions, - int block_height, int block_width, int block_depth, int method, - const char* saved_img_format, int saved_img_depth, FILE *&fhandle ) throw (IOException) -{ - size_t str_len; - char resumer_filepath[STATIC_STRINGS_SIZE]; - char err_msg[STATIC_STRINGS_SIZE]; - - sprintf(resumer_filepath, "%s/%s", output_path, RESUMER_STATUS_FILE_NAME); - if ( iim::isFile(resumer_filepath) ) { - if ( (fhandle = fopen(resumer_filepath,"rb")) == 0 ) { - sprintf(err_msg, "in initResumer: file %s cannot be opened for reading",output_path); - throw IOException(err_msg); - } - else { - char _out_fmt[STATIC_STRINGS_SIZE]; - char _output_path[STATIC_STRINGS_SIZE]; - int _resolutions_size; - bool _resolutions[TMITREE_MAX_HEIGHT]; - int _block_height; - int _block_width; - int _block_depth; - int _method; - char _saved_img_format[STATIC_STRINGS_SIZE]; - int _saved_img_depth; - int dummy; - - rewind(fhandle); - dummy = fread(&str_len,sizeof(size_t),1,fhandle); - dummy = fread(_out_fmt,sizeof(char),str_len,fhandle); - if ( strcmp(out_fmt,_out_fmt) ) { - fclose(fhandle); - sprintf(err_msg, "in initResumer: saved format of output image (%s) differ from requested format (%s)", - _out_fmt,out_fmt); - throw IOException(err_msg); - } - - dummy = fread(&str_len,sizeof(size_t),1,fhandle); - dummy = fread(_output_path,sizeof(char),str_len,fhandle); - dummy = fread(&_resolutions_size,sizeof(int),1,fhandle); - dummy = fread(&_resolutions,sizeof(bool),_resolutions_size,fhandle); - dummy = fread(&_block_height,sizeof(int),1,fhandle); - dummy = fread(&_block_width,sizeof(int),1,fhandle); - dummy = fread(&_block_depth,sizeof(int),1,fhandle); - dummy = fread(&_method,sizeof(int),1,fhandle); - dummy = fread(&str_len,sizeof(size_t),1,fhandle); - dummy = fread(_saved_img_format,sizeof(char),str_len,fhandle); - dummy = fread(&_saved_img_depth,sizeof(int),1,fhandle); - - if ( strcmp(output_path,_output_path) || - block_height!=_block_height || block_width!=_block_width || block_depth!=_block_depth || - strcmp(saved_img_format,_saved_img_format) || saved_img_depth!=_saved_img_depth ) { - fclose(fhandle); - sprintf(err_msg, "in initResumer: saved parameters differ from current parameters (%s vs. %s)", - _out_fmt,out_fmt); - throw IOException(err_msg); - } - - bool res_err = true; - int i; - if ( resolutions_size==_resolutions_size ) { - for ( i=0, res_err=false; i - -bool initResumer ( const char *out_fmt, const char *output_path, int resolution_size,bool* resolutions, - int block_height, int block_width, int block_depth, int method, - const char* saved_img_format, int saved_img_depth, FILE *&fhandle ) throw (iim::IOException); - -void readResumerState ( FILE *&fhandle, const char *output_path, int &resolution_size, int *stack_block, int *slice_start, int *slice_end, - iim::sint64 &z, iim::sint64 &z_parts ) throw (iim::IOException); - -void saveResumerState ( FILE *fhandle, int resolution_size, int *stack_block, int *slice_start, int *slice_end, - iim::sint64 z, iim::sint64 z_parts ) throw (iim::IOException); - -void closeResumer ( FILE *fhandle, const char *output_path = 0 ) throw (iim::IOException); - -#endif - diff --git a/v3d_main/terafly/src/core/tinyxml/CMakeLists.txt b/v3d_main/terafly/src/core/tinyxml/CMakeLists.txt deleted file mode 100644 index 30f3fe35c5..0000000000 --- a/v3d_main/terafly/src/core/tinyxml/CMakeLists.txt +++ /dev/null @@ -1,6 +0,0 @@ -# CmakeLists.txt in TinyXML dir - -# Adds a library called tinyxml (tinyxml.a under Linux, tinyxml.lib under Windows) from the all .h and .cpp files -file(GLOB tinyxml_headers *.h) -file(GLOB tinyxml_sources *.cpp) -add_library(tinyxml STATIC ${tinyxml_headers} ${tinyxml_sources}) \ No newline at end of file diff --git a/v3d_main/terafly/src/core/tinyxml/tinystr.cpp b/v3d_main/terafly/src/core/tinyxml/tinystr.cpp deleted file mode 100644 index 6f8a28ce04..0000000000 --- a/v3d_main/terafly/src/core/tinyxml/tinystr.cpp +++ /dev/null @@ -1,116 +0,0 @@ -/* -www.sourceforge.net/projects/tinyxml -Original file by Yves Berquin. - -This software is provided 'as-is', without any express or implied -warranty. In no event will the authors be held liable for any -damages arising from the use of this software. - -Permission is granted to anyone to use this software for any -purpose, including commercial applications, and to alter it and -redistribute it freely, subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must -not claim that you wrote the original software. If you use this -software in a product, an acknowledgment in the product documentation -would be appreciated but is not required. - -2. Altered source versions must be plainly marked as such, and -must not be misrepresented as being the original software. - -3. This notice may not be removed or altered from any source -distribution. -*/ - -/* - * THIS FILE WAS ALTERED BY Tyge Løvset, 7. April 2005. - */ - - -#ifndef TIXML_USE_STL - -#include "tinystr.h" - -// Error value for find primitive -const TiXmlString::size_type TiXmlString::npos = static_cast< TiXmlString::size_type >(-1); - - -// Null rep. -TiXmlString::Rep TiXmlString::nullrep_ = { 0, 0, { '\0' } }; - - -void TiXmlString::reserve (size_type cap) -{ - if (cap > capacity()) - { - TiXmlString tmp; - tmp.init(length(), cap); - memcpy(tmp.start(), data(), length()); - swap(tmp); - } -} - - -TiXmlString& TiXmlString::assign(const char* str, size_type len) -{ - size_type cap = capacity(); - if (len > cap || cap > 3*(len + 8)) - { - TiXmlString tmp; - tmp.init(len); - memcpy(tmp.start(), str, len); - swap(tmp); - } - else - { - memmove(start(), str, len); - set_size(len); - } - return *this; -} - - -TiXmlString& TiXmlString::append(const char* str, size_type len) -{ - size_type newsize = length() + len; - if (newsize > capacity()) - { - reserve (newsize + capacity()); - } - memmove(finish(), str, len); - set_size(newsize); - return *this; -} - - -TiXmlString operator + (const TiXmlString & a, const TiXmlString & b) -{ - TiXmlString tmp; - tmp.reserve(a.length() + b.length()); - tmp += a; - tmp += b; - return tmp; -} - -TiXmlString operator + (const TiXmlString & a, const char* b) -{ - TiXmlString tmp; - TiXmlString::size_type b_len = static_cast( strlen(b) ); - tmp.reserve(a.length() + b_len); - tmp += a; - tmp.append(b, b_len); - return tmp; -} - -TiXmlString operator + (const char* a, const TiXmlString & b) -{ - TiXmlString tmp; - TiXmlString::size_type a_len = static_cast( strlen(a) ); - tmp.reserve(a_len + b.length()); - tmp.append(a, a_len); - tmp += b; - return tmp; -} - - -#endif // TIXML_USE_STL diff --git a/v3d_main/terafly/src/core/tinyxml/tinystr.h b/v3d_main/terafly/src/core/tinyxml/tinystr.h deleted file mode 100644 index 74b6b7e815..0000000000 --- a/v3d_main/terafly/src/core/tinyxml/tinystr.h +++ /dev/null @@ -1,319 +0,0 @@ -/* -www.sourceforge.net/projects/tinyxml -Original file by Yves Berquin. - -This software is provided 'as-is', without any express or implied -warranty. In no event will the authors be held liable for any -damages arising from the use of this software. - -Permission is granted to anyone to use this software for any -purpose, including commercial applications, and to alter it and -redistribute it freely, subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must -not claim that you wrote the original software. If you use this -software in a product, an acknowledgment in the product documentation -would be appreciated but is not required. - -2. Altered source versions must be plainly marked as such, and -must not be misrepresented as being the original software. - -3. This notice may not be removed or altered from any source -distribution. -*/ - -/* - * THIS FILE WAS ALTERED BY Tyge Lovset, 7. April 2005. - * - * - completely rewritten. compact, clean, and fast implementation. - * - sizeof(TiXmlString) = pointer size (4 bytes on 32-bit systems) - * - fixed reserve() to work as per specification. - * - fixed buggy compares operator==(), operator<(), and operator>() - * - fixed operator+=() to take a const ref argument, following spec. - * - added "copy" constructor with length, and most compare operators. - * - added swap(), clear(), size(), capacity(), operator+(). - */ - -#ifndef TIXML_USE_STL - -#ifndef TIXML_STRING_INCLUDED -#define TIXML_STRING_INCLUDED - -#include -#include - -/* The support for explicit isn't that universal, and it isn't really - required - it is used to check that the TiXmlString class isn't incorrectly - used. Be nice to old compilers and macro it here: -*/ -#if defined(_MSC_VER) && (_MSC_VER >= 1200 ) - // Microsoft visual studio, version 6 and higher. - #define TIXML_EXPLICIT explicit -#elif defined(__GNUC__) && (__GNUC__ >= 3 ) - // GCC version 3 and higher.s - #define TIXML_EXPLICIT explicit -#else - #define TIXML_EXPLICIT -#endif - - -/* - TiXmlString is an emulation of a subset of the std::string template. - Its purpose is to allow compiling TinyXML on compilers with no or poor STL support. - Only the member functions relevant to the TinyXML project have been implemented. - The buffer allocation is made by a simplistic power of 2 like mechanism : if we increase - a string and there's no more room, we allocate a buffer twice as big as we need. -*/ -class TiXmlString -{ - public : - // The size type used - typedef size_t size_type; - - // Error value for find primitive - static const size_type npos; // = -1; - - - // TiXmlString empty constructor - TiXmlString () : rep_(&nullrep_) - { - } - - // TiXmlString copy constructor - TiXmlString ( const TiXmlString & copy) : rep_(0) - { - init(copy.length()); - memcpy(start(), copy.data(), length()); - } - - // TiXmlString constructor, based on a string - TIXML_EXPLICIT TiXmlString ( const char * copy) : rep_(0) - { - init( static_cast( strlen(copy) )); - memcpy(start(), copy, length()); - } - - // TiXmlString constructor, based on a string - TIXML_EXPLICIT TiXmlString ( const char * str, size_type len) : rep_(0) - { - init(len); - memcpy(start(), str, len); - } - - // TiXmlString destructor - ~TiXmlString () - { - quit(); - } - - // = operator - TiXmlString& operator = (const char * copy) - { - return assign( copy, (size_type)strlen(copy)); - } - - // = operator - TiXmlString& operator = (const TiXmlString & copy) - { - return assign(copy.start(), copy.length()); - } - - - // += operator. Maps to append - TiXmlString& operator += (const char * suffix) - { - return append(suffix, static_cast( strlen(suffix) )); - } - - // += operator. Maps to append - TiXmlString& operator += (char single) - { - return append(&single, 1); - } - - // += operator. Maps to append - TiXmlString& operator += (const TiXmlString & suffix) - { - return append(suffix.data(), suffix.length()); - } - - - // Convert a TiXmlString into a null-terminated char * - const char * c_str () const { return rep_->str; } - - // Convert a TiXmlString into a char * (need not be null terminated). - const char * data () const { return rep_->str; } - - // Return the length of a TiXmlString - size_type length () const { return rep_->size; } - - // Alias for length() - size_type size () const { return rep_->size; } - - // Checks if a TiXmlString is empty - bool empty () const { return rep_->size == 0; } - - // Return capacity of string - size_type capacity () const { return rep_->capacity; } - - - // single char extraction - const char& at (size_type index) const - { - assert( index < length() ); - return rep_->str[ index ]; - } - - // [] operator - char& operator [] (size_type index) const - { - assert( index < length() ); - return rep_->str[ index ]; - } - - // find a char in a string. Return TiXmlString::npos if not found - size_type find (char lookup) const - { - return find(lookup, 0); - } - - // find a char in a string from an offset. Return TiXmlString::npos if not found - size_type find (char tofind, size_type offset) const - { - if (offset >= length()) return npos; - - for (const char* p = c_str() + offset; *p != '\0'; ++p) - { - if (*p == tofind) return static_cast< size_type >( p - c_str() ); - } - return npos; - } - - void clear () - { - //Lee: - //The original was just too strange, though correct: - // TiXmlString().swap(*this); - //Instead use the quit & re-init: - quit(); - init(0,0); - } - - /* Function to reserve a big amount of data when we know we'll need it. Be aware that this - function DOES NOT clear the content of the TiXmlString if any exists. - */ - void reserve (size_type cap); - - TiXmlString& assign (const char* str, size_type len); - - TiXmlString& append (const char* str, size_type len); - - void swap (TiXmlString& other) - { - Rep* r = rep_; - rep_ = other.rep_; - other.rep_ = r; - } - - private: - - void init(size_type sz) { init(sz, sz); } - void set_size(size_type sz) { rep_->str[ rep_->size = sz ] = '\0'; } - char* start() const { return rep_->str; } - char* finish() const { return rep_->str + rep_->size; } - - struct Rep - { - size_type size, capacity; - char str[1]; - }; - - void init(size_type sz, size_type cap) - { - if (cap) - { - // Lee: the original form: - // rep_ = static_cast(operator new(sizeof(Rep) + cap)); - // doesn't work in some cases of new being overloaded. Switching - // to the normal allocation, although use an 'int' for systems - // that are overly picky about structure alignment. - const size_type bytesNeeded = sizeof(Rep) + cap; - const size_type intsNeeded = ( bytesNeeded + sizeof(int) - 1 ) / sizeof( int ); - rep_ = reinterpret_cast( new int[ intsNeeded ] ); - - rep_->str[ rep_->size = sz ] = '\0'; - rep_->capacity = cap; - } - else - { - rep_ = &nullrep_; - } - } - - void quit() - { - if (rep_ != &nullrep_) - { - // The rep_ is really an array of ints. (see the allocator, above). - // Cast it back before delete, so the compiler won't incorrectly call destructors. - delete [] ( reinterpret_cast( rep_ ) ); - } - } - - Rep * rep_; - static Rep nullrep_; - -} ; - - -inline bool operator == (const TiXmlString & a, const TiXmlString & b) -{ - return ( a.length() == b.length() ) // optimization on some platforms - && ( strcmp(a.c_str(), b.c_str()) == 0 ); // actual compare -} -inline bool operator < (const TiXmlString & a, const TiXmlString & b) -{ - return strcmp(a.c_str(), b.c_str()) < 0; -} - -inline bool operator != (const TiXmlString & a, const TiXmlString & b) { return !(a == b); } -inline bool operator > (const TiXmlString & a, const TiXmlString & b) { return b < a; } -inline bool operator <= (const TiXmlString & a, const TiXmlString & b) { return !(b < a); } -inline bool operator >= (const TiXmlString & a, const TiXmlString & b) { return !(a < b); } - -inline bool operator == (const TiXmlString & a, const char* b) { return strcmp(a.c_str(), b) == 0; } -inline bool operator == (const char* a, const TiXmlString & b) { return b == a; } -inline bool operator != (const TiXmlString & a, const char* b) { return !(a == b); } -inline bool operator != (const char* a, const TiXmlString & b) { return !(b == a); } - -TiXmlString operator + (const TiXmlString & a, const TiXmlString & b); -TiXmlString operator + (const TiXmlString & a, const char* b); -TiXmlString operator + (const char* a, const TiXmlString & b); - - -/* - TiXmlOutStream is an emulation of std::ostream. It is based on TiXmlString. - Only the operators that we need for TinyXML have been developped. -*/ -class TiXmlOutStream : public TiXmlString -{ -public : - - // TiXmlOutStream << operator. - TiXmlOutStream & operator << (const TiXmlString & in) - { - *this += in; - return *this; - } - - // TiXmlOutStream << operator. - TiXmlOutStream & operator << (const char * in) - { - *this += in; - return *this; - } - -} ; - -#endif // TIXML_STRING_INCLUDED -#endif // TIXML_USE_STL diff --git a/v3d_main/terafly/src/core/tinyxml/tinyxml.cpp b/v3d_main/terafly/src/core/tinyxml/tinyxml.cpp deleted file mode 100644 index 9214ee8542..0000000000 --- a/v3d_main/terafly/src/core/tinyxml/tinyxml.cpp +++ /dev/null @@ -1,1839 +0,0 @@ -/* -www.sourceforge.net/projects/tinyxml -Original code (2.0 and earlier )copyright (c) 2000-2006 Lee Thomason (www.grinninglizard.com) - -This software is provided 'as-is', without any express or implied -warranty. In no event will the authors be held liable for any -damages arising from the use of this software. - -Permission is granted to anyone to use this software for any -purpose, including commercial applications, and to alter it and -redistribute it freely, subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must -not claim that you wrote the original software. If you use this -software in a product, an acknowledgment in the product documentation -would be appreciated but is not required. - -2. Altered source versions must be plainly marked as such, and -must not be misrepresented as being the original software. - -3. This notice may not be removed or altered from any source -distribution. -*/ - -#include - -#ifdef TIXML_USE_STL -#include -#include -#endif - -#include "tinyxml.h" - -FILE* TiXmlFOpen( const char* filename, const char* mode ); - -bool TiXmlBase::condenseWhiteSpace = true; - -// Microsoft compiler security -FILE* TiXmlFOpen( const char* filename, const char* mode ) -{ - #if defined(_MSC_VER) && (_MSC_VER >= 1400 ) - FILE* fp = 0; - errno_t err = fopen_s( &fp, filename, mode ); - if ( !err && fp ) - return fp; - return 0; - #else - return fopen( filename, mode ); - #endif -} - -void TiXmlBase::EncodeString( const TIXML_STRING& str, TIXML_STRING* outString ) -{ - int i=0; - - while( i<(int)str.length() ) - { - unsigned char c = (unsigned char) str[i]; - - if ( c == '&' - && i < ( (int)str.length() - 2 ) - && str[i+1] == '#' - && str[i+2] == 'x' ) - { - // Hexadecimal character reference. - // Pass through unchanged. - // © -- copyright symbol, for example. - // - // The -1 is a bug fix from Rob Laveaux. It keeps - // an overflow from happening if there is no ';'. - // There are actually 2 ways to exit this loop - - // while fails (error case) and break (semicolon found). - // However, there is no mechanism (currently) for - // this function to return an error. - while ( i<(int)str.length()-1 ) - { - outString->append( str.c_str() + i, 1 ); - ++i; - if ( str[i] == ';' ) - break; - } - } - else if ( c == '&' ) - { - outString->append( entity[0].str, entity[0].strLength ); - ++i; - } - else if ( c == '<' ) - { - outString->append( entity[1].str, entity[1].strLength ); - ++i; - } - else if ( c == '>' ) - { - outString->append( entity[2].str, entity[2].strLength ); - ++i; - } - else if ( c == '\"' ) - { - outString->append( entity[3].str, entity[3].strLength ); - ++i; - } - else if ( c == '\'' ) - { - outString->append( entity[4].str, entity[4].strLength ); - ++i; - } - else if ( c < 32 ) - { - // Easy pass at non-alpha/numeric/symbol - // Below 32 is symbolic. - char buf[ 32 ]; - - #if defined(TIXML_SNPRINTF) - TIXML_SNPRINTF( buf, sizeof(buf), "&#x%02X;", (unsigned) ( c & 0xff ) ); - #else - sprintf( buf, "&#x%02X;", (unsigned) ( c & 0xff ) ); - #endif - - //*ME: warning C4267: convert 'size_t' to 'int' - //*ME: Int-Cast to make compiler happy ... - outString->append( buf, (int)strlen( buf ) ); - ++i; - } - else - { - //char realc = (char) c; - //outString->append( &realc, 1 ); - *outString += (char) c; // somewhat more efficient function call. - ++i; - } - } -} - - -TiXmlNode::TiXmlNode( NodeType _type ) : TiXmlBase() -{ - parent = 0; - type = _type; - firstChild = 0; - lastChild = 0; - prev = 0; - next = 0; -} - - -TiXmlNode::~TiXmlNode() -{ - TiXmlNode* node = firstChild; - TiXmlNode* temp = 0; - - while ( node ) - { - temp = node; - node = node->next; - delete temp; - } -} - - -void TiXmlNode::CopyTo( TiXmlNode* target ) const -{ - target->SetValue (value.c_str() ); - target->userData = userData; - target->location = location; -} - - -void TiXmlNode::Clear() -{ - TiXmlNode* node = firstChild; - TiXmlNode* temp = 0; - - while ( node ) - { - temp = node; - node = node->next; - delete temp; - } - - firstChild = 0; - lastChild = 0; -} - - -TiXmlNode* TiXmlNode::LinkEndChild( TiXmlNode* node ) -{ - assert( node->parent == 0 || node->parent == this ); - assert( node->GetDocument() == 0 || node->GetDocument() == this->GetDocument() ); - - if ( node->Type() == TiXmlNode::TINYXML_DOCUMENT ) - { - delete node; - if ( GetDocument() ) GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN ); - return 0; - } - - node->parent = this; - - node->prev = lastChild; - node->next = 0; - - if ( lastChild ) - lastChild->next = node; - else - firstChild = node; // it was an empty list. - - lastChild = node; - return node; -} - - -TiXmlNode* TiXmlNode::InsertEndChild( const TiXmlNode& addThis ) -{ - if ( addThis.Type() == TiXmlNode::TINYXML_DOCUMENT ) - { - if ( GetDocument() ) GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN ); - return 0; - } - TiXmlNode* node = addThis.Clone(); - if ( !node ) - return 0; - - return LinkEndChild( node ); -} - - -TiXmlNode* TiXmlNode::InsertBeforeChild( TiXmlNode* beforeThis, const TiXmlNode& addThis ) -{ - if ( !beforeThis || beforeThis->parent != this ) { - return 0; - } - if ( addThis.Type() == TiXmlNode::TINYXML_DOCUMENT ) - { - if ( GetDocument() ) GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN ); - return 0; - } - - TiXmlNode* node = addThis.Clone(); - if ( !node ) - return 0; - node->parent = this; - - node->next = beforeThis; - node->prev = beforeThis->prev; - if ( beforeThis->prev ) - { - beforeThis->prev->next = node; - } - else - { - assert( firstChild == beforeThis ); - firstChild = node; - } - beforeThis->prev = node; - return node; -} - - -TiXmlNode* TiXmlNode::InsertAfterChild( TiXmlNode* afterThis, const TiXmlNode& addThis ) -{ - if ( !afterThis || afterThis->parent != this ) { - return 0; - } - if ( addThis.Type() == TiXmlNode::TINYXML_DOCUMENT ) - { - if ( GetDocument() ) GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN ); - return 0; - } - - TiXmlNode* node = addThis.Clone(); - if ( !node ) - return 0; - node->parent = this; - - node->prev = afterThis; - node->next = afterThis->next; - if ( afterThis->next ) - { - afterThis->next->prev = node; - } - else - { - assert( lastChild == afterThis ); - lastChild = node; - } - afterThis->next = node; - return node; -} - - -TiXmlNode* TiXmlNode::ReplaceChild( TiXmlNode* replaceThis, const TiXmlNode& withThis ) -{ - if ( !replaceThis ) - return 0; - - if ( replaceThis->parent != this ) - return 0; - - if ( withThis.ToDocument() ) { - // A document can never be a child. Thanks to Noam. - TiXmlDocument* document = GetDocument(); - if ( document ) - document->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN ); - return 0; - } - - TiXmlNode* node = withThis.Clone(); - if ( !node ) - return 0; - - node->next = replaceThis->next; - node->prev = replaceThis->prev; - - if ( replaceThis->next ) - replaceThis->next->prev = node; - else - lastChild = node; - - if ( replaceThis->prev ) - replaceThis->prev->next = node; - else - firstChild = node; - - delete replaceThis; - node->parent = this; - return node; -} - - -bool TiXmlNode::RemoveChild( TiXmlNode* removeThis ) -{ - if ( !removeThis ) { - return false; - } - - if ( removeThis->parent != this ) - { - assert( 0 ); - return false; - } - - if ( removeThis->next ) - removeThis->next->prev = removeThis->prev; - else - lastChild = removeThis->prev; - - if ( removeThis->prev ) - removeThis->prev->next = removeThis->next; - else - firstChild = removeThis->next; - - delete removeThis; - return true; -} - -const TiXmlNode* TiXmlNode::FirstChild( const char * _value ) const -{ - const TiXmlNode* node; - for ( node = firstChild; node; node = node->next ) - { - if ( strcmp( node->Value(), _value ) == 0 ) - return node; - } - return 0; -} - - -const TiXmlNode* TiXmlNode::LastChild( const char * _value ) const -{ - const TiXmlNode* node; - for ( node = lastChild; node; node = node->prev ) - { - if ( strcmp( node->Value(), _value ) == 0 ) - return node; - } - return 0; -} - - -const TiXmlNode* TiXmlNode::IterateChildren( const TiXmlNode* previous ) const -{ - if ( !previous ) - { - return FirstChild(); - } - else - { - assert( previous->parent == this ); - return previous->NextSibling(); - } -} - - -const TiXmlNode* TiXmlNode::IterateChildren( const char * val, const TiXmlNode* previous ) const -{ - if ( !previous ) - { - return FirstChild( val ); - } - else - { - assert( previous->parent == this ); - return previous->NextSibling( val ); - } -} - - -const TiXmlNode* TiXmlNode::NextSibling( const char * _value ) const -{ - const TiXmlNode* node; - for ( node = next; node; node = node->next ) - { - if ( strcmp( node->Value(), _value ) == 0 ) - return node; - } - return 0; -} - - -const TiXmlNode* TiXmlNode::PreviousSibling( const char * _value ) const -{ - const TiXmlNode* node; - for ( node = prev; node; node = node->prev ) - { - if ( strcmp( node->Value(), _value ) == 0 ) - return node; - } - return 0; -} - - -void TiXmlElement::RemoveAttribute( const char * name ) -{ - #ifdef TIXML_USE_STL - TIXML_STRING str( name ); - TiXmlAttribute* node = attributeSet.Find( str ); - #else - TiXmlAttribute* node = attributeSet.Find( name ); - #endif - if ( node ) - { - attributeSet.Remove( node ); - delete node; - } -} - -const TiXmlElement* TiXmlNode::FirstChildElement() const -{ - const TiXmlNode* node; - - for ( node = FirstChild(); - node; - node = node->NextSibling() ) - { - if ( node->ToElement() ) - return node->ToElement(); - } - return 0; -} - - -const TiXmlElement* TiXmlNode::FirstChildElement( const char * _value ) const -{ - const TiXmlNode* node; - - for ( node = FirstChild( _value ); - node; - node = node->NextSibling( _value ) ) - { - if ( node->ToElement() ) - return node->ToElement(); - } - return 0; -} - - -const TiXmlElement* TiXmlNode::NextSiblingElement() const -{ - const TiXmlNode* node; - - for ( node = NextSibling(); - node; - node = node->NextSibling() ) - { - if ( node->ToElement() ) - return node->ToElement(); - } - return 0; -} - - -const TiXmlElement* TiXmlNode::NextSiblingElement( const char * _value ) const -{ - const TiXmlNode* node; - - for ( node = NextSibling( _value ); - node; - node = node->NextSibling( _value ) ) - { - if ( node->ToElement() ) - return node->ToElement(); - } - return 0; -} - - -const TiXmlDocument* TiXmlNode::GetDocument() const -{ - const TiXmlNode* node; - - for( node = this; node; node = node->parent ) - { - if ( node->ToDocument() ) - return node->ToDocument(); - } - return 0; -} - - -TiXmlElement::TiXmlElement (const char * _value) - : TiXmlNode( TiXmlNode::TINYXML_ELEMENT ) -{ - firstChild = lastChild = 0; - value = _value; -} - - -#ifdef TIXML_USE_STL -TiXmlElement::TiXmlElement( const std::string& _value ) - : TiXmlNode( TiXmlNode::TINYXML_ELEMENT ) -{ - firstChild = lastChild = 0; - value = _value; -} -#endif - - -TiXmlElement::TiXmlElement( const TiXmlElement& copy) - : TiXmlNode( TiXmlNode::TINYXML_ELEMENT ) -{ - firstChild = lastChild = 0; - copy.CopyTo( this ); -} - - -void TiXmlElement::operator=( const TiXmlElement& base ) -{ - ClearThis(); - base.CopyTo( this ); -} - - -TiXmlElement::~TiXmlElement() -{ - ClearThis(); -} - - -void TiXmlElement::ClearThis() -{ - Clear(); - while( attributeSet.First() ) - { - TiXmlAttribute* node = attributeSet.First(); - attributeSet.Remove( node ); - delete node; - } -} - - -const char* TiXmlElement::Attribute( const char* name ) const -{ - const TiXmlAttribute* node = attributeSet.Find( name ); - if ( node ) - return node->Value(); - return 0; -} - - -#ifdef TIXML_USE_STL -const std::string* TiXmlElement::Attribute( const std::string& name ) const -{ - const TiXmlAttribute* attrib = attributeSet.Find( name ); - if ( attrib ) - return &attrib->ValueStr(); - return 0; -} -#endif - - -const char* TiXmlElement::Attribute( const char* name, int* i ) const -{ - const TiXmlAttribute* attrib = attributeSet.Find( name ); - const char* result = 0; - - if ( attrib ) { - result = attrib->Value(); - if ( i ) { - attrib->QueryIntValue( i ); - } - } - return result; -} - - -#ifdef TIXML_USE_STL -const std::string* TiXmlElement::Attribute( const std::string& name, int* i ) const -{ - const TiXmlAttribute* attrib = attributeSet.Find( name ); - const std::string* result = 0; - - if ( attrib ) { - result = &attrib->ValueStr(); - if ( i ) { - attrib->QueryIntValue( i ); - } - } - return result; -} -#endif - - -const char* TiXmlElement::Attribute( const char* name, double* d ) const -{ - const TiXmlAttribute* attrib = attributeSet.Find( name ); - const char* result = 0; - - if ( attrib ) { - result = attrib->Value(); - if ( d ) { - attrib->QueryDoubleValue( d ); - } - } - return result; -} - - -#ifdef TIXML_USE_STL -const std::string* TiXmlElement::Attribute( const std::string& name, double* d ) const -{ - const TiXmlAttribute* attrib = attributeSet.Find( name ); - const std::string* result = 0; - - if ( attrib ) { - result = &attrib->ValueStr(); - if ( d ) { - attrib->QueryDoubleValue( d ); - } - } - return result; -} -#endif - - -int TiXmlElement::QueryIntAttribute( const char* name, int* ival ) const -{ - const TiXmlAttribute* attrib = attributeSet.Find( name ); - if ( !attrib ) - return TIXML_NO_ATTRIBUTE; - return attrib->QueryIntValue( ival ); -} - - -#ifdef TIXML_USE_STL -int TiXmlElement::QueryIntAttribute( const std::string& name, int* ival ) const -{ - const TiXmlAttribute* attrib = attributeSet.Find( name ); - if ( !attrib ) - return TIXML_NO_ATTRIBUTE; - return attrib->QueryIntValue( ival ); -} -#endif - - -int TiXmlElement::QueryDoubleAttribute( const char* name, double* dval ) const -{ - const TiXmlAttribute* attrib = attributeSet.Find( name ); - if ( !attrib ) - return TIXML_NO_ATTRIBUTE; - return attrib->QueryDoubleValue( dval ); -} - - -#ifdef TIXML_USE_STL -int TiXmlElement::QueryDoubleAttribute( const std::string& name, double* dval ) const -{ - const TiXmlAttribute* attrib = attributeSet.Find( name ); - if ( !attrib ) - return TIXML_NO_ATTRIBUTE; - return attrib->QueryDoubleValue( dval ); -} -#endif - - -void TiXmlElement::SetAttribute( const char * name, int val ) -{ - TiXmlAttribute* attrib = attributeSet.FindOrCreate( name ); - if ( attrib ) { - attrib->SetIntValue( val ); - } -} - - -#ifdef TIXML_USE_STL -void TiXmlElement::SetAttribute( const std::string& name, int val ) -{ - TiXmlAttribute* attrib = attributeSet.FindOrCreate( name ); - if ( attrib ) { - attrib->SetIntValue( val ); - } -} -#endif - - -void TiXmlElement::SetDoubleAttribute( const char * name, double val ) -{ - TiXmlAttribute* attrib = attributeSet.FindOrCreate( name ); - if ( attrib ) { - attrib->SetDoubleValue( val ); - } -} - - -#ifdef TIXML_USE_STL -void TiXmlElement::SetDoubleAttribute( const std::string& name, double val ) -{ - TiXmlAttribute* attrib = attributeSet.FindOrCreate( name ); - if ( attrib ) { - attrib->SetDoubleValue( val ); - } -} -#endif - - -void TiXmlElement::SetAttribute( const char * cname, const char * cvalue ) -{ - TiXmlAttribute* attrib = attributeSet.FindOrCreate( cname ); - if ( attrib ) { - attrib->SetValue( cvalue ); - } -} - - -#ifdef TIXML_USE_STL -void TiXmlElement::SetAttribute( const std::string& _name, const std::string& _value ) -{ - TiXmlAttribute* attrib = attributeSet.FindOrCreate( _name ); - if ( attrib ) { - attrib->SetValue( _value ); - } -} -#endif - - -void TiXmlElement::Print( FILE* cfile, int depth ) const -{ - int i; - assert( cfile ); - for ( i=0; iNext() ) - { - fprintf( cfile, " " ); - attrib->Print( cfile, depth ); - } - - // There are 3 different formatting approaches: - // 1) An element without children is printed as a node - // 2) An element with only a text child is printed as text - // 3) An element with children is printed on multiple lines. - TiXmlNode* node; - if ( !firstChild ) - { - fprintf( cfile, " />" ); - } - else if ( firstChild == lastChild && firstChild->ToText() ) - { - fprintf( cfile, ">" ); - firstChild->Print( cfile, depth + 1 ); - fprintf( cfile, "", value.c_str() ); - } - else - { - fprintf( cfile, ">" ); - - for ( node = firstChild; node; node=node->NextSibling() ) - { - if ( !node->ToText() ) - { - fprintf( cfile, "\n" ); - } - node->Print( cfile, depth+1 ); - } - fprintf( cfile, "\n" ); - for( i=0; i", value.c_str() ); - } -} - - -void TiXmlElement::CopyTo( TiXmlElement* target ) const -{ - // superclass: - TiXmlNode::CopyTo( target ); - - // Element class: - // Clone the attributes, then clone the children. - const TiXmlAttribute* attribute = 0; - for( attribute = attributeSet.First(); - attribute; - attribute = attribute->Next() ) - { - target->SetAttribute( attribute->Name(), attribute->Value() ); - } - - TiXmlNode* node = 0; - for ( node = firstChild; node; node = node->NextSibling() ) - { - target->LinkEndChild( node->Clone() ); - } -} - -bool TiXmlElement::Accept( TiXmlVisitor* visitor ) const -{ - if ( visitor->VisitEnter( *this, attributeSet.First() ) ) - { - for ( const TiXmlNode* node=FirstChild(); node; node=node->NextSibling() ) - { - if ( !node->Accept( visitor ) ) - break; - } - } - return visitor->VisitExit( *this ); -} - - -TiXmlNode* TiXmlElement::Clone() const -{ - TiXmlElement* clone = new TiXmlElement( Value() ); - if ( !clone ) - return 0; - - CopyTo( clone ); - return clone; -} - - -const char* TiXmlElement::GetText() const -{ - const TiXmlNode* child = this->FirstChild(); - if ( child ) { - const TiXmlText* childText = child->ToText(); - if ( childText ) { - return childText->Value(); - } - } - return 0; -} - - -TiXmlDocument::TiXmlDocument() : TiXmlNode( TiXmlNode::TINYXML_DOCUMENT ) -{ - tabsize = 4; - useMicrosoftBOM = false; - ClearError(); -} - -TiXmlDocument::TiXmlDocument( const char * documentName ) : TiXmlNode( TiXmlNode::TINYXML_DOCUMENT ) -{ - tabsize = 4; - useMicrosoftBOM = false; - value = documentName; - ClearError(); -} - - -#ifdef TIXML_USE_STL -TiXmlDocument::TiXmlDocument( const std::string& documentName ) : TiXmlNode( TiXmlNode::TINYXML_DOCUMENT ) -{ - tabsize = 4; - useMicrosoftBOM = false; - value = documentName; - ClearError(); -} -#endif - - -TiXmlDocument::TiXmlDocument( const TiXmlDocument& copy ) : TiXmlNode( TiXmlNode::TINYXML_DOCUMENT ) -{ - copy.CopyTo( this ); -} - - -void TiXmlDocument::operator=( const TiXmlDocument& copy ) -{ - Clear(); - copy.CopyTo( this ); -} - - -bool TiXmlDocument::LoadFile( TiXmlEncoding encoding ) -{ - return LoadFile( Value(), encoding ); -} - - -bool TiXmlDocument::SaveFile() const -{ - return SaveFile( Value() ); -} - -bool TiXmlDocument::LoadFile( const char* _filename, TiXmlEncoding encoding ) -{ - TIXML_STRING filename( _filename ); - value = filename; - - // reading in binary mode so that tinyxml can normalize the EOL - FILE* file = TiXmlFOpen( value.c_str (), "rb" ); - - if ( file ) - { - bool result = LoadFile( file, encoding ); - fclose( file ); - return result; - } - else - { - SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN ); - return false; - } -} - -bool TiXmlDocument::LoadFile( FILE* file, TiXmlEncoding encoding ) -{ - if ( !file ) - { - SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN ); - return false; - } - - // Delete the existing data: - Clear(); - location.Clear(); - - // Get the file size, so we can pre-allocate the string. HUGE speed impact. - long length = 0; - fseek( file, 0, SEEK_END ); - length = ftell( file ); - fseek( file, 0, SEEK_SET ); - - // Strange case, but good to handle up front. - if ( length <= 0 ) - { - SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN ); - return false; - } - - // Subtle bug here. TinyXml did use fgets. But from the XML spec: - // 2.11 End-of-Line Handling - // - // - // ...the XML processor MUST behave as if it normalized all line breaks in external - // parsed entities (including the document entity) on input, before parsing, by translating - // both the two-character sequence #xD #xA and any #xD that is not followed by #xA to - // a single #xA character. - // - // - // It is not clear fgets does that, and certainly isn't clear it works cross platform. - // Generally, you expect fgets to translate from the convention of the OS to the c/unix - // convention, and not work generally. - - /* - while( fgets( buf, sizeof(buf), file ) ) - { - data += buf; - } - */ - - char* buf = new char[ length+1 ]; - buf[0] = 0; - - if ( fread( buf, length, 1, file ) != 1 ) { - delete [] buf; - SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN ); - return false; - } - - // Process the buffer in place to normalize new lines. (See comment above.) - // Copies from the 'p' to 'q' pointer, where p can advance faster if - // a newline-carriage return is hit. - // - // Wikipedia: - // Systems based on ASCII or a compatible character set use either LF (Line feed, '\n', 0x0A, 10 in decimal) or - // CR (Carriage return, '\r', 0x0D, 13 in decimal) individually, or CR followed by LF (CR+LF, 0x0D 0x0A)... - // * LF: Multics, Unix and Unix-like systems (GNU/Linux, AIX, Xenix, Mac OS X, FreeBSD, etc.), BeOS, Amiga, RISC OS, and others - // * CR+LF: DEC RT-11 and most other early non-Unix, non-IBM OSes, CP/M, MP/M, DOS, OS/2, Microsoft Windows, Symbian OS - // * CR: Commodore 8-bit machines, Apple II family, Mac OS up to version 9 and OS-9 - - const char* p = buf; // the read head - char* q = buf; // the write head - const char CR = 0x0d; - const char LF = 0x0a; - - buf[length] = 0; - while( *p ) { - assert( p < (buf+length) ); - assert( q <= (buf+length) ); - assert( q <= p ); - - if ( *p == CR ) { - *q++ = LF; - p++; - if ( *p == LF ) { // check for CR+LF (and skip LF) - p++; - } - } - else { - *q++ = *p++; - } - } - assert( q <= (buf+length) ); - *q = 0; - - Parse( buf, 0, encoding ); - - delete [] buf; - return !Error(); -} - - -bool TiXmlDocument::SaveFile( const char * filename ) const -{ - // The old c stuff lives on... - FILE* fp = TiXmlFOpen( filename, "w" ); - if ( fp ) - { - bool result = SaveFile( fp ); - fclose( fp ); - return result; - } - return false; -} - - -bool TiXmlDocument::SaveFile( FILE* fp ) const -{ - if ( useMicrosoftBOM ) - { - const unsigned char TIXML_UTF_LEAD_0 = 0xefU; - const unsigned char TIXML_UTF_LEAD_1 = 0xbbU; - const unsigned char TIXML_UTF_LEAD_2 = 0xbfU; - - fputc( TIXML_UTF_LEAD_0, fp ); - fputc( TIXML_UTF_LEAD_1, fp ); - fputc( TIXML_UTF_LEAD_2, fp ); - } - Print( fp, 0 ); - return (ferror(fp) == 0); -} - - -void TiXmlDocument::CopyTo( TiXmlDocument* target ) const -{ - TiXmlNode::CopyTo( target ); - - target->error = error; - target->errorId = errorId; - target->errorDesc = errorDesc; - target->tabsize = tabsize; - target->errorLocation = errorLocation; - target->useMicrosoftBOM = useMicrosoftBOM; - - TiXmlNode* node = 0; - for ( node = firstChild; node; node = node->NextSibling() ) - { - target->LinkEndChild( node->Clone() ); - } -} - - -TiXmlNode* TiXmlDocument::Clone() const -{ - TiXmlDocument* clone = new TiXmlDocument(); - if ( !clone ) - return 0; - - CopyTo( clone ); - return clone; -} - - -void TiXmlDocument::Print( FILE* cfile, int depth ) const -{ - assert( cfile ); - for ( const TiXmlNode* node=FirstChild(); node; node=node->NextSibling() ) - { - node->Print( cfile, depth ); - fprintf( cfile, "\n" ); - } -} - - -bool TiXmlDocument::Accept( TiXmlVisitor* visitor ) const -{ - if ( visitor->VisitEnter( *this ) ) - { - for ( const TiXmlNode* node=FirstChild(); node; node=node->NextSibling() ) - { - if ( !node->Accept( visitor ) ) - break; - } - } - return visitor->VisitExit( *this ); -} - - -const TiXmlAttribute* TiXmlAttribute::Next() const -{ - // We are using knowledge of the sentinel. The sentinel - // have a value or name. - if ( next->value.empty() && next->name.empty() ) - return 0; - return next; -} - -/* -TiXmlAttribute* TiXmlAttribute::Next() -{ - // We are using knowledge of the sentinel. The sentinel - // have a value or name. - if ( next->value.empty() && next->name.empty() ) - return 0; - return next; -} -*/ - -const TiXmlAttribute* TiXmlAttribute::Previous() const -{ - // We are using knowledge of the sentinel. The sentinel - // have a value or name. - if ( prev->value.empty() && prev->name.empty() ) - return 0; - return prev; -} - -/* -TiXmlAttribute* TiXmlAttribute::Previous() -{ - // We are using knowledge of the sentinel. The sentinel - // have a value or name. - if ( prev->value.empty() && prev->name.empty() ) - return 0; - return prev; -} -*/ - -void TiXmlAttribute::Print( FILE* cfile, int /*depth*/, TIXML_STRING* str ) const -{ - TIXML_STRING n, v; - - EncodeString( name, &n ); - EncodeString( value, &v ); - - if (value.find ('\"') == TIXML_STRING::npos) { - if ( cfile ) { - fprintf (cfile, "%s=\"%s\"", n.c_str(), v.c_str() ); - } - if ( str ) { - (*str) += n; (*str) += "=\""; (*str) += v; (*str) += "\""; - } - } - else { - if ( cfile ) { - fprintf (cfile, "%s='%s'", n.c_str(), v.c_str() ); - } - if ( str ) { - (*str) += n; (*str) += "='"; (*str) += v; (*str) += "'"; - } - } -} - - -int TiXmlAttribute::QueryIntValue( int* ival ) const -{ - if ( TIXML_SSCANF( value.c_str(), "%d", ival ) == 1 ) - return TIXML_SUCCESS; - return TIXML_WRONG_TYPE; -} - -int TiXmlAttribute::QueryDoubleValue( double* dval ) const -{ - if ( TIXML_SSCANF( value.c_str(), "%lf", dval ) == 1 ) - return TIXML_SUCCESS; - return TIXML_WRONG_TYPE; -} - -void TiXmlAttribute::SetIntValue( int _value ) -{ - char buf [64]; - #if defined(TIXML_SNPRINTF) - TIXML_SNPRINTF(buf, sizeof(buf), "%d", _value); - #else - sprintf (buf, "%d", _value); - #endif - SetValue (buf); -} - -void TiXmlAttribute::SetDoubleValue( double _value ) -{ - char buf [256]; - #if defined(TIXML_SNPRINTF) - TIXML_SNPRINTF( buf, sizeof(buf), "%g", _value); - #else - sprintf (buf, "%g", _value); - #endif - SetValue (buf); -} - -int TiXmlAttribute::IntValue() const -{ - return atoi (value.c_str ()); -} - -double TiXmlAttribute::DoubleValue() const -{ - return atof (value.c_str ()); -} - - -TiXmlComment::TiXmlComment( const TiXmlComment& copy ) : TiXmlNode( TiXmlNode::TINYXML_COMMENT ) -{ - copy.CopyTo( this ); -} - - -void TiXmlComment::operator=( const TiXmlComment& base ) -{ - Clear(); - base.CopyTo( this ); -} - - -void TiXmlComment::Print( FILE* cfile, int depth ) const -{ - assert( cfile ); - for ( int i=0; i", value.c_str() ); -} - - -void TiXmlComment::CopyTo( TiXmlComment* target ) const -{ - TiXmlNode::CopyTo( target ); -} - - -bool TiXmlComment::Accept( TiXmlVisitor* visitor ) const -{ - return visitor->Visit( *this ); -} - - -TiXmlNode* TiXmlComment::Clone() const -{ - TiXmlComment* clone = new TiXmlComment(); - - if ( !clone ) - return 0; - - CopyTo( clone ); - return clone; -} - - -void TiXmlText::Print( FILE* cfile, int depth ) const -{ - assert( cfile ); - if ( cdata ) - { - int i; - fprintf( cfile, "\n" ); - for ( i=0; i\n", value.c_str() ); // unformatted output - } - else - { - TIXML_STRING buffer; - EncodeString( value, &buffer ); - fprintf( cfile, "%s", buffer.c_str() ); - } -} - - -void TiXmlText::CopyTo( TiXmlText* target ) const -{ - TiXmlNode::CopyTo( target ); - target->cdata = cdata; -} - - -bool TiXmlText::Accept( TiXmlVisitor* visitor ) const -{ - return visitor->Visit( *this ); -} - - -TiXmlNode* TiXmlText::Clone() const -{ - TiXmlText* clone = 0; - clone = new TiXmlText( "" ); - - if ( !clone ) - return 0; - - CopyTo( clone ); - return clone; -} - - -TiXmlDeclaration::TiXmlDeclaration( const char * _version, - const char * _encoding, - const char * _standalone ) - : TiXmlNode( TiXmlNode::TINYXML_DECLARATION ) -{ - version = _version; - encoding = _encoding; - standalone = _standalone; -} - - -#ifdef TIXML_USE_STL -TiXmlDeclaration::TiXmlDeclaration( const std::string& _version, - const std::string& _encoding, - const std::string& _standalone ) - : TiXmlNode( TiXmlNode::TINYXML_DECLARATION ) -{ - version = _version; - encoding = _encoding; - standalone = _standalone; -} -#endif - - -TiXmlDeclaration::TiXmlDeclaration( const TiXmlDeclaration& copy ) - : TiXmlNode( TiXmlNode::TINYXML_DECLARATION ) -{ - copy.CopyTo( this ); -} - - -void TiXmlDeclaration::operator=( const TiXmlDeclaration& copy ) -{ - Clear(); - copy.CopyTo( this ); -} - - -void TiXmlDeclaration::Print( FILE* cfile, int /*depth*/, TIXML_STRING* str ) const -{ - if ( cfile ) fprintf( cfile, "" ); - if ( str ) (*str) += "?>"; -} - - -void TiXmlDeclaration::CopyTo( TiXmlDeclaration* target ) const -{ - TiXmlNode::CopyTo( target ); - - target->version = version; - target->encoding = encoding; - target->standalone = standalone; -} - - -bool TiXmlDeclaration::Accept( TiXmlVisitor* visitor ) const -{ - return visitor->Visit( *this ); -} - - -TiXmlNode* TiXmlDeclaration::Clone() const -{ - TiXmlDeclaration* clone = new TiXmlDeclaration(); - - if ( !clone ) - return 0; - - CopyTo( clone ); - return clone; -} - - -void TiXmlUnknown::Print( FILE* cfile, int depth ) const -{ - for ( int i=0; i", value.c_str() ); -} - - -void TiXmlUnknown::CopyTo( TiXmlUnknown* target ) const -{ - TiXmlNode::CopyTo( target ); -} - - -bool TiXmlUnknown::Accept( TiXmlVisitor* visitor ) const -{ - return visitor->Visit( *this ); -} - - -TiXmlNode* TiXmlUnknown::Clone() const -{ - TiXmlUnknown* clone = new TiXmlUnknown(); - - if ( !clone ) - return 0; - - CopyTo( clone ); - return clone; -} - - -TiXmlAttributeSet::TiXmlAttributeSet() -{ - sentinel.next = &sentinel; - sentinel.prev = &sentinel; -} - - -TiXmlAttributeSet::~TiXmlAttributeSet() -{ - assert( sentinel.next == &sentinel ); - assert( sentinel.prev == &sentinel ); -} - - -void TiXmlAttributeSet::Add( TiXmlAttribute* addMe ) -{ - #ifdef TIXML_USE_STL - assert( !Find( TIXML_STRING( addMe->Name() ) ) ); // Shouldn't be multiply adding to the set. - #else - assert( !Find( addMe->Name() ) ); // Shouldn't be multiply adding to the set. - #endif - - addMe->next = &sentinel; - addMe->prev = sentinel.prev; - - sentinel.prev->next = addMe; - sentinel.prev = addMe; -} - -void TiXmlAttributeSet::Remove( TiXmlAttribute* removeMe ) -{ - TiXmlAttribute* node; - - for( node = sentinel.next; node != &sentinel; node = node->next ) - { - if ( node == removeMe ) - { - node->prev->next = node->next; - node->next->prev = node->prev; - node->next = 0; - node->prev = 0; - return; - } - } - assert( 0 ); // we tried to remove a non-linked attribute. -} - - -#ifdef TIXML_USE_STL -TiXmlAttribute* TiXmlAttributeSet::Find( const std::string& name ) const -{ - for( TiXmlAttribute* node = sentinel.next; node != &sentinel; node = node->next ) - { - if ( node->name == name ) - return node; - } - return 0; -} - -TiXmlAttribute* TiXmlAttributeSet::FindOrCreate( const std::string& _name ) -{ - TiXmlAttribute* attrib = Find( _name ); - if ( !attrib ) { - attrib = new TiXmlAttribute(); - Add( attrib ); - attrib->SetName( _name ); - } - return attrib; -} -#endif - - -TiXmlAttribute* TiXmlAttributeSet::Find( const char* name ) const -{ - for( TiXmlAttribute* node = sentinel.next; node != &sentinel; node = node->next ) - { - if ( strcmp( node->name.c_str(), name ) == 0 ) - return node; - } - return 0; -} - - -TiXmlAttribute* TiXmlAttributeSet::FindOrCreate( const char* _name ) -{ - TiXmlAttribute* attrib = Find( _name ); - if ( !attrib ) { - attrib = new TiXmlAttribute(); - Add( attrib ); - attrib->SetName( _name ); - } - return attrib; -} - - -#ifdef TIXML_USE_STL -std::istream& operator>> (std::istream & in, TiXmlNode & base) -{ - TIXML_STRING tag; - tag.reserve( 8 * 1000 ); - base.StreamIn( &in, &tag ); - - base.Parse( tag.c_str(), 0, TIXML_DEFAULT_ENCODING ); - return in; -} -#endif - - -#ifdef TIXML_USE_STL -std::ostream& operator<< (std::ostream & out, const TiXmlNode & base) -{ - TiXmlPrinter printer; - printer.SetStreamPrinting(); - base.Accept( &printer ); - out << printer.Str(); - - return out; -} - - -std::string& operator<< (std::string& out, const TiXmlNode& base ) -{ - TiXmlPrinter printer; - printer.SetStreamPrinting(); - base.Accept( &printer ); - out.append( printer.Str() ); - - return out; -} -#endif - - -TiXmlHandle TiXmlHandle::FirstChild() const -{ - if ( node ) - { - TiXmlNode* child = node->FirstChild(); - if ( child ) - return TiXmlHandle( child ); - } - return TiXmlHandle( 0 ); -} - - -TiXmlHandle TiXmlHandle::FirstChild( const char * value ) const -{ - if ( node ) - { - TiXmlNode* child = node->FirstChild( value ); - if ( child ) - return TiXmlHandle( child ); - } - return TiXmlHandle( 0 ); -} - - -TiXmlHandle TiXmlHandle::FirstChildElement() const -{ - if ( node ) - { - TiXmlElement* child = node->FirstChildElement(); - if ( child ) - return TiXmlHandle( child ); - } - return TiXmlHandle( 0 ); -} - - -TiXmlHandle TiXmlHandle::FirstChildElement( const char * value ) const -{ - if ( node ) - { - TiXmlElement* child = node->FirstChildElement( value ); - if ( child ) - return TiXmlHandle( child ); - } - return TiXmlHandle( 0 ); -} - - -TiXmlHandle TiXmlHandle::Child( int count ) const -{ - if ( node ) - { - int i; - TiXmlNode* child = node->FirstChild(); - for ( i=0; - child && iNextSibling(), ++i ) - { - // nothing - } - if ( child ) - return TiXmlHandle( child ); - } - return TiXmlHandle( 0 ); -} - - -TiXmlHandle TiXmlHandle::Child( const char* value, int count ) const -{ - if ( node ) - { - int i; - TiXmlNode* child = node->FirstChild( value ); - for ( i=0; - child && iNextSibling( value ), ++i ) - { - // nothing - } - if ( child ) - return TiXmlHandle( child ); - } - return TiXmlHandle( 0 ); -} - - -TiXmlHandle TiXmlHandle::ChildElement( int count ) const -{ - if ( node ) - { - int i; - TiXmlElement* child = node->FirstChildElement(); - for ( i=0; - child && iNextSiblingElement(), ++i ) - { - // nothing - } - if ( child ) - return TiXmlHandle( child ); - } - return TiXmlHandle( 0 ); -} - - -TiXmlHandle TiXmlHandle::ChildElement( const char* value, int count ) const -{ - if ( node ) - { - int i; - TiXmlElement* child = node->FirstChildElement( value ); - for ( i=0; - child && iNextSiblingElement( value ), ++i ) - { - // nothing - } - if ( child ) - return TiXmlHandle( child ); - } - return TiXmlHandle( 0 ); -} - - -bool TiXmlPrinter::VisitEnter( const TiXmlDocument& ) -{ - return true; -} - -bool TiXmlPrinter::VisitExit( const TiXmlDocument& ) -{ - return true; -} - -bool TiXmlPrinter::VisitEnter( const TiXmlElement& element, const TiXmlAttribute* firstAttribute ) -{ - DoIndent(); - buffer += "<"; - buffer += element.Value(); - - for( const TiXmlAttribute* attrib = firstAttribute; attrib; attrib = attrib->Next() ) - { - buffer += " "; - attrib->Print( 0, 0, &buffer ); - } - - if ( !element.FirstChild() ) - { - buffer += " />"; - DoLineBreak(); - } - else - { - buffer += ">"; - if ( element.FirstChild()->ToText() - && element.LastChild() == element.FirstChild() - && element.FirstChild()->ToText()->CDATA() == false ) - { - simpleTextPrint = true; - // no DoLineBreak()! - } - else - { - DoLineBreak(); - } - } - ++depth; - return true; -} - - -bool TiXmlPrinter::VisitExit( const TiXmlElement& element ) -{ - --depth; - if ( !element.FirstChild() ) - { - // nothing. - } - else - { - if ( simpleTextPrint ) - { - simpleTextPrint = false; - } - else - { - DoIndent(); - } - buffer += ""; - DoLineBreak(); - } - return true; -} - - -bool TiXmlPrinter::Visit( const TiXmlText& text ) -{ - if ( text.CDATA() ) - { - DoIndent(); - buffer += ""; - DoLineBreak(); - } - else if ( simpleTextPrint ) - { - TIXML_STRING str; - TiXmlBase::EncodeString( text.ValueTStr(), &str ); - buffer += str; - } - else - { - DoIndent(); - TIXML_STRING str; - TiXmlBase::EncodeString( text.ValueTStr(), &str ); - buffer += str; - DoLineBreak(); - } - return true; -} - - -bool TiXmlPrinter::Visit( const TiXmlDeclaration& declaration ) -{ - DoIndent(); - declaration.Print( 0, 0, &buffer ); - DoLineBreak(); - return true; -} - - -bool TiXmlPrinter::Visit( const TiXmlComment& comment ) -{ - DoIndent(); - buffer += ""; - DoLineBreak(); - return true; -} - - -bool TiXmlPrinter::Visit( const TiXmlUnknown& unknown ) -{ - DoIndent(); - buffer += "<"; - buffer += unknown.Value(); - buffer += ">"; - DoLineBreak(); - return true; -} - diff --git a/v3d_main/terafly/src/core/tinyxml/tinyxml.h b/v3d_main/terafly/src/core/tinyxml/tinyxml.h deleted file mode 100644 index 05be801b84..0000000000 --- a/v3d_main/terafly/src/core/tinyxml/tinyxml.h +++ /dev/null @@ -1,1799 +0,0 @@ -/* -www.sourceforge.net/projects/tinyxml -Original code (2.0 and earlier )copyright (c) 2000-2006 Lee Thomason (www.grinninglizard.com) - -This software is provided 'as-is', without any express or implied -warranty. In no event will the authors be held liable for any -damages arising from the use of this software. - -Permission is granted to anyone to use this software for any -purpose, including commercial applications, and to alter it and -redistribute it freely, subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must -not claim that you wrote the original software. If you use this -software in a product, an acknowledgment in the product documentation -would be appreciated but is not required. - -2. Altered source versions must be plainly marked as such, and -must not be misrepresented as being the original software. - -3. This notice may not be removed or altered from any source -distribution. -*/ - - -#ifndef TINYXML_INCLUDED -#define TINYXML_INCLUDED - -#ifdef _MSC_VER -#pragma warning( push ) -#pragma warning( disable : 4530 ) -#pragma warning( disable : 4786 ) -#endif - -#include -#include -#include -#include -#include - -// Help out windows: -#if defined( _DEBUG ) && !defined( TIXML_DEBUG ) -#define TIXML_DEBUG -#endif - -#ifdef TIXML_USE_STL - #include - #include - #include - #define TIXML_STRING std::string -#else - #include "tinystr.h" - #define TIXML_STRING TiXmlString -#endif - -// Deprecated library function hell. Compilers want to use the -// new safe versions. This probably doesn't fully address the problem, -// but it gets closer. There are too many compilers for me to fully -// test. If you get compilation troubles, undefine TIXML_SAFE -#define TIXML_SAFE - -#ifdef TIXML_SAFE - #if defined(_MSC_VER) && (_MSC_VER >= 1400 ) - // Microsoft visual studio, version 2005 and higher. - #define TIXML_SNPRINTF _snprintf_s - #define TIXML_SSCANF sscanf_s - #elif defined(_MSC_VER) && (_MSC_VER >= 1200 ) - // Microsoft visual studio, version 6 and higher. - //#pragma message( "Using _sn* functions." ) - #define TIXML_SNPRINTF _snprintf - #define TIXML_SSCANF sscanf - #elif defined(__GNUC__) && (__GNUC__ >= 3 ) - // GCC version 3 and higher.s - //#warning( "Using sn* functions." ) - #define TIXML_SNPRINTF snprintf - #define TIXML_SSCANF sscanf - #else - #define TIXML_SNPRINTF snprintf - #define TIXML_SSCANF sscanf - #endif -#endif - -class TiXmlDocument; -class TiXmlElement; -class TiXmlComment; -class TiXmlUnknown; -class TiXmlAttribute; -class TiXmlText; -class TiXmlDeclaration; -class TiXmlParsingData; - -const int TIXML_MAJOR_VERSION = 2; -const int TIXML_MINOR_VERSION = 6; -const int TIXML_PATCH_VERSION = 1; - -/* Internal structure for tracking location of items - in the XML file. -*/ -struct TiXmlCursor -{ - TiXmlCursor() { Clear(); } - void Clear() { row = col = -1; } - - int row; // 0 based. - int col; // 0 based. -}; - - -/** - Implements the interface to the "Visitor pattern" (see the Accept() method.) - If you call the Accept() method, it requires being passed a TiXmlVisitor - class to handle callbacks. For nodes that contain other nodes (Document, Element) - you will get called with a VisitEnter/VisitExit pair. Nodes that are always leaves - are simply called with Visit(). - - If you return 'true' from a Visit method, recursive parsing will continue. If you return - false, no children of this node or its sibilings will be Visited. - - All flavors of Visit methods have a default implementation that returns 'true' (continue - visiting). You need to only override methods that are interesting to you. - - Generally Accept() is called on the TiXmlDocument, although all nodes suppert Visiting. - - You should never change the document from a callback. - - @sa TiXmlNode::Accept() -*/ -class TiXmlVisitor -{ -public: - virtual ~TiXmlVisitor() {} - - /// Visit a document. - virtual bool VisitEnter( const TiXmlDocument& /*doc*/ ) { return true; } - /// Visit a document. - virtual bool VisitExit( const TiXmlDocument& /*doc*/ ) { return true; } - - /// Visit an element. - virtual bool VisitEnter( const TiXmlElement& /*element*/, const TiXmlAttribute* /*firstAttribute*/ ) { return true; } - /// Visit an element. - virtual bool VisitExit( const TiXmlElement& /*element*/ ) { return true; } - - /// Visit a declaration - virtual bool Visit( const TiXmlDeclaration& /*declaration*/ ) { return true; } - /// Visit a text node - virtual bool Visit( const TiXmlText& /*text*/ ) { return true; } - /// Visit a comment node - virtual bool Visit( const TiXmlComment& /*comment*/ ) { return true; } - /// Visit an unknow node - virtual bool Visit( const TiXmlUnknown& /*unknown*/ ) { return true; } -}; - -// Only used by Attribute::Query functions -enum -{ - TIXML_SUCCESS, - TIXML_NO_ATTRIBUTE, - TIXML_WRONG_TYPE -}; - - -// Used by the parsing routines. -enum TiXmlEncoding -{ - TIXML_ENCODING_UNKNOWN, - TIXML_ENCODING_UTF8, - TIXML_ENCODING_LEGACY -}; - -const TiXmlEncoding TIXML_DEFAULT_ENCODING = TIXML_ENCODING_UNKNOWN; - -/** TiXmlBase is a base class for every class in TinyXml. - It does little except to establish that TinyXml classes - can be printed and provide some utility functions. - - In XML, the document and elements can contain - other elements and other types of nodes. - - @verbatim - A Document can contain: Element (container or leaf) - Comment (leaf) - Unknown (leaf) - Declaration( leaf ) - - An Element can contain: Element (container or leaf) - Text (leaf) - Attributes (not on tree) - Comment (leaf) - Unknown (leaf) - - A Decleration contains: Attributes (not on tree) - @endverbatim -*/ -class TiXmlBase -{ - friend class TiXmlNode; - friend class TiXmlElement; - friend class TiXmlDocument; - -public: - TiXmlBase() : userData(0) {} - virtual ~TiXmlBase() {} - - /** All TinyXml classes can print themselves to a filestream - or the string class (TiXmlString in non-STL mode, std::string - in STL mode.) Either or both cfile and str can be null. - - This is a formatted print, and will insert - tabs and newlines. - - (For an unformatted stream, use the << operator.) - */ - virtual void Print( FILE* cfile, int depth ) const = 0; - - /** The world does not agree on whether white space should be kept or - not. In order to make everyone happy, these global, static functions - are provided to set whether or not TinyXml will condense all white space - into a single space or not. The default is to condense. Note changing this - value is not thread safe. - */ - static void SetCondenseWhiteSpace( bool condense ) { condenseWhiteSpace = condense; } - - /// Return the current white space setting. - static bool IsWhiteSpaceCondensed() { return condenseWhiteSpace; } - - /** Return the position, in the original source file, of this node or attribute. - The row and column are 1-based. (That is the first row and first column is - 1,1). If the returns values are 0 or less, then the parser does not have - a row and column value. - - Generally, the row and column value will be set when the TiXmlDocument::Load(), - TiXmlDocument::LoadFile(), or any TiXmlNode::Parse() is called. It will NOT be set - when the DOM was created from operator>>. - - The values reflect the initial load. Once the DOM is modified programmatically - (by adding or changing nodes and attributes) the new values will NOT update to - reflect changes in the document. - - There is a minor performance cost to computing the row and column. Computation - can be disabled if TiXmlDocument::SetTabSize() is called with 0 as the value. - - @sa TiXmlDocument::SetTabSize() - */ - int Row() const { return location.row + 1; } - int Column() const { return location.col + 1; } ///< See Row() - - void SetUserData( void* user ) { userData = user; } ///< Set a pointer to arbitrary user data. - void* GetUserData() { return userData; } ///< Get a pointer to arbitrary user data. - const void* GetUserData() const { return userData; } ///< Get a pointer to arbitrary user data. - - // Table that returs, for a given lead byte, the total number of bytes - // in the UTF-8 sequence. - static const int utf8ByteTable[256]; - - virtual const char* Parse( const char* p, - TiXmlParsingData* data, - TiXmlEncoding encoding /*= TIXML_ENCODING_UNKNOWN */ ) = 0; - - /** Expands entities in a string. Note this should not contian the tag's '<', '>', etc, - or they will be transformed into entities! - */ - static void EncodeString( const TIXML_STRING& str, TIXML_STRING* out ); - - enum - { - TIXML_NO_ERROR = 0, - TIXML_ERROR, - TIXML_ERROR_OPENING_FILE, - TIXML_ERROR_PARSING_ELEMENT, - TIXML_ERROR_FAILED_TO_READ_ELEMENT_NAME, - TIXML_ERROR_READING_ELEMENT_VALUE, - TIXML_ERROR_READING_ATTRIBUTES, - TIXML_ERROR_PARSING_EMPTY, - TIXML_ERROR_READING_END_TAG, - TIXML_ERROR_PARSING_UNKNOWN, - TIXML_ERROR_PARSING_COMMENT, - TIXML_ERROR_PARSING_DECLARATION, - TIXML_ERROR_DOCUMENT_EMPTY, - TIXML_ERROR_EMBEDDED_NULL, - TIXML_ERROR_PARSING_CDATA, - TIXML_ERROR_DOCUMENT_TOP_ONLY, - - TIXML_ERROR_STRING_COUNT - }; - -protected: - - static const char* SkipWhiteSpace( const char*, TiXmlEncoding encoding ); - - inline static bool IsWhiteSpace( char c ) - { - return ( isspace( (unsigned char) c ) || c == '\n' || c == '\r' ); - } - inline static bool IsWhiteSpace( int c ) - { - if ( c < 256 ) - return IsWhiteSpace( (char) c ); - return false; // Again, only truly correct for English/Latin...but usually works. - } - - #ifdef TIXML_USE_STL - static bool StreamWhiteSpace( std::istream * in, TIXML_STRING * tag ); - static bool StreamTo( std::istream * in, int character, TIXML_STRING * tag ); - #endif - - /* Reads an XML name into the string provided. Returns - a pointer just past the last character of the name, - or 0 if the function has an error. - */ - static const char* ReadName( const char* p, TIXML_STRING* name, TiXmlEncoding encoding ); - - /* Reads text. Returns a pointer past the given end tag. - Wickedly complex options, but it keeps the (sensitive) code in one place. - */ - static const char* ReadText( const char* in, // where to start - TIXML_STRING* text, // the string read - bool ignoreWhiteSpace, // whether to keep the white space - const char* endTag, // what ends this text - bool ignoreCase, // whether to ignore case in the end tag - TiXmlEncoding encoding ); // the current encoding - - // If an entity has been found, transform it into a character. - static const char* GetEntity( const char* in, char* value, int* length, TiXmlEncoding encoding ); - - // Get a character, while interpreting entities. - // The length can be from 0 to 4 bytes. - inline static const char* GetChar( const char* p, char* _value, int* length, TiXmlEncoding encoding ) - { - assert( p ); - if ( encoding == TIXML_ENCODING_UTF8 ) - { - *length = utf8ByteTable[ *((const unsigned char*)p) ]; - assert( *length >= 0 && *length < 5 ); - } - else - { - *length = 1; - } - - if ( *length == 1 ) - { - if ( *p == '&' ) - return GetEntity( p, _value, length, encoding ); - *_value = *p; - return p+1; - } - else if ( *length ) - { - //strncpy( _value, p, *length ); // lots of compilers don't like this function (unsafe), - // and the null terminator isn't needed - for( int i=0; p[i] && i<*length; ++i ) { - _value[i] = p[i]; - } - return p + (*length); - } - else - { - // Not valid text. - return 0; - } - } - - // Return true if the next characters in the stream are any of the endTag sequences. - // Ignore case only works for english, and should only be relied on when comparing - // to English words: StringEqual( p, "version", true ) is fine. - static bool StringEqual( const char* p, - const char* endTag, - bool ignoreCase, - TiXmlEncoding encoding ); - - static const char* errorString[ TIXML_ERROR_STRING_COUNT ]; - - TiXmlCursor location; - - /// Field containing a generic user pointer - void* userData; - - // None of these methods are reliable for any language except English. - // Good for approximation, not great for accuracy. - static int IsAlpha( unsigned char anyByte, TiXmlEncoding encoding ); - static int IsAlphaNum( unsigned char anyByte, TiXmlEncoding encoding ); - inline static int ToLower( int v, TiXmlEncoding encoding ) - { - if ( encoding == TIXML_ENCODING_UTF8 ) - { - if ( v < 128 ) return tolower( v ); - return v; - } - else - { - return tolower( v ); - } - } - static void ConvertUTF32ToUTF8( unsigned long input, char* output, int* length ); - -private: - TiXmlBase( const TiXmlBase& ); // not implemented. - void operator=( const TiXmlBase& base ); // not allowed. - - struct Entity - { - const char* str; - unsigned int strLength; - char chr; - }; - enum - { - NUM_ENTITY = 5, - MAX_ENTITY_LENGTH = 6 - - }; - static Entity entity[ NUM_ENTITY ]; - static bool condenseWhiteSpace; -}; - - -/** The parent class for everything in the Document Object Model. - (Except for attributes). - Nodes have siblings, a parent, and children. A node can be - in a document, or stand on its own. The type of a TiXmlNode - can be queried, and it can be cast to its more defined type. -*/ -class TiXmlNode : public TiXmlBase -{ - friend class TiXmlDocument; - friend class TiXmlElement; - -public: - #ifdef TIXML_USE_STL - - /** An input stream operator, for every class. Tolerant of newlines and - formatting, but doesn't expect them. - */ - friend std::istream& operator >> (std::istream& in, TiXmlNode& base); - - /** An output stream operator, for every class. Note that this outputs - without any newlines or formatting, as opposed to Print(), which - includes tabs and new lines. - - The operator<< and operator>> are not completely symmetric. Writing - a node to a stream is very well defined. You'll get a nice stream - of output, without any extra whitespace or newlines. - - But reading is not as well defined. (As it always is.) If you create - a TiXmlElement (for example) and read that from an input stream, - the text needs to define an element or junk will result. This is - true of all input streams, but it's worth keeping in mind. - - A TiXmlDocument will read nodes until it reads a root element, and - all the children of that root element. - */ - friend std::ostream& operator<< (std::ostream& out, const TiXmlNode& base); - - /// Appends the XML node or attribute to a std::string. - friend std::string& operator<< (std::string& out, const TiXmlNode& base ); - - #endif - - /** The types of XML nodes supported by TinyXml. (All the - unsupported types are picked up by UNKNOWN.) - */ - enum NodeType - { - TINYXML_DOCUMENT, - TINYXML_ELEMENT, - TINYXML_COMMENT, - TINYXML_UNKNOWN, - TINYXML_TEXT, - TINYXML_DECLARATION, - TINYXML_TYPECOUNT - }; - - virtual ~TiXmlNode(); - - /** The meaning of 'value' changes for the specific type of - TiXmlNode. - @verbatim - Document: filename of the xml file - Element: name of the element - Comment: the comment text - Unknown: the tag contents - Text: the text string - @endverbatim - - The subclasses will wrap this function. - */ - const char *Value() const { return value.c_str (); } - - #ifdef TIXML_USE_STL - /** Return Value() as a std::string. If you only use STL, - this is more efficient than calling Value(). - Only available in STL mode. - */ - const std::string& ValueStr() const { return value; } - #endif - - const TIXML_STRING& ValueTStr() const { return value; } - - /** Changes the value of the node. Defined as: - @verbatim - Document: filename of the xml file - Element: name of the element - Comment: the comment text - Unknown: the tag contents - Text: the text string - @endverbatim - */ - void SetValue(const char * _value) { value = _value;} - - #ifdef TIXML_USE_STL - /// STL std::string form. - void SetValue( const std::string& _value ) { value = _value; } - #endif - - /// Delete all the children of this node. Does not affect 'this'. - void Clear(); - - /// One step up the DOM. - TiXmlNode* Parent() { return parent; } - const TiXmlNode* Parent() const { return parent; } - - const TiXmlNode* FirstChild() const { return firstChild; } ///< The first child of this node. Will be null if there are no children. - TiXmlNode* FirstChild() { return firstChild; } - const TiXmlNode* FirstChild( const char * value ) const; ///< The first child of this node with the matching 'value'. Will be null if none found. - /// The first child of this node with the matching 'value'. Will be null if none found. - TiXmlNode* FirstChild( const char * _value ) { - // Call through to the const version - safe since nothing is changed. Exiting syntax: cast this to a const (always safe) - // call the method, cast the return back to non-const. - return const_cast< TiXmlNode* > ((const_cast< const TiXmlNode* >(this))->FirstChild( _value )); - } - const TiXmlNode* LastChild() const { return lastChild; } /// The last child of this node. Will be null if there are no children. - TiXmlNode* LastChild() { return lastChild; } - - const TiXmlNode* LastChild( const char * value ) const; /// The last child of this node matching 'value'. Will be null if there are no children. - TiXmlNode* LastChild( const char * _value ) { - return const_cast< TiXmlNode* > ((const_cast< const TiXmlNode* >(this))->LastChild( _value )); - } - - #ifdef TIXML_USE_STL - const TiXmlNode* FirstChild( const std::string& _value ) const { return FirstChild (_value.c_str ()); } ///< STL std::string form. - TiXmlNode* FirstChild( const std::string& _value ) { return FirstChild (_value.c_str ()); } ///< STL std::string form. - const TiXmlNode* LastChild( const std::string& _value ) const { return LastChild (_value.c_str ()); } ///< STL std::string form. - TiXmlNode* LastChild( const std::string& _value ) { return LastChild (_value.c_str ()); } ///< STL std::string form. - #endif - - /** An alternate way to walk the children of a node. - One way to iterate over nodes is: - @verbatim - for( child = parent->FirstChild(); child; child = child->NextSibling() ) - @endverbatim - - IterateChildren does the same thing with the syntax: - @verbatim - child = 0; - while( child = parent->IterateChildren( child ) ) - @endverbatim - - IterateChildren takes the previous child as input and finds - the next one. If the previous child is null, it returns the - first. IterateChildren will return null when done. - */ - const TiXmlNode* IterateChildren( const TiXmlNode* previous ) const; - TiXmlNode* IterateChildren( const TiXmlNode* previous ) { - return const_cast< TiXmlNode* >( (const_cast< const TiXmlNode* >(this))->IterateChildren( previous ) ); - } - - /// This flavor of IterateChildren searches for children with a particular 'value' - const TiXmlNode* IterateChildren( const char * value, const TiXmlNode* previous ) const; - TiXmlNode* IterateChildren( const char * _value, const TiXmlNode* previous ) { - return const_cast< TiXmlNode* >( (const_cast< const TiXmlNode* >(this))->IterateChildren( _value, previous ) ); - } - - #ifdef TIXML_USE_STL - const TiXmlNode* IterateChildren( const std::string& _value, const TiXmlNode* previous ) const { return IterateChildren (_value.c_str (), previous); } ///< STL std::string form. - TiXmlNode* IterateChildren( const std::string& _value, const TiXmlNode* previous ) { return IterateChildren (_value.c_str (), previous); } ///< STL std::string form. - #endif - - /** Add a new node related to this. Adds a child past the LastChild. - Returns a pointer to the new object or NULL if an error occured. - */ - TiXmlNode* InsertEndChild( const TiXmlNode& addThis ); - - - /** Add a new node related to this. Adds a child past the LastChild. - - NOTE: the node to be added is passed by pointer, and will be - henceforth owned (and deleted) by tinyXml. This method is efficient - and avoids an extra copy, but should be used with care as it - uses a different memory model than the other insert functions. - - @sa InsertEndChild - */ - TiXmlNode* LinkEndChild( TiXmlNode* addThis ); - - /** Add a new node related to this. Adds a child before the specified child. - Returns a pointer to the new object or NULL if an error occured. - */ - TiXmlNode* InsertBeforeChild( TiXmlNode* beforeThis, const TiXmlNode& addThis ); - - /** Add a new node related to this. Adds a child after the specified child. - Returns a pointer to the new object or NULL if an error occured. - */ - TiXmlNode* InsertAfterChild( TiXmlNode* afterThis, const TiXmlNode& addThis ); - - /** Replace a child of this node. - Returns a pointer to the new object or NULL if an error occured. - */ - TiXmlNode* ReplaceChild( TiXmlNode* replaceThis, const TiXmlNode& withThis ); - - /// Delete a child of this node. - bool RemoveChild( TiXmlNode* removeThis ); - - /// Navigate to a sibling node. - const TiXmlNode* PreviousSibling() const { return prev; } - TiXmlNode* PreviousSibling() { return prev; } - - /// Navigate to a sibling node. - const TiXmlNode* PreviousSibling( const char * ) const; - TiXmlNode* PreviousSibling( const char *_prev ) { - return const_cast< TiXmlNode* >( (const_cast< const TiXmlNode* >(this))->PreviousSibling( _prev ) ); - } - - #ifdef TIXML_USE_STL - const TiXmlNode* PreviousSibling( const std::string& _value ) const { return PreviousSibling (_value.c_str ()); } ///< STL std::string form. - TiXmlNode* PreviousSibling( const std::string& _value ) { return PreviousSibling (_value.c_str ()); } ///< STL std::string form. - const TiXmlNode* NextSibling( const std::string& _value) const { return NextSibling (_value.c_str ()); } ///< STL std::string form. - TiXmlNode* NextSibling( const std::string& _value) { return NextSibling (_value.c_str ()); } ///< STL std::string form. - #endif - - /// Navigate to a sibling node. - const TiXmlNode* NextSibling() const { return next; } - TiXmlNode* NextSibling() { return next; } - - /// Navigate to a sibling node with the given 'value'. - const TiXmlNode* NextSibling( const char * ) const; - TiXmlNode* NextSibling( const char* _next ) { - return const_cast< TiXmlNode* >( (const_cast< const TiXmlNode* >(this))->NextSibling( _next ) ); - } - - /** Convenience function to get through elements. - Calls NextSibling and ToElement. Will skip all non-Element - nodes. Returns 0 if there is not another element. - */ - const TiXmlElement* NextSiblingElement() const; - TiXmlElement* NextSiblingElement() { - return const_cast< TiXmlElement* >( (const_cast< const TiXmlNode* >(this))->NextSiblingElement() ); - } - - /** Convenience function to get through elements. - Calls NextSibling and ToElement. Will skip all non-Element - nodes. Returns 0 if there is not another element. - */ - const TiXmlElement* NextSiblingElement( const char * ) const; - TiXmlElement* NextSiblingElement( const char *_next ) { - return const_cast< TiXmlElement* >( (const_cast< const TiXmlNode* >(this))->NextSiblingElement( _next ) ); - } - - #ifdef TIXML_USE_STL - const TiXmlElement* NextSiblingElement( const std::string& _value) const { return NextSiblingElement (_value.c_str ()); } ///< STL std::string form. - TiXmlElement* NextSiblingElement( const std::string& _value) { return NextSiblingElement (_value.c_str ()); } ///< STL std::string form. - #endif - - /// Convenience function to get through elements. - const TiXmlElement* FirstChildElement() const; - TiXmlElement* FirstChildElement() { - return const_cast< TiXmlElement* >( (const_cast< const TiXmlNode* >(this))->FirstChildElement() ); - } - - /// Convenience function to get through elements. - const TiXmlElement* FirstChildElement( const char * _value ) const; - TiXmlElement* FirstChildElement( const char * _value ) { - return const_cast< TiXmlElement* >( (const_cast< const TiXmlNode* >(this))->FirstChildElement( _value ) ); - } - - #ifdef TIXML_USE_STL - const TiXmlElement* FirstChildElement( const std::string& _value ) const { return FirstChildElement (_value.c_str ()); } ///< STL std::string form. - TiXmlElement* FirstChildElement( const std::string& _value ) { return FirstChildElement (_value.c_str ()); } ///< STL std::string form. - #endif - - /** Query the type (as an enumerated value, above) of this node. - The possible types are: DOCUMENT, ELEMENT, COMMENT, - UNKNOWN, TEXT, and DECLARATION. - */ - int Type() const { return type; } - - /** Return a pointer to the Document this node lives in. - Returns null if not in a document. - */ - const TiXmlDocument* GetDocument() const; - TiXmlDocument* GetDocument() { - return const_cast< TiXmlDocument* >( (const_cast< const TiXmlNode* >(this))->GetDocument() ); - } - - /// Returns true if this node has no children. - bool NoChildren() const { return !firstChild; } - - virtual const TiXmlDocument* ToDocument() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. - virtual const TiXmlElement* ToElement() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. - virtual const TiXmlComment* ToComment() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. - virtual const TiXmlUnknown* ToUnknown() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. - virtual const TiXmlText* ToText() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. - virtual const TiXmlDeclaration* ToDeclaration() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. - - virtual TiXmlDocument* ToDocument() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. - virtual TiXmlElement* ToElement() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. - virtual TiXmlComment* ToComment() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. - virtual TiXmlUnknown* ToUnknown() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. - virtual TiXmlText* ToText() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. - virtual TiXmlDeclaration* ToDeclaration() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. - - /** Create an exact duplicate of this node and return it. The memory must be deleted - by the caller. - */ - virtual TiXmlNode* Clone() const = 0; - - /** Accept a hierchical visit the nodes in the TinyXML DOM. Every node in the - XML tree will be conditionally visited and the host will be called back - via the TiXmlVisitor interface. - - This is essentially a SAX interface for TinyXML. (Note however it doesn't re-parse - the XML for the callbacks, so the performance of TinyXML is unchanged by using this - interface versus any other.) - - The interface has been based on ideas from: - - - http://www.saxproject.org/ - - http://c2.com/cgi/wiki?HierarchicalVisitorPattern - - Which are both good references for "visiting". - - An example of using Accept(): - @verbatim - TiXmlPrinter printer; - tinyxmlDoc.Accept( &printer ); - const char* xmlcstr = printer.CStr(); - @endverbatim - */ - virtual bool Accept( TiXmlVisitor* visitor ) const = 0; - -protected: - TiXmlNode( NodeType _type ); - - // Copy to the allocated object. Shared functionality between Clone, Copy constructor, - // and the assignment operator. - void CopyTo( TiXmlNode* target ) const; - - #ifdef TIXML_USE_STL - // The real work of the input operator. - virtual void StreamIn( std::istream* in, TIXML_STRING* tag ) = 0; - #endif - - // Figure out what is at *p, and parse it. Returns null if it is not an xml node. - TiXmlNode* Identify( const char* start, TiXmlEncoding encoding ); - - TiXmlNode* parent; - NodeType type; - - TiXmlNode* firstChild; - TiXmlNode* lastChild; - - TIXML_STRING value; - - TiXmlNode* prev; - TiXmlNode* next; - -private: - TiXmlNode( const TiXmlNode& ); // not implemented. - void operator=( const TiXmlNode& base ); // not allowed. -}; - - -/** An attribute is a name-value pair. Elements have an arbitrary - number of attributes, each with a unique name. - - @note The attributes are not TiXmlNodes, since they are not - part of the tinyXML document object model. There are other - suggested ways to look at this problem. -*/ -class TiXmlAttribute : public TiXmlBase -{ - friend class TiXmlAttributeSet; - -public: - /// Construct an empty attribute. - TiXmlAttribute() : TiXmlBase() - { - document = 0; - prev = next = 0; - } - - #ifdef TIXML_USE_STL - /// std::string constructor. - TiXmlAttribute( const std::string& _name, const std::string& _value ) - { - name = _name; - value = _value; - document = 0; - prev = next = 0; - } - #endif - - /// Construct an attribute with a name and value. - TiXmlAttribute( const char * _name, const char * _value ) - { - name = _name; - value = _value; - document = 0; - prev = next = 0; - } - - const char* Name() const { return name.c_str(); } ///< Return the name of this attribute. - const char* Value() const { return value.c_str(); } ///< Return the value of this attribute. - #ifdef TIXML_USE_STL - const std::string& ValueStr() const { return value; } ///< Return the value of this attribute. - #endif - int IntValue() const; ///< Return the value of this attribute, converted to an integer. - double DoubleValue() const; ///< Return the value of this attribute, converted to a double. - - // Get the tinyxml string representation - const TIXML_STRING& NameTStr() const { return name; } - - /** QueryIntValue examines the value string. It is an alternative to the - IntValue() method with richer error checking. - If the value is an integer, it is stored in 'value' and - the call returns TIXML_SUCCESS. If it is not - an integer, it returns TIXML_WRONG_TYPE. - - A specialized but useful call. Note that for success it returns 0, - which is the opposite of almost all other TinyXml calls. - */ - int QueryIntValue( int* _value ) const; - /// QueryDoubleValue examines the value string. See QueryIntValue(). - int QueryDoubleValue( double* _value ) const; - - void SetName( const char* _name ) { name = _name; } ///< Set the name of this attribute. - void SetValue( const char* _value ) { value = _value; } ///< Set the value. - - void SetIntValue( int _value ); ///< Set the value from an integer. - void SetDoubleValue( double _value ); ///< Set the value from a double. - - #ifdef TIXML_USE_STL - /// STL std::string form. - void SetName( const std::string& _name ) { name = _name; } - /// STL std::string form. - void SetValue( const std::string& _value ) { value = _value; } - #endif - - /// Get the next sibling attribute in the DOM. Returns null at end. - const TiXmlAttribute* Next() const; - TiXmlAttribute* Next() { - return const_cast< TiXmlAttribute* >( (const_cast< const TiXmlAttribute* >(this))->Next() ); - } - - /// Get the previous sibling attribute in the DOM. Returns null at beginning. - const TiXmlAttribute* Previous() const; - TiXmlAttribute* Previous() { - return const_cast< TiXmlAttribute* >( (const_cast< const TiXmlAttribute* >(this))->Previous() ); - } - - bool operator==( const TiXmlAttribute& rhs ) const { return rhs.name == name; } - bool operator<( const TiXmlAttribute& rhs ) const { return name < rhs.name; } - bool operator>( const TiXmlAttribute& rhs ) const { return name > rhs.name; } - - /* Attribute parsing starts: first letter of the name - returns: the next char after the value end quote - */ - virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); - - // Prints this Attribute to a FILE stream. - virtual void Print( FILE* cfile, int depth ) const { - Print( cfile, depth, 0 ); - } - void Print( FILE* cfile, int depth, TIXML_STRING* str ) const; - - // [internal use] - // Set the document pointer so the attribute can report errors. - void SetDocument( TiXmlDocument* doc ) { document = doc; } - -private: - TiXmlAttribute( const TiXmlAttribute& ); // not implemented. - void operator=( const TiXmlAttribute& base ); // not allowed. - - TiXmlDocument* document; // A pointer back to a document, for error reporting. - TIXML_STRING name; - TIXML_STRING value; - TiXmlAttribute* prev; - TiXmlAttribute* next; -}; - - -/* A class used to manage a group of attributes. - It is only used internally, both by the ELEMENT and the DECLARATION. - - The set can be changed transparent to the Element and Declaration - classes that use it, but NOT transparent to the Attribute - which has to implement a next() and previous() method. Which makes - it a bit problematic and prevents the use of STL. - - This version is implemented with circular lists because: - - I like circular lists - - it demonstrates some independence from the (typical) doubly linked list. -*/ -class TiXmlAttributeSet -{ -public: - TiXmlAttributeSet(); - ~TiXmlAttributeSet(); - - void Add( TiXmlAttribute* attribute ); - void Remove( TiXmlAttribute* attribute ); - - const TiXmlAttribute* First() const { return ( sentinel.next == &sentinel ) ? 0 : sentinel.next; } - TiXmlAttribute* First() { return ( sentinel.next == &sentinel ) ? 0 : sentinel.next; } - const TiXmlAttribute* Last() const { return ( sentinel.prev == &sentinel ) ? 0 : sentinel.prev; } - TiXmlAttribute* Last() { return ( sentinel.prev == &sentinel ) ? 0 : sentinel.prev; } - - TiXmlAttribute* Find( const char* _name ) const; - TiXmlAttribute* FindOrCreate( const char* _name ); - -# ifdef TIXML_USE_STL - TiXmlAttribute* Find( const std::string& _name ) const; - TiXmlAttribute* FindOrCreate( const std::string& _name ); -# endif - - -private: - //*ME: Because of hidden/disabled copy-construktor in TiXmlAttribute (sentinel-element), - //*ME: this class must be also use a hidden/disabled copy-constructor !!! - TiXmlAttributeSet( const TiXmlAttributeSet& ); // not allowed - void operator=( const TiXmlAttributeSet& ); // not allowed (as TiXmlAttribute) - - TiXmlAttribute sentinel; -}; - - -/** The element is a container class. It has a value, the element name, - and can contain other elements, text, comments, and unknowns. - Elements also contain an arbitrary number of attributes. -*/ -class TiXmlElement : public TiXmlNode -{ -public: - /// Construct an element. - TiXmlElement (const char * in_value); - - #ifdef TIXML_USE_STL - /// std::string constructor. - TiXmlElement( const std::string& _value ); - #endif - - TiXmlElement( const TiXmlElement& ); - - void operator=( const TiXmlElement& base ); - - virtual ~TiXmlElement(); - - /** Given an attribute name, Attribute() returns the value - for the attribute of that name, or null if none exists. - */ - const char* Attribute( const char* name ) const; - - /** Given an attribute name, Attribute() returns the value - for the attribute of that name, or null if none exists. - If the attribute exists and can be converted to an integer, - the integer value will be put in the return 'i', if 'i' - is non-null. - */ - const char* Attribute( const char* name, int* i ) const; - - /** Given an attribute name, Attribute() returns the value - for the attribute of that name, or null if none exists. - If the attribute exists and can be converted to an double, - the double value will be put in the return 'd', if 'd' - is non-null. - */ - const char* Attribute( const char* name, double* d ) const; - - /** QueryIntAttribute examines the attribute - it is an alternative to the - Attribute() method with richer error checking. - If the attribute is an integer, it is stored in 'value' and - the call returns TIXML_SUCCESS. If it is not - an integer, it returns TIXML_WRONG_TYPE. If the attribute - does not exist, then TIXML_NO_ATTRIBUTE is returned. - */ - int QueryIntAttribute( const char* name, int* _value ) const; - /// QueryDoubleAttribute examines the attribute - see QueryIntAttribute(). - int QueryDoubleAttribute( const char* name, double* _value ) const; - /// QueryFloatAttribute examines the attribute - see QueryIntAttribute(). - int QueryFloatAttribute( const char* name, float* _value ) const { - double d; - int result = QueryDoubleAttribute( name, &d ); - if ( result == TIXML_SUCCESS ) { - *_value = (float)d; - } - return result; - } - - #ifdef TIXML_USE_STL - /// QueryStringAttribute examines the attribute - see QueryIntAttribute(). - int QueryStringAttribute( const char* name, std::string* _value ) const { - const char* cstr = Attribute( name ); - if ( cstr ) { - *_value = std::string( cstr ); - return TIXML_SUCCESS; - } - return TIXML_NO_ATTRIBUTE; - } - - /** Template form of the attribute query which will try to read the - attribute into the specified type. Very easy, very powerful, but - be careful to make sure to call this with the correct type. - - NOTE: This method doesn't work correctly for 'string' types that contain spaces. - - @return TIXML_SUCCESS, TIXML_WRONG_TYPE, or TIXML_NO_ATTRIBUTE - */ - template< typename T > int QueryValueAttribute( const std::string& name, T* outValue ) const - { - const TiXmlAttribute* node = attributeSet.Find( name ); - if ( !node ) - return TIXML_NO_ATTRIBUTE; - - std::stringstream sstream( node->ValueStr() ); - sstream >> *outValue; - if ( !sstream.fail() ) - return TIXML_SUCCESS; - return TIXML_WRONG_TYPE; - } - - int QueryValueAttribute( const std::string& name, std::string* outValue ) const - { - const TiXmlAttribute* node = attributeSet.Find( name ); - if ( !node ) - return TIXML_NO_ATTRIBUTE; - *outValue = node->ValueStr(); - return TIXML_SUCCESS; - } - #endif - - /** Sets an attribute of name to a given value. The attribute - will be created if it does not exist, or changed if it does. - */ - void SetAttribute( const char* name, const char * _value ); - - #ifdef TIXML_USE_STL - const std::string* Attribute( const std::string& name ) const; - const std::string* Attribute( const std::string& name, int* i ) const; - const std::string* Attribute( const std::string& name, double* d ) const; - int QueryIntAttribute( const std::string& name, int* _value ) const; - int QueryDoubleAttribute( const std::string& name, double* _value ) const; - - /// STL std::string form. - void SetAttribute( const std::string& name, const std::string& _value ); - ///< STL std::string form. - void SetAttribute( const std::string& name, int _value ); - ///< STL std::string form. - void SetDoubleAttribute( const std::string& name, double value ); - #endif - - /** Sets an attribute of name to a given value. The attribute - will be created if it does not exist, or changed if it does. - */ - void SetAttribute( const char * name, int value ); - - /** Sets an attribute of name to a given value. The attribute - will be created if it does not exist, or changed if it does. - */ - void SetDoubleAttribute( const char * name, double value ); - - /** Deletes an attribute with the given name. - */ - void RemoveAttribute( const char * name ); - #ifdef TIXML_USE_STL - void RemoveAttribute( const std::string& name ) { RemoveAttribute (name.c_str ()); } ///< STL std::string form. - #endif - - const TiXmlAttribute* FirstAttribute() const { return attributeSet.First(); } ///< Access the first attribute in this element. - TiXmlAttribute* FirstAttribute() { return attributeSet.First(); } - const TiXmlAttribute* LastAttribute() const { return attributeSet.Last(); } ///< Access the last attribute in this element. - TiXmlAttribute* LastAttribute() { return attributeSet.Last(); } - - /** Convenience function for easy access to the text inside an element. Although easy - and concise, GetText() is limited compared to getting the TiXmlText child - and accessing it directly. - - If the first child of 'this' is a TiXmlText, the GetText() - returns the character string of the Text node, else null is returned. - - This is a convenient method for getting the text of simple contained text: - @verbatim - This is text - const char* str = fooElement->GetText(); - @endverbatim - - 'str' will be a pointer to "This is text". - - Note that this function can be misleading. If the element foo was created from - this XML: - @verbatim - This is text - @endverbatim - - then the value of str would be null. The first child node isn't a text node, it is - another element. From this XML: - @verbatim - This is text - @endverbatim - GetText() will return "This is ". - - WARNING: GetText() accesses a child node - don't become confused with the - similarly named TiXmlHandle::Text() and TiXmlNode::ToText() which are - safe type casts on the referenced node. - */ - const char* GetText() const; - - /// Creates a new Element and returns it - the returned element is a copy. - virtual TiXmlNode* Clone() const; - // Print the Element to a FILE stream. - virtual void Print( FILE* cfile, int depth ) const; - - /* Attribtue parsing starts: next char past '<' - returns: next char past '>' - */ - virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); - - virtual const TiXmlElement* ToElement() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type. - virtual TiXmlElement* ToElement() { return this; } ///< Cast to a more defined type. Will return null not of the requested type. - - /** Walk the XML tree visiting this node and all of its children. - */ - virtual bool Accept( TiXmlVisitor* visitor ) const; - -protected: - - void CopyTo( TiXmlElement* target ) const; - void ClearThis(); // like clear, but initializes 'this' object as well - - // Used to be public [internal use] - #ifdef TIXML_USE_STL - virtual void StreamIn( std::istream * in, TIXML_STRING * tag ); - #endif - /* [internal use] - Reads the "value" of the element -- another element, or text. - This should terminate with the current end tag. - */ - const char* ReadValue( const char* in, TiXmlParsingData* prevData, TiXmlEncoding encoding ); - -private: - TiXmlAttributeSet attributeSet; -}; - - -/** An XML comment. -*/ -class TiXmlComment : public TiXmlNode -{ -public: - /// Constructs an empty comment. - TiXmlComment() : TiXmlNode( TiXmlNode::TINYXML_COMMENT ) {} - /// Construct a comment from text. - TiXmlComment( const char* _value ) : TiXmlNode( TiXmlNode::TINYXML_COMMENT ) { - SetValue( _value ); - } - TiXmlComment( const TiXmlComment& ); - void operator=( const TiXmlComment& base ); - - virtual ~TiXmlComment() {} - - /// Returns a copy of this Comment. - virtual TiXmlNode* Clone() const; - // Write this Comment to a FILE stream. - virtual void Print( FILE* cfile, int depth ) const; - - /* Attribtue parsing starts: at the ! of the !-- - returns: next char past '>' - */ - virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); - - virtual const TiXmlComment* ToComment() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type. - virtual TiXmlComment* ToComment() { return this; } ///< Cast to a more defined type. Will return null not of the requested type. - - /** Walk the XML tree visiting this node and all of its children. - */ - virtual bool Accept( TiXmlVisitor* visitor ) const; - -protected: - void CopyTo( TiXmlComment* target ) const; - - // used to be public - #ifdef TIXML_USE_STL - virtual void StreamIn( std::istream * in, TIXML_STRING * tag ); - #endif -// virtual void StreamOut( TIXML_OSTREAM * out ) const; - -private: - -}; - - -/** XML text. A text node can have 2 ways to output the next. "normal" output - and CDATA. It will default to the mode it was parsed from the XML file and - you generally want to leave it alone, but you can change the output mode with - SetCDATA() and query it with CDATA(). -*/ -class TiXmlText : public TiXmlNode -{ - friend class TiXmlElement; -public: - /** Constructor for text element. By default, it is treated as - normal, encoded text. If you want it be output as a CDATA text - element, set the parameter _cdata to 'true' - */ - TiXmlText (const char * initValue ) : TiXmlNode (TiXmlNode::TINYXML_TEXT) - { - SetValue( initValue ); - cdata = false; - } - virtual ~TiXmlText() {} - - #ifdef TIXML_USE_STL - /// Constructor. - TiXmlText( const std::string& initValue ) : TiXmlNode (TiXmlNode::TINYXML_TEXT) - { - SetValue( initValue ); - cdata = false; - } - #endif - - TiXmlText( const TiXmlText& copy ) : TiXmlNode( TiXmlNode::TINYXML_TEXT ) { copy.CopyTo( this ); } - void operator=( const TiXmlText& base ) { base.CopyTo( this ); } - - // Write this text object to a FILE stream. - virtual void Print( FILE* cfile, int depth ) const; - - /// Queries whether this represents text using a CDATA section. - bool CDATA() const { return cdata; } - /// Turns on or off a CDATA representation of text. - void SetCDATA( bool _cdata ) { cdata = _cdata; } - - virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); - - virtual const TiXmlText* ToText() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type. - virtual TiXmlText* ToText() { return this; } ///< Cast to a more defined type. Will return null not of the requested type. - - /** Walk the XML tree visiting this node and all of its children. - */ - virtual bool Accept( TiXmlVisitor* content ) const; - -protected : - /// [internal use] Creates a new Element and returns it. - virtual TiXmlNode* Clone() const; - void CopyTo( TiXmlText* target ) const; - - bool Blank() const; // returns true if all white space and new lines - // [internal use] - #ifdef TIXML_USE_STL - virtual void StreamIn( std::istream * in, TIXML_STRING * tag ); - #endif - -private: - bool cdata; // true if this should be input and output as a CDATA style text element -}; - - -/** In correct XML the declaration is the first entry in the file. - @verbatim - - @endverbatim - - TinyXml will happily read or write files without a declaration, - however. There are 3 possible attributes to the declaration: - version, encoding, and standalone. - - Note: In this version of the code, the attributes are - handled as special cases, not generic attributes, simply - because there can only be at most 3 and they are always the same. -*/ -class TiXmlDeclaration : public TiXmlNode -{ -public: - /// Construct an empty declaration. - TiXmlDeclaration() : TiXmlNode( TiXmlNode::TINYXML_DECLARATION ) {} - -#ifdef TIXML_USE_STL - /// Constructor. - TiXmlDeclaration( const std::string& _version, - const std::string& _encoding, - const std::string& _standalone ); -#endif - - /// Construct. - TiXmlDeclaration( const char* _version, - const char* _encoding, - const char* _standalone ); - - TiXmlDeclaration( const TiXmlDeclaration& copy ); - void operator=( const TiXmlDeclaration& copy ); - - virtual ~TiXmlDeclaration() {} - - /// Version. Will return an empty string if none was found. - const char *Version() const { return version.c_str (); } - /// Encoding. Will return an empty string if none was found. - const char *Encoding() const { return encoding.c_str (); } - /// Is this a standalone document? - const char *Standalone() const { return standalone.c_str (); } - - /// Creates a copy of this Declaration and returns it. - virtual TiXmlNode* Clone() const; - // Print this declaration to a FILE stream. - virtual void Print( FILE* cfile, int depth, TIXML_STRING* str ) const; - virtual void Print( FILE* cfile, int depth ) const { - Print( cfile, depth, 0 ); - } - - virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); - - virtual const TiXmlDeclaration* ToDeclaration() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type. - virtual TiXmlDeclaration* ToDeclaration() { return this; } ///< Cast to a more defined type. Will return null not of the requested type. - - /** Walk the XML tree visiting this node and all of its children. - */ - virtual bool Accept( TiXmlVisitor* visitor ) const; - -protected: - void CopyTo( TiXmlDeclaration* target ) const; - // used to be public - #ifdef TIXML_USE_STL - virtual void StreamIn( std::istream * in, TIXML_STRING * tag ); - #endif - -private: - - TIXML_STRING version; - TIXML_STRING encoding; - TIXML_STRING standalone; -}; - - -/** Any tag that tinyXml doesn't recognize is saved as an - unknown. It is a tag of text, but should not be modified. - It will be written back to the XML, unchanged, when the file - is saved. - - DTD tags get thrown into TiXmlUnknowns. -*/ -class TiXmlUnknown : public TiXmlNode -{ -public: - TiXmlUnknown() : TiXmlNode( TiXmlNode::TINYXML_UNKNOWN ) {} - virtual ~TiXmlUnknown() {} - - TiXmlUnknown( const TiXmlUnknown& copy ) : TiXmlNode( TiXmlNode::TINYXML_UNKNOWN ) { copy.CopyTo( this ); } - void operator=( const TiXmlUnknown& copy ) { copy.CopyTo( this ); } - - /// Creates a copy of this Unknown and returns it. - virtual TiXmlNode* Clone() const; - // Print this Unknown to a FILE stream. - virtual void Print( FILE* cfile, int depth ) const; - - virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); - - virtual const TiXmlUnknown* ToUnknown() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type. - virtual TiXmlUnknown* ToUnknown() { return this; } ///< Cast to a more defined type. Will return null not of the requested type. - - /** Walk the XML tree visiting this node and all of its children. - */ - virtual bool Accept( TiXmlVisitor* content ) const; - -protected: - void CopyTo( TiXmlUnknown* target ) const; - - #ifdef TIXML_USE_STL - virtual void StreamIn( std::istream * in, TIXML_STRING * tag ); - #endif - -private: - -}; - - -/** Always the top level node. A document binds together all the - XML pieces. It can be saved, loaded, and printed to the screen. - The 'value' of a document node is the xml file name. -*/ -class TiXmlDocument : public TiXmlNode -{ -public: - /// Create an empty document, that has no name. - TiXmlDocument(); - /// Create a document with a name. The name of the document is also the filename of the xml. - TiXmlDocument( const char * documentName ); - - #ifdef TIXML_USE_STL - /// Constructor. - TiXmlDocument( const std::string& documentName ); - #endif - - TiXmlDocument( const TiXmlDocument& copy ); - void operator=( const TiXmlDocument& copy ); - - virtual ~TiXmlDocument() {} - - /** Load a file using the current document value. - Returns true if successful. Will delete any existing - document data before loading. - */ - bool LoadFile( TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ); - /// Save a file using the current document value. Returns true if successful. - bool SaveFile() const; - /// Load a file using the given filename. Returns true if successful. - bool LoadFile( const char * filename, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ); - /// Save a file using the given filename. Returns true if successful. - bool SaveFile( const char * filename ) const; - /** Load a file using the given FILE*. Returns true if successful. Note that this method - doesn't stream - the entire object pointed at by the FILE* - will be interpreted as an XML file. TinyXML doesn't stream in XML from the current - file location. Streaming may be added in the future. - */ - bool LoadFile( FILE*, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ); - /// Save a file using the given FILE*. Returns true if successful. - bool SaveFile( FILE* ) const; - - #ifdef TIXML_USE_STL - bool LoadFile( const std::string& filename, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ) ///< STL std::string version. - { - return LoadFile( filename.c_str(), encoding ); - } - bool SaveFile( const std::string& filename ) const ///< STL std::string version. - { - return SaveFile( filename.c_str() ); - } - #endif - - /** Parse the given null terminated block of xml data. Passing in an encoding to this - method (either TIXML_ENCODING_LEGACY or TIXML_ENCODING_UTF8 will force TinyXml - to use that encoding, regardless of what TinyXml might otherwise try to detect. - */ - virtual const char* Parse( const char* p, TiXmlParsingData* data = 0, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ); - - /** Get the root element -- the only top level element -- of the document. - In well formed XML, there should only be one. TinyXml is tolerant of - multiple elements at the document level. - */ - const TiXmlElement* RootElement() const { return FirstChildElement(); } - TiXmlElement* RootElement() { return FirstChildElement(); } - - /** If an error occurs, Error will be set to true. Also, - - The ErrorId() will contain the integer identifier of the error (not generally useful) - - The ErrorDesc() method will return the name of the error. (very useful) - - The ErrorRow() and ErrorCol() will return the location of the error (if known) - */ - bool Error() const { return error; } - - /// Contains a textual (english) description of the error if one occurs. - const char * ErrorDesc() const { return errorDesc.c_str (); } - - /** Generally, you probably want the error string ( ErrorDesc() ). But if you - prefer the ErrorId, this function will fetch it. - */ - int ErrorId() const { return errorId; } - - /** Returns the location (if known) of the error. The first column is column 1, - and the first row is row 1. A value of 0 means the row and column wasn't applicable - (memory errors, for example, have no row/column) or the parser lost the error. (An - error in the error reporting, in that case.) - - @sa SetTabSize, Row, Column - */ - int ErrorRow() const { return errorLocation.row+1; } - int ErrorCol() const { return errorLocation.col+1; } ///< The column where the error occured. See ErrorRow() - - /** SetTabSize() allows the error reporting functions (ErrorRow() and ErrorCol()) - to report the correct values for row and column. It does not change the output - or input in any way. - - By calling this method, with a tab size - greater than 0, the row and column of each node and attribute is stored - when the file is loaded. Very useful for tracking the DOM back in to - the source file. - - The tab size is required for calculating the location of nodes. If not - set, the default of 4 is used. The tabsize is set per document. Setting - the tabsize to 0 disables row/column tracking. - - Note that row and column tracking is not supported when using operator>>. - - The tab size needs to be enabled before the parse or load. Correct usage: - @verbatim - TiXmlDocument doc; - doc.SetTabSize( 8 ); - doc.Load( "myfile.xml" ); - @endverbatim - - @sa Row, Column - */ - void SetTabSize( int _tabsize ) { tabsize = _tabsize; } - - int TabSize() const { return tabsize; } - - /** If you have handled the error, it can be reset with this call. The error - state is automatically cleared if you Parse a new XML block. - */ - void ClearError() { error = false; - errorId = 0; - errorDesc = ""; - errorLocation.row = errorLocation.col = 0; - //errorLocation.last = 0; - } - - /** Write the document to standard out using formatted printing ("pretty print"). */ - void Print() const { Print( stdout, 0 ); } - - /* Write the document to a string using formatted printing ("pretty print"). This - will allocate a character array (new char[]) and return it as a pointer. The - calling code pust call delete[] on the return char* to avoid a memory leak. - */ - //char* PrintToMemory() const; - - /// Print this Document to a FILE stream. - virtual void Print( FILE* cfile, int depth = 0 ) const; - // [internal use] - void SetError( int err, const char* errorLocation, TiXmlParsingData* prevData, TiXmlEncoding encoding ); - - virtual const TiXmlDocument* ToDocument() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type. - virtual TiXmlDocument* ToDocument() { return this; } ///< Cast to a more defined type. Will return null not of the requested type. - - /** Walk the XML tree visiting this node and all of its children. - */ - virtual bool Accept( TiXmlVisitor* content ) const; - -protected : - // [internal use] - virtual TiXmlNode* Clone() const; - #ifdef TIXML_USE_STL - virtual void StreamIn( std::istream * in, TIXML_STRING * tag ); - #endif - -private: - void CopyTo( TiXmlDocument* target ) const; - - bool error; - int errorId; - TIXML_STRING errorDesc; - int tabsize; - TiXmlCursor errorLocation; - bool useMicrosoftBOM; // the UTF-8 BOM were found when read. Note this, and try to write. -}; - - -/** - A TiXmlHandle is a class that wraps a node pointer with null checks; this is - an incredibly useful thing. Note that TiXmlHandle is not part of the TinyXml - DOM structure. It is a separate utility class. - - Take an example: - @verbatim - - - - - - - @endverbatim - - Assuming you want the value of "attributeB" in the 2nd "Child" element, it's very - easy to write a *lot* of code that looks like: - - @verbatim - TiXmlElement* root = document.FirstChildElement( "Document" ); - if ( root ) - { - TiXmlElement* element = root->FirstChildElement( "Element" ); - if ( element ) - { - TiXmlElement* child = element->FirstChildElement( "Child" ); - if ( child ) - { - TiXmlElement* child2 = child->NextSiblingElement( "Child" ); - if ( child2 ) - { - // Finally do something useful. - @endverbatim - - And that doesn't even cover "else" cases. TiXmlHandle addresses the verbosity - of such code. A TiXmlHandle checks for null pointers so it is perfectly safe - and correct to use: - - @verbatim - TiXmlHandle docHandle( &document ); - TiXmlElement* child2 = docHandle.FirstChild( "Document" ).FirstChild( "Element" ).Child( "Child", 1 ).ToElement(); - if ( child2 ) - { - // do something useful - @endverbatim - - Which is MUCH more concise and useful. - - It is also safe to copy handles - internally they are nothing more than node pointers. - @verbatim - TiXmlHandle handleCopy = handle; - @endverbatim - - What they should not be used for is iteration: - - @verbatim - int i=0; - while ( true ) - { - TiXmlElement* child = docHandle.FirstChild( "Document" ).FirstChild( "Element" ).Child( "Child", i ).ToElement(); - if ( !child ) - break; - // do something - ++i; - } - @endverbatim - - It seems reasonable, but it is in fact two embedded while loops. The Child method is - a linear walk to find the element, so this code would iterate much more than it needs - to. Instead, prefer: - - @verbatim - TiXmlElement* child = docHandle.FirstChild( "Document" ).FirstChild( "Element" ).FirstChild( "Child" ).ToElement(); - - for( child; child; child=child->NextSiblingElement() ) - { - // do something - } - @endverbatim -*/ -class TiXmlHandle -{ -public: - /// Create a handle from any node (at any depth of the tree.) This can be a null pointer. - TiXmlHandle( TiXmlNode* _node ) { this->node = _node; } - /// Copy constructor - TiXmlHandle( const TiXmlHandle& ref ) { this->node = ref.node; } - TiXmlHandle operator=( const TiXmlHandle& ref ) { this->node = ref.node; return *this; } - - /// Return a handle to the first child node. - TiXmlHandle FirstChild() const; - /// Return a handle to the first child node with the given name. - TiXmlHandle FirstChild( const char * value ) const; - /// Return a handle to the first child element. - TiXmlHandle FirstChildElement() const; - /// Return a handle to the first child element with the given name. - TiXmlHandle FirstChildElement( const char * value ) const; - - /** Return a handle to the "index" child with the given name. - The first child is 0, the second 1, etc. - */ - TiXmlHandle Child( const char* value, int index ) const; - /** Return a handle to the "index" child. - The first child is 0, the second 1, etc. - */ - TiXmlHandle Child( int index ) const; - /** Return a handle to the "index" child element with the given name. - The first child element is 0, the second 1, etc. Note that only TiXmlElements - are indexed: other types are not counted. - */ - TiXmlHandle ChildElement( const char* value, int index ) const; - /** Return a handle to the "index" child element. - The first child element is 0, the second 1, etc. Note that only TiXmlElements - are indexed: other types are not counted. - */ - TiXmlHandle ChildElement( int index ) const; - - #ifdef TIXML_USE_STL - TiXmlHandle FirstChild( const std::string& _value ) const { return FirstChild( _value.c_str() ); } - TiXmlHandle FirstChildElement( const std::string& _value ) const { return FirstChildElement( _value.c_str() ); } - - TiXmlHandle Child( const std::string& _value, int index ) const { return Child( _value.c_str(), index ); } - TiXmlHandle ChildElement( const std::string& _value, int index ) const { return ChildElement( _value.c_str(), index ); } - #endif - - /** Return the handle as a TiXmlNode. This may return null. - */ - TiXmlNode* ToNode() const { return node; } - /** Return the handle as a TiXmlElement. This may return null. - */ - TiXmlElement* ToElement() const { return ( ( node && node->ToElement() ) ? node->ToElement() : 0 ); } - /** Return the handle as a TiXmlText. This may return null. - */ - TiXmlText* ToText() const { return ( ( node && node->ToText() ) ? node->ToText() : 0 ); } - /** Return the handle as a TiXmlUnknown. This may return null. - */ - TiXmlUnknown* ToUnknown() const { return ( ( node && node->ToUnknown() ) ? node->ToUnknown() : 0 ); } - - /** @deprecated use ToNode. - Return the handle as a TiXmlNode. This may return null. - */ - TiXmlNode* Node() const { return ToNode(); } - /** @deprecated use ToElement. - Return the handle as a TiXmlElement. This may return null. - */ - TiXmlElement* Element() const { return ToElement(); } - /** @deprecated use ToText() - Return the handle as a TiXmlText. This may return null. - */ - TiXmlText* Text() const { return ToText(); } - /** @deprecated use ToUnknown() - Return the handle as a TiXmlUnknown. This may return null. - */ - TiXmlUnknown* Unknown() const { return ToUnknown(); } - -private: - TiXmlNode* node; -}; - - -/** Print to memory functionality. The TiXmlPrinter is useful when you need to: - - -# Print to memory (especially in non-STL mode) - -# Control formatting (line endings, etc.) - - When constructed, the TiXmlPrinter is in its default "pretty printing" mode. - Before calling Accept() you can call methods to control the printing - of the XML document. After TiXmlNode::Accept() is called, the printed document can - be accessed via the CStr(), Str(), and Size() methods. - - TiXmlPrinter uses the Visitor API. - @verbatim - TiXmlPrinter printer; - printer.SetIndent( "\t" ); - - doc.Accept( &printer ); - fprintf( stdout, "%s", printer.CStr() ); - @endverbatim -*/ -class TiXmlPrinter : public TiXmlVisitor -{ -public: - TiXmlPrinter() : depth( 0 ), simpleTextPrint( false ), - buffer(), indent( " " ), lineBreak( "\n" ) {} - - virtual bool VisitEnter( const TiXmlDocument& doc ); - virtual bool VisitExit( const TiXmlDocument& doc ); - - virtual bool VisitEnter( const TiXmlElement& element, const TiXmlAttribute* firstAttribute ); - virtual bool VisitExit( const TiXmlElement& element ); - - virtual bool Visit( const TiXmlDeclaration& declaration ); - virtual bool Visit( const TiXmlText& text ); - virtual bool Visit( const TiXmlComment& comment ); - virtual bool Visit( const TiXmlUnknown& unknown ); - - /** Set the indent characters for printing. By default 4 spaces - but tab (\t) is also useful, or null/empty string for no indentation. - */ - void SetIndent( const char* _indent ) { indent = _indent ? _indent : "" ; } - /// Query the indention string. - const char* Indent() { return indent.c_str(); } - /** Set the line breaking string. By default set to newline (\n). - Some operating systems prefer other characters, or can be - set to the null/empty string for no indenation. - */ - void SetLineBreak( const char* _lineBreak ) { lineBreak = _lineBreak ? _lineBreak : ""; } - /// Query the current line breaking string. - const char* LineBreak() { return lineBreak.c_str(); } - - /** Switch over to "stream printing" which is the most dense formatting without - linebreaks. Common when the XML is needed for network transmission. - */ - void SetStreamPrinting() { indent = ""; - lineBreak = ""; - } - /// Return the result. - const char* CStr() { return buffer.c_str(); } - /// Return the length of the result string. - size_t Size() { return buffer.size(); } - - #ifdef TIXML_USE_STL - /// Return the result. - const std::string& Str() { return buffer; } - #endif - -private: - void DoIndent() { - for( int i=0; i -#include - -#include "tinyxml.h" - -//#define DEBUG_PARSER -#if defined( DEBUG_PARSER ) -# if defined( TIXML_DEBUG ) && defined( _MSC_VER ) -# include -# define TIXML_LOG OutputDebugString -# else -# define TIXML_LOG printf -# endif -#endif - -// Note tha "PutString" hardcodes the same list. This -// is less flexible than it appears. Changing the entries -// or order will break putstring. -TiXmlBase::Entity TiXmlBase::entity[ NUM_ENTITY ] = -{ - { "&", 5, '&' }, - { "<", 4, '<' }, - { ">", 4, '>' }, - { """, 6, '\"' }, - { "'", 6, '\'' } -}; - -// Bunch of unicode info at: -// http://www.unicode.org/faq/utf_bom.html -// Including the basic of this table, which determines the #bytes in the -// sequence from the lead byte. 1 placed for invalid sequences -- -// although the result will be junk, pass it through as much as possible. -// Beware of the non-characters in UTF-8: -// ef bb bf (Microsoft "lead bytes") -// ef bf be -// ef bf bf - -const unsigned char TIXML_UTF_LEAD_0 = 0xefU; -const unsigned char TIXML_UTF_LEAD_1 = 0xbbU; -const unsigned char TIXML_UTF_LEAD_2 = 0xbfU; - -const int TiXmlBase::utf8ByteTable[256] = -{ - // 0 1 2 3 4 5 6 7 8 9 a b c d e f - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x00 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x10 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x20 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x30 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x40 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x50 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x60 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x70 End of ASCII range - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x80 0x80 to 0xc1 invalid - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x90 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xa0 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xb0 - 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 0xc0 0xc2 to 0xdf 2 byte - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 0xd0 - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 0xe0 0xe0 to 0xef 3 byte - 4, 4, 4, 4, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // 0xf0 0xf0 to 0xf4 4 byte, 0xf5 and higher invalid -}; - - -void TiXmlBase::ConvertUTF32ToUTF8( unsigned long input, char* output, int* length ) -{ - const unsigned long BYTE_MASK = 0xBF; - const unsigned long BYTE_MARK = 0x80; - const unsigned long FIRST_BYTE_MARK[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; - - if (input < 0x80) - *length = 1; - else if ( input < 0x800 ) - *length = 2; - else if ( input < 0x10000 ) - *length = 3; - else if ( input < 0x200000 ) - *length = 4; - else - { *length = 0; return; } // This code won't covert this correctly anyway. - - output += *length; - - // Scary scary fall throughs. - switch (*length) - { - case 4: - --output; - *output = (char)((input | BYTE_MARK) & BYTE_MASK); - input >>= 6; - case 3: - --output; - *output = (char)((input | BYTE_MARK) & BYTE_MASK); - input >>= 6; - case 2: - --output; - *output = (char)((input | BYTE_MARK) & BYTE_MASK); - input >>= 6; - case 1: - --output; - *output = (char)(input | FIRST_BYTE_MARK[*length]); - } -} - - -/*static*/ int TiXmlBase::IsAlpha( unsigned char anyByte, TiXmlEncoding /*encoding*/ ) -{ - // This will only work for low-ascii, everything else is assumed to be a valid - // letter. I'm not sure this is the best approach, but it is quite tricky trying - // to figure out alhabetical vs. not across encoding. So take a very - // conservative approach. - -// if ( encoding == TIXML_ENCODING_UTF8 ) -// { - if ( anyByte < 127 ) - return isalpha( anyByte ); - else - return 1; // What else to do? The unicode set is huge...get the english ones right. -// } -// else -// { -// return isalpha( anyByte ); -// } -} - - -/*static*/ int TiXmlBase::IsAlphaNum( unsigned char anyByte, TiXmlEncoding /*encoding*/ ) -{ - // This will only work for low-ascii, everything else is assumed to be a valid - // letter. I'm not sure this is the best approach, but it is quite tricky trying - // to figure out alhabetical vs. not across encoding. So take a very - // conservative approach. - -// if ( encoding == TIXML_ENCODING_UTF8 ) -// { - if ( anyByte < 127 ) - return isalnum( anyByte ); - else - return 1; // What else to do? The unicode set is huge...get the english ones right. -// } -// else -// { -// return isalnum( anyByte ); -// } -} - - -class TiXmlParsingData -{ - friend class TiXmlDocument; - public: - void Stamp( const char* now, TiXmlEncoding encoding ); - - const TiXmlCursor& Cursor() { return cursor; } - - private: - // Only used by the document! - TiXmlParsingData( const char* start, int _tabsize, int row, int col ) - { - assert( start ); - stamp = start; - tabsize = _tabsize; - cursor.row = row; - cursor.col = col; - } - - TiXmlCursor cursor; - const char* stamp; - int tabsize; -}; - - -void TiXmlParsingData::Stamp( const char* now, TiXmlEncoding encoding ) -{ - assert( now ); - - // Do nothing if the tabsize is 0. - if ( tabsize < 1 ) - { - return; - } - - // Get the current row, column. - int row = cursor.row; - int col = cursor.col; - const char* p = stamp; - assert( p ); - - while ( p < now ) - { - // Treat p as unsigned, so we have a happy compiler. - const unsigned char* pU = (const unsigned char*)p; - - // Code contributed by Fletcher Dunn: (modified by lee) - switch (*pU) { - case 0: - // We *should* never get here, but in case we do, don't - // advance past the terminating null character, ever - return; - - case '\r': - // bump down to the next line - ++row; - col = 0; - // Eat the character - ++p; - - // Check for \r\n sequence, and treat this as a single character - if (*p == '\n') { - ++p; - } - break; - - case '\n': - // bump down to the next line - ++row; - col = 0; - - // Eat the character - ++p; - - // Check for \n\r sequence, and treat this as a single - // character. (Yes, this bizarre thing does occur still - // on some arcane platforms...) - if (*p == '\r') { - ++p; - } - break; - - case '\t': - // Eat the character - ++p; - - // Skip to next tab stop - col = (col / tabsize + 1) * tabsize; - break; - - case TIXML_UTF_LEAD_0: - if ( encoding == TIXML_ENCODING_UTF8 ) - { - if ( *(p+1) && *(p+2) ) - { - // In these cases, don't advance the column. These are - // 0-width spaces. - if ( *(pU+1)==TIXML_UTF_LEAD_1 && *(pU+2)==TIXML_UTF_LEAD_2 ) - p += 3; - else if ( *(pU+1)==0xbfU && *(pU+2)==0xbeU ) - p += 3; - else if ( *(pU+1)==0xbfU && *(pU+2)==0xbfU ) - p += 3; - else - { p +=3; ++col; } // A normal character. - } - } - else - { - ++p; - ++col; - } - break; - - default: - if ( encoding == TIXML_ENCODING_UTF8 ) - { - // Eat the 1 to 4 byte utf8 character. - int step = TiXmlBase::utf8ByteTable[*((const unsigned char*)p)]; - if ( step == 0 ) - step = 1; // Error case from bad encoding, but handle gracefully. - p += step; - - // Just advance one column, of course. - ++col; - } - else - { - ++p; - ++col; - } - break; - } - } - cursor.row = row; - cursor.col = col; - assert( cursor.row >= -1 ); - assert( cursor.col >= -1 ); - stamp = p; - assert( stamp ); -} - - -const char* TiXmlBase::SkipWhiteSpace( const char* p, TiXmlEncoding encoding ) -{ - if ( !p || !*p ) - { - return 0; - } - if ( encoding == TIXML_ENCODING_UTF8 ) - { - while ( *p ) - { - const unsigned char* pU = (const unsigned char*)p; - - // Skip the stupid Microsoft UTF-8 Byte order marks - if ( *(pU+0)==TIXML_UTF_LEAD_0 - && *(pU+1)==TIXML_UTF_LEAD_1 - && *(pU+2)==TIXML_UTF_LEAD_2 ) - { - p += 3; - continue; - } - else if(*(pU+0)==TIXML_UTF_LEAD_0 - && *(pU+1)==0xbfU - && *(pU+2)==0xbeU ) - { - p += 3; - continue; - } - else if(*(pU+0)==TIXML_UTF_LEAD_0 - && *(pU+1)==0xbfU - && *(pU+2)==0xbfU ) - { - p += 3; - continue; - } - - if ( IsWhiteSpace( *p ) ) // Still using old rules for white space. - ++p; - else - break; - } - } - else - { - while ( *p && IsWhiteSpace( *p ) ) - ++p; - } - - return p; -} - -#ifdef TIXML_USE_STL -/*static*/ bool TiXmlBase::StreamWhiteSpace( std::istream * in, TIXML_STRING * tag ) -{ - for( ;; ) - { - if ( !in->good() ) return false; - - int c = in->peek(); - // At this scope, we can't get to a document. So fail silently. - if ( !IsWhiteSpace( c ) || c <= 0 ) - return true; - - *tag += (char) in->get(); - } -} - -/*static*/ bool TiXmlBase::StreamTo( std::istream * in, int character, TIXML_STRING * tag ) -{ - //assert( character > 0 && character < 128 ); // else it won't work in utf-8 - while ( in->good() ) - { - int c = in->peek(); - if ( c == character ) - return true; - if ( c <= 0 ) // Silent failure: can't get document at this scope - return false; - - in->get(); - *tag += (char) c; - } - return false; -} -#endif - -// One of TinyXML's more performance demanding functions. Try to keep the memory overhead down. The -// "assign" optimization removes over 10% of the execution time. -// -const char* TiXmlBase::ReadName( const char* p, TIXML_STRING * name, TiXmlEncoding encoding ) -{ - // Oddly, not supported on some comilers, - //name->clear(); - // So use this: - *name = ""; - assert( p ); - - // Names start with letters or underscores. - // Of course, in unicode, tinyxml has no idea what a letter *is*. The - // algorithm is generous. - // - // After that, they can be letters, underscores, numbers, - // hyphens, or colons. (Colons are valid ony for namespaces, - // but tinyxml can't tell namespaces from names.) - if ( p && *p - && ( IsAlpha( (unsigned char) *p, encoding ) || *p == '_' ) ) - { - const char* start = p; - while( p && *p - && ( IsAlphaNum( (unsigned char ) *p, encoding ) - || *p == '_' - || *p == '-' - || *p == '.' - || *p == ':' ) ) - { - //(*name) += *p; // expensive - ++p; - } - if ( p-start > 0 ) { - name->assign( start, p-start ); - } - return p; - } - return 0; -} - -const char* TiXmlBase::GetEntity( const char* p, char* value, int* length, TiXmlEncoding encoding ) -{ - // Presume an entity, and pull it out. - TIXML_STRING ent; - int i; - *length = 0; - - if ( *(p+1) && *(p+1) == '#' && *(p+2) ) - { - unsigned long ucs = 0; - ptrdiff_t delta = 0; - unsigned mult = 1; - - if ( *(p+2) == 'x' ) - { - // Hexadecimal. - if ( !*(p+3) ) return 0; - - const char* q = p+3; - q = strchr( q, ';' ); - - if ( !q || !*q ) return 0; - - delta = q-p; - --q; - - while ( *q != 'x' ) - { - if ( *q >= '0' && *q <= '9' ) - ucs += mult * (*q - '0'); - else if ( *q >= 'a' && *q <= 'f' ) - ucs += mult * (*q - 'a' + 10); - else if ( *q >= 'A' && *q <= 'F' ) - ucs += mult * (*q - 'A' + 10 ); - else - return 0; - mult *= 16; - --q; - } - } - else - { - // Decimal. - if ( !*(p+2) ) return 0; - - const char* q = p+2; - q = strchr( q, ';' ); - - if ( !q || !*q ) return 0; - - delta = q-p; - --q; - - while ( *q != '#' ) - { - if ( *q >= '0' && *q <= '9' ) - ucs += mult * (*q - '0'); - else - return 0; - mult *= 10; - --q; - } - } - if ( encoding == TIXML_ENCODING_UTF8 ) - { - // convert the UCS to UTF-8 - ConvertUTF32ToUTF8( ucs, value, length ); - } - else - { - *value = (char)ucs; - *length = 1; - } - return p + delta + 1; - } - - // Now try to match it. - for( i=0; iappend( cArr, len ); - } - } - else - { - bool whitespace = false; - - // Remove leading white space: - p = SkipWhiteSpace( p, encoding ); - while ( p && *p - && !StringEqual( p, endTag, caseInsensitive, encoding ) ) - { - if ( *p == '\r' || *p == '\n' ) - { - whitespace = true; - ++p; - } - else if ( IsWhiteSpace( *p ) ) - { - whitespace = true; - ++p; - } - else - { - // If we've found whitespace, add it before the - // new character. Any whitespace just becomes a space. - if ( whitespace ) - { - (*text) += ' '; - whitespace = false; - } - int len; - char cArr[4] = { 0, 0, 0, 0 }; - p = GetChar( p, cArr, &len, encoding ); - if ( len == 1 ) - (*text) += cArr[0]; // more efficient - else - text->append( cArr, len ); - } - } - } - if ( p && *p ) - p += strlen( endTag ); - return p; -} - -#ifdef TIXML_USE_STL - -void TiXmlDocument::StreamIn( std::istream * in, TIXML_STRING * tag ) -{ - // The basic issue with a document is that we don't know what we're - // streaming. Read something presumed to be a tag (and hope), then - // identify it, and call the appropriate stream method on the tag. - // - // This "pre-streaming" will never read the closing ">" so the - // sub-tag can orient itself. - - if ( !StreamTo( in, '<', tag ) ) - { - SetError( TIXML_ERROR_PARSING_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN ); - return; - } - - while ( in->good() ) - { - int tagIndex = (int) tag->length(); - while ( in->good() && in->peek() != '>' ) - { - int c = in->get(); - if ( c <= 0 ) - { - SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN ); - break; - } - (*tag) += (char) c; - } - - if ( in->good() ) - { - // We now have something we presume to be a node of - // some sort. Identify it, and call the node to - // continue streaming. - TiXmlNode* node = Identify( tag->c_str() + tagIndex, TIXML_DEFAULT_ENCODING ); - - if ( node ) - { - node->StreamIn( in, tag ); - bool isElement = node->ToElement() != 0; - delete node; - node = 0; - - // If this is the root element, we're done. Parsing will be - // done by the >> operator. - if ( isElement ) - { - return; - } - } - else - { - SetError( TIXML_ERROR, 0, 0, TIXML_ENCODING_UNKNOWN ); - return; - } - } - } - // We should have returned sooner. - SetError( TIXML_ERROR, 0, 0, TIXML_ENCODING_UNKNOWN ); -} - -#endif - -const char* TiXmlDocument::Parse( const char* p, TiXmlParsingData* prevData, TiXmlEncoding encoding ) -{ - ClearError(); - - // Parse away, at the document level. Since a document - // contains nothing but other tags, most of what happens - // here is skipping white space. - if ( !p || !*p ) - { - SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN ); - return 0; - } - - // Note that, for a document, this needs to come - // before the while space skip, so that parsing - // starts from the pointer we are given. - location.Clear(); - if ( prevData ) - { - location.row = prevData->cursor.row; - location.col = prevData->cursor.col; - } - else - { - location.row = 0; - location.col = 0; - } - TiXmlParsingData data( p, TabSize(), location.row, location.col ); - location = data.Cursor(); - - if ( encoding == TIXML_ENCODING_UNKNOWN ) - { - // Check for the Microsoft UTF-8 lead bytes. - const unsigned char* pU = (const unsigned char*)p; - if ( *(pU+0) && *(pU+0) == TIXML_UTF_LEAD_0 - && *(pU+1) && *(pU+1) == TIXML_UTF_LEAD_1 - && *(pU+2) && *(pU+2) == TIXML_UTF_LEAD_2 ) - { - encoding = TIXML_ENCODING_UTF8; - useMicrosoftBOM = true; - } - } - - p = SkipWhiteSpace( p, encoding ); - if ( !p ) - { - SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN ); - return 0; - } - - while ( p && *p ) - { - TiXmlNode* node = Identify( p, encoding ); - if ( node ) - { - p = node->Parse( p, &data, encoding ); - LinkEndChild( node ); - } - else - { - break; - } - - // Did we get encoding info? - if ( encoding == TIXML_ENCODING_UNKNOWN - && node->ToDeclaration() ) - { - TiXmlDeclaration* dec = node->ToDeclaration(); - const char* enc = dec->Encoding(); - assert( enc ); - - if ( *enc == 0 ) - encoding = TIXML_ENCODING_UTF8; - else if ( StringEqual( enc, "UTF-8", true, TIXML_ENCODING_UNKNOWN ) ) - encoding = TIXML_ENCODING_UTF8; - else if ( StringEqual( enc, "UTF8", true, TIXML_ENCODING_UNKNOWN ) ) - encoding = TIXML_ENCODING_UTF8; // incorrect, but be nice - else - encoding = TIXML_ENCODING_LEGACY; - } - - p = SkipWhiteSpace( p, encoding ); - } - - // Was this empty? - if ( !firstChild ) { - SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, encoding ); - return 0; - } - - // All is well. - return p; -} - -void TiXmlDocument::SetError( int err, const char* pError, TiXmlParsingData* data, TiXmlEncoding encoding ) -{ - // The first error in a chain is more accurate - don't set again! - if ( error ) - return; - - assert( err > 0 && err < TIXML_ERROR_STRING_COUNT ); - error = true; - errorId = err; - errorDesc = errorString[ errorId ]; - - errorLocation.Clear(); - if ( pError && data ) - { - data->Stamp( pError, encoding ); - errorLocation = data->Cursor(); - } -} - - -TiXmlNode* TiXmlNode::Identify( const char* p, TiXmlEncoding encoding ) -{ - TiXmlNode* returnNode = 0; - - p = SkipWhiteSpace( p, encoding ); - if( !p || !*p || *p != '<' ) - { - return 0; - } - - p = SkipWhiteSpace( p, encoding ); - - if ( !p || !*p ) - { - return 0; - } - - // What is this thing? - // - Elements start with a letter or underscore, but xml is reserved. - // - Comments: "; - - if ( !StringEqual( p, startTag, false, encoding ) ) - { - document->SetError( TIXML_ERROR_PARSING_COMMENT, p, data, encoding ); - return 0; - } - p += strlen( startTag ); - - // [ 1475201 ] TinyXML parses entities in comments - // Oops - ReadText doesn't work, because we don't want to parse the entities. - // p = ReadText( p, &value, false, endTag, false, encoding ); - // - // from the XML spec: - /* - [Definition: Comments may appear anywhere in a document outside other markup; in addition, - they may appear within the document type declaration at places allowed by the grammar. - They are not part of the document's character data; an XML processor MAY, but need not, - make it possible for an application to retrieve the text of comments. For compatibility, - the string "--" (double-hyphen) MUST NOT occur within comments.] Parameter entity - references MUST NOT be recognized within comments. - - An example of a comment: - - - */ - - value = ""; - // Keep all the white space. - while ( p && *p && !StringEqual( p, endTag, false, encoding ) ) - { - value.append( p, 1 ); - ++p; - } - if ( p && *p ) - p += strlen( endTag ); - - return p; -} - - -const char* TiXmlAttribute::Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ) -{ - p = SkipWhiteSpace( p, encoding ); - if ( !p || !*p ) return 0; - - if ( data ) - { - data->Stamp( p, encoding ); - location = data->Cursor(); - } - // Read the name, the '=' and the value. - const char* pErr = p; - p = ReadName( p, &name, encoding ); - if ( !p || !*p ) - { - if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES, pErr, data, encoding ); - return 0; - } - p = SkipWhiteSpace( p, encoding ); - if ( !p || !*p || *p != '=' ) - { - if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES, p, data, encoding ); - return 0; - } - - ++p; // skip '=' - p = SkipWhiteSpace( p, encoding ); - if ( !p || !*p ) - { - if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES, p, data, encoding ); - return 0; - } - - const char* end; - const char SINGLE_QUOTE = '\''; - const char DOUBLE_QUOTE = '\"'; - - if ( *p == SINGLE_QUOTE ) - { - ++p; - end = "\'"; // single quote in string - p = ReadText( p, &value, false, end, false, encoding ); - } - else if ( *p == DOUBLE_QUOTE ) - { - ++p; - end = "\""; // double quote in string - p = ReadText( p, &value, false, end, false, encoding ); - } - else - { - // All attribute values should be in single or double quotes. - // But this is such a common error that the parser will try - // its best, even without them. - value = ""; - while ( p && *p // existence - && !IsWhiteSpace( *p ) // whitespace - && *p != '/' && *p != '>' ) // tag end - { - if ( *p == SINGLE_QUOTE || *p == DOUBLE_QUOTE ) { - // [ 1451649 ] Attribute values with trailing quotes not handled correctly - // We did not have an opening quote but seem to have a - // closing one. Give up and throw an error. - if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES, p, data, encoding ); - return 0; - } - value += *p; - ++p; - } - } - return p; -} - -#ifdef TIXML_USE_STL -void TiXmlText::StreamIn( std::istream * in, TIXML_STRING * tag ) -{ - while ( in->good() ) - { - int c = in->peek(); - if ( !cdata && (c == '<' ) ) - { - return; - } - if ( c <= 0 ) - { - TiXmlDocument* document = GetDocument(); - if ( document ) - document->SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN ); - return; - } - - (*tag) += (char) c; - in->get(); // "commits" the peek made above - - if ( cdata && c == '>' && tag->size() >= 3 ) { - size_t len = tag->size(); - if ( (*tag)[len-2] == ']' && (*tag)[len-3] == ']' ) { - // terminator of cdata. - return; - } - } - } -} -#endif - -const char* TiXmlText::Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ) -{ - value = ""; - TiXmlDocument* document = GetDocument(); - - if ( data ) - { - data->Stamp( p, encoding ); - location = data->Cursor(); - } - - const char* const startTag = ""; - - if ( cdata || StringEqual( p, startTag, false, encoding ) ) - { - cdata = true; - - if ( !StringEqual( p, startTag, false, encoding ) ) - { - document->SetError( TIXML_ERROR_PARSING_CDATA, p, data, encoding ); - return 0; - } - p += strlen( startTag ); - - // Keep all the white space, ignore the encoding, etc. - while ( p && *p - && !StringEqual( p, endTag, false, encoding ) - ) - { - value += *p; - ++p; - } - - TIXML_STRING dummy; - p = ReadText( p, &dummy, false, endTag, false, encoding ); - return p; - } - else - { - bool ignoreWhite = true; - - const char* end = "<"; - p = ReadText( p, &value, ignoreWhite, end, false, encoding ); - if ( p ) - return p-1; // don't truncate the '<' - return 0; - } -} - -#ifdef TIXML_USE_STL -void TiXmlDeclaration::StreamIn( std::istream * in, TIXML_STRING * tag ) -{ - while ( in->good() ) - { - int c = in->get(); - if ( c <= 0 ) - { - TiXmlDocument* document = GetDocument(); - if ( document ) - document->SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN ); - return; - } - (*tag) += (char) c; - - if ( c == '>' ) - { - // All is well. - return; - } - } -} -#endif - -const char* TiXmlDeclaration::Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding _encoding ) -{ - p = SkipWhiteSpace( p, _encoding ); - // Find the beginning, find the end, and look for - // the stuff in-between. - TiXmlDocument* document = GetDocument(); - if ( !p || !*p || !StringEqual( p, "SetError( TIXML_ERROR_PARSING_DECLARATION, 0, 0, _encoding ); - return 0; - } - if ( data ) - { - data->Stamp( p, _encoding ); - location = data->Cursor(); - } - p += 5; - - version = ""; - encoding = ""; - standalone = ""; - - while ( p && *p ) - { - if ( *p == '>' ) - { - ++p; - return p; - } - - p = SkipWhiteSpace( p, _encoding ); - if ( StringEqual( p, "version", true, _encoding ) ) - { - TiXmlAttribute attrib; - p = attrib.Parse( p, data, _encoding ); - version = attrib.Value(); - } - else if ( StringEqual( p, "encoding", true, _encoding ) ) - { - TiXmlAttribute attrib; - p = attrib.Parse( p, data, _encoding ); - encoding = attrib.Value(); - } - else if ( StringEqual( p, "standalone", true, _encoding ) ) - { - TiXmlAttribute attrib; - p = attrib.Parse( p, data, _encoding ); - standalone = attrib.Value(); - } - else - { - // Read over whatever it is. - while( p && *p && *p != '>' && !IsWhiteSpace( *p ) ) - ++p; - } - } - return 0; -} - -bool TiXmlText::Blank() const -{ - for ( unsigned i=0; i -#include - -#ifdef _VAA3D_TERAFLY_PLUGIN_MODE -#include -#include "PLog.h" -#include "COperation.h" -#endif - -/******************************************************************************************************* -* Volume formats supported: -* -* SimpleVolume: simple sequence of slices stored as 2D images in the same directory -* StackedVolume: bidimensional matrix of 3D stacks stored in a hierarchical structure of directories -* -*******************************************************************************************************/ -#include "../imagemanager/SimpleVolume.h" -#include "../imagemanager/SimpleVolumeRaw.h" -#include "../imagemanager/RawVolume.h" -#include "../imagemanager/TiledVolume.h" -#include "../imagemanager/TiledMCVolume.h" -#include "../imagemanager/StackedVolume.h" -#include "../imagemanager/TimeSeries.h" -/******************************************************************************************************/ - -#include "../imagemanager/Tiff3DMngr.h" -#include "../imagemanager/HDF5Mngr.h" - -#include -#include -#include -#include -#include -#include "resumer.h" - -using namespace iim; - -VolumeConverter::VolumeConverter( ) -{ - /**/iim::debug(iim::LEV3, 0, __iim__current__function__); - - volume = (VirtualVolume *) 0; -} - - -VolumeConverter::~VolumeConverter() -{ - /**/iim::debug(iim::LEV3, 0, __iim__current__function__); - - if(volume) - delete volume; -} - - -void VolumeConverter::setSrcVolume(const char* _root_dir, const char* _fmt, const char* _out_fmt, bool time_series /* = false */) throw (IOException) -{ - /**/iim::debug(iim::LEV3, strprintf("_root_dir = %s, _fmt = %s, _out_fmt = %s, time_series = %s", - _root_dir, _fmt, _out_fmt, time_series ? "true" : "false").c_str(), __iim__current__function__); - - if(time_series) - volume = new TimeSeries(_root_dir, _fmt); - else - //volume = VirtualVolume::instance(_root_dir, _fmt, vertical, horizontal, depth, 1.0f, 1.0f, 1.0f); - //volume = VirtualVolume::instance_format(_root_dir); - // 2015-04-14. Alessandro. @FIXED misleading usage of 'VirtualVolume::instance' w/o format argument in 'setSrcVolume' - volume = VirtualVolume::instance_format(_root_dir, _fmt); - - // 2015-04-14 Alessandro. @FIXED bug-crash when the volume has not been imported correctly in setSrcVolume. - if(!volume) - throw iim::IOException(iim::strprintf("in VolumeConverter::setSrcVolume(): unable to recognize the volume format of \"%s\"", _root_dir)); - - //channels = (volume->getDIM_C()>1) ? 3 : 1; // only 1 or 3 channels supported - channels = volume->getDIM_C(); - - if ( strcmp(_out_fmt,REAL_REPRESENTATION) == 0 ) { - if ( channels > 1 ) { - fprintf(stderr,"*** warning *** more than 1 channel, the internal representation has been changed\n"); - out_fmt = UINT8x3_REPRESENTATION; - internal_rep = UINT8_INTERNAL_REP; - } - else { - out_fmt = _out_fmt; - internal_rep = REAL_INTERNAL_REP; - } - } - else if ( strcmp(_out_fmt,UINT8_REPRESENTATION) == 0 ) { - out_fmt = _out_fmt; - internal_rep = UINT8_INTERNAL_REP; - } - else if ( strcmp(_out_fmt,UINT8x3_REPRESENTATION) == 0 ) { - out_fmt = _out_fmt; - internal_rep = UINT8_INTERNAL_REP; - } - else { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"VolumeConverter::setSrcVolume: unsupported output format (%s)",out_fmt); - throw IOException(err_msg); - } - - V0 = 0; - H0 = 0; - D0 = 0; - V1 = volume->getDIM_V(); - H1 = volume->getDIM_H(); - D1 = volume->getDIM_D(); -} - - -/************************************************************************************************************* -* Method to be called for tile generation. <> parameters are mandatory, while [] are optional. -* : absolute directory path where generted tiles have to be stored. -* [resolutions] : pointer to an array of S_MAX_MULTIRES size which boolean entries identify the acti- -* vaction/deactivation of the i-th resolution. If not given, all resolutions will be -* activated. -* [slice_height/width] : desired dimensions of tiles slices after merging. It is actually an upper-bound of -* the actual slice dimensions, which will be computed in such a way that all tiles di- -* mensions can differ by 1 pixel only along both directions. If not given, the maximum -* allowed dimensions will be set, which will result in a volume composed by one large -* tile only. -* [show_progress_bar] : enables/disables progress bar with estimated time remaining. -* [saved_img_format] : determines saved images format ("png","tif","jpeg", etc.). -* [saved_img_depth] : determines saved images bitdepth (16 or 8). -**************************************************************************************************************/ -void VolumeConverter::generateTiles(std::string output_path, bool* resolutions, - int slice_height, int slice_width, int method, bool show_progress_bar, const char* saved_img_format, - int saved_img_depth, std::string frame_dir) throw (IOException) -{ - printf("in VolumeConverter::generateTiles(path = \"%s\", resolutions = ", output_path.c_str()); - for(int i=0; i< TMITREE_MAX_HEIGHT; i++) - printf("%d", resolutions[i]); - printf(", slice_height = %d, slice_width = %d, method = %d, show_progress_bar = %s, saved_img_format = %s, saved_img_depth = %d, frame_dir = \"%s\")\n", - slice_height, slice_width, method, show_progress_bar ? "true" : "false", saved_img_format, saved_img_depth, frame_dir.c_str()); - - if ( saved_img_depth == 0 ) // default value: output depth is the same of input depth - saved_img_depth = (volume->getBYTESxCHAN() * 8); - - if ( saved_img_depth != 8 && volume->getNACtiveChannels() > 1) { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"VolumeConverter::generateTilesVaa3DRaw: %d bits per channel of destination is not supported for %d channels", - saved_img_depth, volume->getNACtiveChannels()); - throw IOException(err_msg); - } - - if ( saved_img_depth != (volume->getBYTESxCHAN() * 8) ) { // saveImage_from and saveImage_from_UINT8 do not support depth conversion yet - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"VolumeConverter::generateTilesVaa3DRaw: a mismatch between bits per channel of source (%d) and destination (%d) is not supported", - volume->getBYTESxCHAN() * 8, saved_img_depth); - throw IOException(err_msg); - } - - //LOCAL VARIABLES - sint64 height, width, depth; //height, width and depth of the whole volume that covers all stacks - real32* rbuffer; //buffer where temporary image data are stored (REAL_INTERNAL_REP) - uint8** ubuffer; //array of buffers where temporary image data of channels are stored (UINT8_INTERNAL_REP) - int bytes_chan = volume->getBYTESxCHAN(); - //uint8* ubuffer_ch2; //buffer temporary image data of channel 1 are stored (UINT8_INTERNAL_REP) - //uint8* ubuffer_ch3; //buffer temporary image data of channel 1 are stored (UINT8_INTERNAL_REP) - int org_channels = 0; //store the number of channels read the first time (for checking purposes) - int supported_channels; //channels to be supported (stacks of tiffs 2D only supports 1 or 3 channels) - // real32* stripe_up=NULL; //will contain up-stripe and down-stripe computed by calling 'getStripe' method (unused) - sint64 z_ratio, z_max_res; - int n_stacks_V[TMITREE_MAX_HEIGHT], n_stacks_H[TMITREE_MAX_HEIGHT]; //array of number of tiles along V and H directions respectively at i-th resolution - int **stacks_height[TMITREE_MAX_HEIGHT], **stacks_width[TMITREE_MAX_HEIGHT]; //array of matrices of tiles dimensions at i-th resolution - std::stringstream file_path[TMITREE_MAX_HEIGHT]; //array of root directory name at i-th resolution - int resolutions_size = 0; - - if ( volume == 0 ) { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"VolumeConverter::generateTiles: undefined source volume"); - throw IOException(err_msg); - } - - //initializing the progress bar - char progressBarMsg[200]; - if(show_progress_bar) - { - imProgressBar::getInstance()->start("Multiresolution tile generation"); - imProgressBar::getInstance()->update(0,"Initializing..."); - imProgressBar::getInstance()->show(); - } - - // 2015-03-03. Giulio. @ADDED selection of IO plugin if not provided. - if(iom::IMOUT_PLUGIN.compare("empty") == 0) - { - iom::IMOUT_PLUGIN = "tiff2D"; - } - - //computing dimensions of volume to be stitched - //this->computeVolumeDims(exclude_nonstitchable_stacks, _ROW_START, _ROW_END, _COL_START, _COL_END, _D0, _D1); - width = this->H1-this->H0; - height = this->V1-this->V0; - depth = this->D1-this->D0; - - //activating resolutions - slice_height = (slice_height == -1 ? (int)height : slice_height); - slice_width = (slice_width == -1 ? (int)width : slice_width); - if(slice_height < TMITREE_MIN_BLOCK_DIM || slice_width < TMITREE_MIN_BLOCK_DIM) - { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"The minimum dimension for both slice width and height is %d", TMITREE_MIN_BLOCK_DIM); - throw IOException(err_msg); - } - if(resolutions == NULL) - { - resolutions = new bool; - *resolutions = true; - resolutions_size = 1; - } - else - for(int i=0; i 3 ) { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"The volume contains too many channels (%d)", channels); - throw IOException(err_msg); - } - - //allocated even if not used - org_channels = channels; // save for checks - supported_channels = (channels>1) ? 3 : 1; // only 1 or 3 channels supported if output format is stacks of tiffs 2D - ubuffer = new uint8 *[supported_channels]; - memset(ubuffer,0,supported_channels*sizeof(uint8 *)); // initializes to null pointers - - for(sint64 z = this->D0, z_parts = 1; z < this->D1; z += z_max_res, z_parts++) - { - // fill one slice block - if ( internal_rep == REAL_INTERNAL_REP ) - rbuffer = volume->loadSubvolume_to_real32(V0,V1,H0,H1,(int)(z-D0),(z-D0+z_max_res <= D1) ? (int)(z-D0+z_max_res) : D1); - else { // internal_rep == UINT8_INTERNAL_REP - ubuffer[0] = volume->loadSubvolume_to_UINT8(V0,V1,H0,H1,(int)(z-D0),(z-D0+z_max_res <= D1) ? (int)(z-D0+z_max_res) : D1,&channels,iim::NATIVE_RTYPE); - // WARNING: next code assumes that channels is 1 or 3, but implementations of loadSubvolume_to_UINT8 do not guarantee this condition - if ( org_channels != channels ) { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"The volume contains images with a different number of channels (%d,%d)", org_channels, channels); - throw IOException(err_msg); - } - - // code has been changed because the load operation can return 1, 2 or 3 channels - /* - if ( supported_channels == 3 ) { - // offsets are to be computed taking into account that buffer size along D may be different - ubuffer[1] = ubuffer[0] + (height * width * ((z_parts<=z_ratio) ? z_max_res : (depth%z_max_res))); - ubuffer[2] = ubuffer[1] + (height * width * ((z_parts<=z_ratio) ? z_max_res : (depth%z_max_res))); - } - */ - // elements of ubuffer not set are null pointers - for ( int c=1; cupdate(((float)(z-D0+z_max_res-1)*100/(float)depth), progressBarMsg); - imProgressBar::getInstance()->show(); - } - - //saving current buffer data at selected resolutions and in multitile format - for(int i=0; i< resolutions_size; i++) - { - if(show_progress_bar) - { - sprintf(progressBarMsg, "Generating resolution %d of %d",i+1,std::max(resolutions_size, resolutions_size)); - imProgressBar::getInstance()->updateInfo(progressBarMsg); - imProgressBar::getInstance()->show(); - } - - //buffer size along D is different when the remainder of the subdivision by z_max_res is considered - sint64 z_size = (z_parts<=z_ratio) ? z_max_res : (depth%z_max_res); - - //halvesampling resolution if current resolution is not the deepest one - if(i!=0) { - if ( internal_rep == REAL_INTERNAL_REP ) - VirtualVolume::halveSample(rbuffer,(int)height/(powInt(2,i-1)),(int)width/(powInt(2,i-1)),(int)z_size/(powInt(2,i-1)),method); - else // internal_rep == UINT8_INTERNAL_REP - VirtualVolume::halveSample_UINT8(ubuffer,(int)height/(powInt(2,i-1)),(int)width/(powInt(2,i-1)),(int)z_size/(powInt(2,i-1)),channels,method,bytes_chan); - } - - //saving at current resolution if it has been selected and iff buffer is at least 1 voxel (Z) deep - if(resolutions[i] && (z_size/(powInt(2,i))) > 0) - { - if(show_progress_bar) - { - sprintf(progressBarMsg, "Saving to disc resolution %d",i+1); - imProgressBar::getInstance()->updateInfo(progressBarMsg); - imProgressBar::getInstance()->show(); - } - - //storing in 'base_path' the absolute path of the directory that will contain all stacks - std::stringstream base_path; - base_path << output_path << "/RES(" << (int)(height/powInt(2,i)) << "x" << (int)(width/powInt(2,i)) << "x" << (int)(depth/powInt(2,i)) << ")/"; - - //if frame_dir not empty must create frame directory - if ( frame_dir != "" ) { - base_path << frame_dir << "/"; - if(!check_and_make_dir(base_path.str().c_str())) - { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg, "in generateTiles(...): unable to create DIR = \"%s\"\n", base_path.str().c_str()); - throw IOException(err_msg); - } - } - - //looping on new stacks - for(int stack_row = 0, start_height = 0, end_height = 0; stack_row < n_stacks_V[i]; stack_row++) - { - //incrementing end_height - end_height = start_height + stacks_height[i][stack_row][0]-1; - - //computing V_DIR_path and creating the directory the first time it is needed - std::stringstream V_DIR_path; - V_DIR_path << base_path.str() << this->getMultiresABS_V_string(i,start_height); - if(z==D0 && !check_and_make_dir(V_DIR_path.str().c_str())) - { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg, "in mergeTiles(...): unable to create V_DIR = \"%s\"\n", V_DIR_path.str().c_str()); - throw IOException(err_msg); - } - - for(int stack_column = 0, start_width=0, end_width=0; stack_column < n_stacks_H[i]; stack_column++) - { - end_width = start_width + stacks_width [i][stack_row][stack_column]-1; - - //computing H_DIR_path and creating the directory the first time it is needed - std::stringstream H_DIR_path; - H_DIR_path << V_DIR_path.str() << "/" << this->getMultiresABS_V_string(i,start_height) << "_" << this->getMultiresABS_H_string(i,start_width); - - if(z==D0 && !check_and_make_dir(H_DIR_path.str().c_str())) - { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg, "in mergeTiles(...): unable to create H_DIR = \"%s\"\n", H_DIR_path.str().c_str()); - throw IOException(err_msg); - } - - //saving HERE - for(int buffer_z=0; buffer_zgetMultiresABS_D(i) + // all stacks start at the same D position - (powInt(2,i)*buffer_z+z) * volume->getVXL_D()); - img_path << H_DIR_path.str() << "/" - << this->getMultiresABS_V_string(i,start_height) << "_" - << this->getMultiresABS_H_string(i,start_width) << "_" - << abs_pos_z.str(); - if ( internal_rep == REAL_INTERNAL_REP ) - VirtualVolume::saveImage(img_path.str(), - rbuffer + buffer_z*(height/powInt(2,i))*(width/powInt(2,i)), // adds the stride - (int)height/(powInt(2,i)),(int)width/(powInt(2,i)), - start_height,end_height,start_width,end_width, - saved_img_format, saved_img_depth); - else // internal_rep == UINT8_INTERNAL_REP - if ( channels == 1 ) - VirtualVolume::saveImage_from_UINT8(img_path.str(), - ubuffer[0] + buffer_z*(height/powInt(2,i))*(width/powInt(2,i)), // adds the stride - (uint8 *) 0, - (uint8 *) 0, - (int)height/(powInt(2,i)),(int)width/(powInt(2,i)), - start_height,end_height,start_width,end_width, - saved_img_format, saved_img_depth); - else if ( channels == 2 ) - VirtualVolume::saveImage_from_UINT8(img_path.str(), - ubuffer[0] + buffer_z*(height/powInt(2,i))*(width/powInt(2,i))*bytes_chan, // stride to be added for slice buffer_z - ubuffer[1] + buffer_z*(height/powInt(2,i))*(width/powInt(2,i))*bytes_chan, // stride to be added for slice buffer_z - (uint8 *) 0, - (int)height/(powInt(2,i)),(int)width/(powInt(2,i)), - start_height,end_height,start_width,end_width, - saved_img_format, saved_img_depth); - else // channels = 3 - VirtualVolume::saveImage_from_UINT8(img_path.str(), - ubuffer[0] + buffer_z*(height/powInt(2,i))*(width/powInt(2,i))*bytes_chan, // stride to be added for slice buffer_z - ubuffer[1] + buffer_z*(height/powInt(2,i))*(width/powInt(2,i))*bytes_chan, // stride to be added for slice buffer_z - ubuffer[2] + buffer_z*(height/powInt(2,i))*(width/powInt(2,i))*bytes_chan, // stride to be added for slice buffer_z - (int)height/(powInt(2,i)),(int)width/(powInt(2,i)), - start_height,end_height,start_width,end_width, - saved_img_format, saved_img_depth); - } - start_width += stacks_width [i][stack_row][stack_column]; - } - start_height += stacks_height[i][stack_row][0]; - } - } - } - - //releasing allocated memory - if ( internal_rep == REAL_INTERNAL_REP ) - delete rbuffer; - else // internal_rep == UINT8_INTERNAL_REP - delete ubuffer[0]; // other buffer pointers are only offsets - } - - // reloads created volumes to generate .bin file descriptors at all resolutions - ref_sys reference(axis(1),axis(2),axis(3)); - TiledMCVolume *mcprobe; - TiledVolume *tprobe; - StackedVolume *sprobe; - sprobe = dynamic_cast(volume); - if ( sprobe ) { - reference.first = sprobe->getAXS_1(); - reference.second = sprobe->getAXS_2(); - reference.third = sprobe->getAXS_3(); - } - else { - tprobe = dynamic_cast(volume); - if ( tprobe ) { - reference.first = tprobe->getAXS_1(); - reference.second = tprobe->getAXS_2(); - reference.third = tprobe->getAXS_3(); - } - else { - mcprobe = dynamic_cast(volume); - if ( mcprobe ) { - reference.first = mcprobe->getAXS_1(); - reference.second = mcprobe->getAXS_2(); - reference.third = mcprobe->getAXS_3(); - } - } - } - for(int res_i=0; res_i< resolutions_size; res_i++) { - if(resolutions[res_i]) - { - //---- Alessandro 2013-04-22 partial fix: wrong voxel size computation. In addition, the predefined reference system {1,2,3} may not be the right - //one when dealing with CLSM data. The right reference system is stored in the object. A possible solution to implement - //is to check whether is a pointer to a object, then specialize it to and get its reference - //system. - //---- Giulio 2013-08-23 fixed - StackedVolume temp_vol(file_path[res_i].str().c_str(),reference, - volume->getVXL_V()*pow(2.0f,res_i), volume->getVXL_H()*pow(2.0f,res_i),volume->getVXL_D()*pow(2.0f,res_i)); - -// StackedVolume temp_vol(file_path[res_i].str().c_str(),ref_sys(axis(1),axis(2),axis(3)), volume->getVXL_V()*(res_i+1), -// volume->getVXL_H()*(res_i+1),volume->getVXL_D()*(res_i+1)); - } - } - - - // ubuffer allocated anyway - delete ubuffer; - - // deallocate memory - for(int res_i=0; res_i< resolutions_size; res_i++) - { - for(int stack_row = 0; stack_row < n_stacks_V[res_i]; stack_row++) - { - delete []stacks_height[res_i][stack_row]; - delete []stacks_width [res_i][stack_row]; - } - delete []stacks_height[res_i]; - delete []stacks_width[res_i]; - } -} - - -/************************************************************************************************************* -* Method to be called for tile generation in Vaa3D raw format. <> parameters are mandatory, while [] are optional. -* : absolute directory path where generted tiles have to be stored. -* [resolutions] : pointer to an array of S_MAX_MULTIRES size which boolean entries identify the acti- -* vaction/deactivation of the i-th resolution. If not given, all resolutions will be -* activated. -* [block_height] : desired dimensions of tiled blocks after merging. It is actually an upper-bound of -* [block_width] the actual slice dimensions, which will be computed in such a way that all tiles di- -* [block_depth] mensions can differ by 1 pixel only along both directions. If not given, the maximum -* allowed dimensions will be set, which will result in a volume composed by one large -* tile only. -* [show_progress_bar] : enables/disables progress bar with estimated time remaining. -* [saved_img_format] : determines saved images format ("png","tif","jpeg", etc.). -* [saved_img_depth] : determines saved images bitdepth (16 or 8). -**************************************************************************************************************/ -void VolumeConverter::generateTilesVaa3DRaw(std::string output_path, bool* resolutions, - int block_height, int block_width, int block_depth, int method, - bool show_progress_bar, const char* saved_img_format, - int saved_img_depth, std::string frame_dir) throw (IOException) -{ - printf("in VolumeConverter::generateTilesVaa3DRaw(path = \"%s\", resolutions = ", output_path.c_str()); - for(int i=0; i< TMITREE_MAX_HEIGHT; i++) - printf("%d", resolutions[i]); - printf(", block_height = %d, block_width = %d, block_depth = %d, method = %d, show_progress_bar = %s, saved_img_format = %s, saved_img_depth = %d, frame_dir = \"%s\")\n", - block_height, block_width, block_depth, method, show_progress_bar ? "true" : "false", saved_img_format, saved_img_depth, frame_dir.c_str()); - - if ( saved_img_depth == 0 ) // default is to generate an image with the same depth of the source - saved_img_depth = volume->getBYTESxCHAN() * 8; - - if ( saved_img_depth != (volume->getBYTESxCHAN() * 8) ) { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"VolumeConverter::generateTilesVaa3DRaw: mismatch between bits per channel of source (%d) and destination (%d)", - volume->getBYTESxCHAN() * 8, saved_img_depth); - throw IOException(err_msg); - } - - //LOCAL VARIABLES - sint64 height, width, depth; //height, width and depth of the whole volume that covers all stacks - real32* rbuffer; //buffer where temporary image data are stored (REAL_INTERNAL_REP) - uint8** ubuffer; //array of buffers where temporary image data of channels are stored (UINT8_INTERNAL_REP) - int bytes_chan = volume->getBYTESxCHAN(); - //uint8* ubuffer_ch2; //buffer temporary image data of channel 1 are stored (UINT8_INTERNAL_REP) - //uint8* ubuffer_ch3; //buffer temporary image data of channel 1 are stored (UINT8_INTERNAL_REP) - int org_channels = 0; //store the number of channels read the first time (for checking purposes) - //real32* stripe_up=NULL; //will contain up-stripe and down-stripe computed by calling 'getStripe' method (unused) - sint64 z_ratio, z_max_res; - int n_stacks_V[TMITREE_MAX_HEIGHT]; //arrays of number of tiles along V, H and D directions respectively at i-th resolution - int n_stacks_H[TMITREE_MAX_HEIGHT]; - int n_stacks_D[TMITREE_MAX_HEIGHT]; - int ***stacks_height[TMITREE_MAX_HEIGHT]; //array of matrices of tiles dimensions at i-th resolution - int ***stacks_width[TMITREE_MAX_HEIGHT]; - int ***stacks_depth[TMITREE_MAX_HEIGHT]; - std::stringstream file_path[TMITREE_MAX_HEIGHT]; //array of root directory name at i-th resolution - int resolutions_size = 0; - - /* DEFINITIONS OF VARIABILES THAT MANAGE TILES (BLOCKS) ALONG D-direction - * In the following the term 'group' means the groups of slices that are - * processed together to generate slices of all resolution requested - */ - - /* stack_block[i] is the index of current block along z (it depends on the resolution i) - * current block is the block in which falls the first slice of the group - * of slices that is currently being processed, i.e. from z to z+z_max_res-1 - */ - int stack_block[TMITREE_MAX_HEIGHT]; - - /* these arrays are the indices of first and last slice of current block at resolution i - * WARNING: the slice index refers to the index of the slice in the volume at resolution i - */ - int slice_start[TMITREE_MAX_HEIGHT]; - int slice_end[TMITREE_MAX_HEIGHT]; - - /* the number of slice of already processed groups at current resolution - * the index of the slice to be saved at current resolution is: - * - * n_slices_pred + z_buffer - */ - sint64 n_slices_pred; - - if ( volume == 0 ) { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"VolumeConverter::generateTilesVaa3DRaw: undefined source volume"); - throw IOException(err_msg); - } - - //initializing the progress bar - char progressBarMsg[200]; - if(show_progress_bar) - { - imProgressBar::getInstance()->start("Multiresolution tile generation"); - imProgressBar::getInstance()->update(0,"Initializing..."); - imProgressBar::getInstance()->show(); - } - - // 2015-03-03. Giulio. @ADDED selection of IO plugin if not provided. - if(iom::IMOUT_PLUGIN.compare("empty") == 0) - { - iom::IMOUT_PLUGIN = "tiff3D"; - } - - //computing dimensions of volume to be stitched - //this->computeVolumeDims(exclude_nonstitchable_stacks, _ROW_START, _ROW_END, _COL_START, _COL_END, _D0, _D1); - width = this->H1-this->H0; - height = this->V1-this->V0; - depth = this->D1-this->D0; - - // code for testing - //uint8 *temp = volume->loadSubvolume_to_UINT8( - // 10,height-10,10,width-10,10,depth-10, - // &channels); - - //activating resolutions - block_height = (block_height == -1 ? (int)height : block_height); - block_width = (block_width == -1 ? (int)width : block_width); - block_depth = (block_depth == -1 ? (int)depth : block_depth); - if(block_height < TMITREE_MIN_BLOCK_DIM || block_width < TMITREE_MIN_BLOCK_DIM /* 2014-11-10. Giulio. @REMOVED (|| block_depth < TMITREE_MIN_BLOCK_DIM) */) - { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"The minimum dimension for block height, width, and depth is %d", TMITREE_MIN_BLOCK_DIM); - throw IOException(err_msg); - } - - if(resolutions == NULL) - { - resolutions = new bool; - *resolutions = true; - resolutions_size = 1; - } - else - for(int i=0; i D and hence: - * - * D >= B >= floor(D/2) - * since it is: - * - * 1/ceil(H/D) = 1/(H/D + alpha) = D/(H + alpha * D) > D/(2 * H) - * where alpha<1. - */ - - //ALLOCATING the MEMORY SPACE for image buffer - z_max_res = powInt(2,resolutions_size-1); - if ( z_max_res > block_depth/2 ) { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg, "in generateTilesVaa3DRaw(...): too much resolutions(%d): too much slices (%lld) in the buffer \n", resolutions_size, z_max_res); - throw IOException(err_msg); - } - z_ratio=depth/z_max_res; - - //allocated even if not used - ubuffer = new uint8 *[channels]; - memset(ubuffer,0,channels*sizeof(uint8 *)); - org_channels = channels; // save for checks - - FILE *fhandle; - sint64 z; - sint64 z_parts; - if ( initResumer("Vaa3DRaw",output_path.c_str(),resolutions_size,resolutions,block_height,block_width,block_depth,method,saved_img_format,saved_img_depth,fhandle) ) { - readResumerState(fhandle,output_path.c_str(),resolutions_size,stack_block,slice_start,slice_end,z,z_parts); - } - else { - //slice_start and slice_end of current block depend on the resolution - for(int res_i=0; res_i< resolutions_size; res_i++) { - stack_block[res_i] = 0; - //slice_start[res_i] = this->D0; - slice_start[res_i] = 0; // indices must start from 0 because they should have relative meaning - slice_end[res_i] = slice_start[res_i] + stacks_depth[res_i][0][0][0] - 1; - } - z = this->D0; - z_parts = 1; - } - - // z must begin from D0 (absolute index into the volume) since it is used to compute tha file names (containing the absolute position along D) - for(/* sint64 z = this->D0, z_parts = 1 */; z < this->D1; z += z_max_res, z_parts++) - { - //if ( z > (this->D1/2) ) { - // closeResumer(fhandle); - // throw IOExcpetion("interruption for test"); - //} - - // 2015-01-30. Alessandro. @ADDED performance (time) measurement in 'generateTilesVaa3DRaw()' method. - #ifdef _VAA3D_TERAFLY_PLUGIN_MODE - TERAFLY_TIME_START(ConverterLoadBlockOperation) - #endif - - // fill one slice block - if ( internal_rep == REAL_INTERNAL_REP ) - rbuffer = volume->loadSubvolume_to_real32(V0,V1,H0,H1,(int)(z-D0),(z-D0+z_max_res <= D1) ? (int)(z-D0+z_max_res) : D1); - else { // internal_rep == UINT8_INTERNAL_REP - ubuffer[0] = volume->loadSubvolume_to_UINT8(V0,V1,H0,H1,(int)(z-D0),(z-D0+z_max_res <= D1) ? (int)(z-D0+z_max_res) : D1,&channels,iim::NATIVE_RTYPE); - if ( org_channels != channels ) { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"The volume contains images with a different number of channels (%d,%d)", org_channels, channels); - throw IOException(err_msg); - } - - for (int i=1; iupdate(((float)(z-D0+z_max_res-1)*100/(float)depth), progressBarMsg); - imProgressBar::getInstance()->show(); - } - - //saving current buffer data at selected resolutions and in multitile format - for(int i=0; i< resolutions_size; i++) - { - if(show_progress_bar) - { - sprintf(progressBarMsg, "Generating resolution %d of %d",i+1,std::max(resolutions_size, resolutions_size)); - imProgressBar::getInstance()->updateInfo(progressBarMsg); - imProgressBar::getInstance()->show(); - } - - // check if current block is changed - // D0 must be subtracted because z is an absolute index in volume while slice index should be computed on a relative basis (i.e. starting form 0) - if ( ((z - this->D0) / powInt(2,i)) > slice_end[i] ) { - stack_block[i]++; - slice_start[i] = slice_end[i] + 1; - slice_end[i] += stacks_depth[i][0][0][stack_block[i]]; - } - - // find abs_pos_z at resolution i - std::stringstream abs_pos_z; - abs_pos_z.width(6); - abs_pos_z.fill('0'); - abs_pos_z << (int)(this->getMultiresABS_D(i) + // all stacks start at the same D position - - D0 * volume->getVXL_D() * 10 + // WARNING: D0 is counted twice,both in getMultiresABS_D and in slice_start - (powInt(2,i)*slice_start[i]) * volume->getVXL_D()); - - //compute the number of slice of previous groups at resolution i - //note that z_parts in the number and not an index (starts from 1) - n_slices_pred = (z_parts - 1) * z_max_res / powInt(2,i); - - //buffer size along D is different when the remainder of the subdivision by z_max_res is considered - sint64 z_size = (z_parts<=z_ratio) ? z_max_res : (depth%z_max_res); - - //halvesampling resolution if current resolution is not the deepest one - if(i!=0) { - if ( internal_rep == REAL_INTERNAL_REP ) - VirtualVolume::halveSample(rbuffer,(int)height/(powInt(2,i-1)),(int)width/(powInt(2,i-1)),(int)z_size/(powInt(2,i-1)),method); - else // internal_rep == UINT8_INTERNAL_REP - VirtualVolume::halveSample_UINT8(ubuffer,(int)height/(powInt(2,i-1)),(int)width/(powInt(2,i-1)),(int)z_size/(powInt(2,i-1)),channels,method,bytes_chan); - } - - //saving at current resolution if it has been selected and iff buffer is at least 1 voxel (Z) deep - if(resolutions[i] && (z_size/(powInt(2,i))) > 0) - { - if(show_progress_bar) - { - sprintf(progressBarMsg, "Saving to disc resolution %d",i+1); - imProgressBar::getInstance()->updateInfo(progressBarMsg); - imProgressBar::getInstance()->show(); - } - - //storing in 'base_path' the absolute path of the directory that will contain all stacks - std::stringstream base_path; - base_path << output_path << "/RES(" << (int)(height/powInt(2,i)) << "x" << - (int)(width/powInt(2,i)) << "x" << (int)(depth/powInt(2,i)) << ")/"; - - //if frame_dir not empty must create frame directory - if ( frame_dir != "" ) { - base_path << frame_dir << "/"; - if(!check_and_make_dir(base_path.str().c_str())) - { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg, "in generateTilesVaa3DRaw(...): unable to create DIR = \"%s\"\n", base_path.str().c_str()); - throw IOException(err_msg); - } - } - - //looping on new stacks - for(int stack_row = 0, start_height = 0, end_height = 0; stack_row < n_stacks_V[i]; stack_row++) - { - //incrementing end_height - end_height = start_height + stacks_height[i][stack_row][0][0]-1; - - //computing V_DIR_path and creating the directory the first time it is needed - std::stringstream V_DIR_path; - V_DIR_path << base_path.str() << this->getMultiresABS_V_string(i,start_height); - if(z==D0 && !check_and_make_dir(V_DIR_path.str().c_str())) - { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg, "in generateTilesVaa3DRaw(...): unable to create V_DIR = \"%s\"\n", V_DIR_path.str().c_str()); - throw IOException(err_msg); - } - - for(int stack_column = 0, start_width=0, end_width=0; stack_column < n_stacks_H[i]; stack_column++) - { - end_width = start_width + stacks_width [i][stack_row][stack_column][0]-1; - - //computing H_DIR_path and creating the directory the first time it is needed - std::stringstream H_DIR_path; - H_DIR_path << V_DIR_path.str() << "/" << this->getMultiresABS_V_string(i,start_height) << "_" << this->getMultiresABS_H_string(i,start_width); - if ( z==D0 ) { - if(!check_and_make_dir(H_DIR_path.str().c_str())) - { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg, "in generateTilesVaa3DRaw(...): unable to create H_DIR = \"%s\"\n", H_DIR_path.str().c_str()); - throw IOException(err_msg); - } - else { // the directory has been created for the first time - // initialize block files - V3DLONG *sz = new V3DLONG[4]; - int datatype; - char *err_rawfmt; - - sz[0] = stacks_width[i][stack_row][stack_column][0]; - sz[1] = stacks_height[i][stack_row][stack_column][0]; - sz[3] = channels; - - if ( internal_rep == REAL_INTERNAL_REP ) - datatype = 4; - else if ( internal_rep == UINT8_INTERNAL_REP ) { - if ( saved_img_depth == 16 ) - datatype = 2; - else if ( saved_img_depth == 8 ) - datatype = 1; - else { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg, "in generateTilesVaa3DRaw(...): unknown image depth (%d)", saved_img_depth); - throw IOException(err_msg); - } - } - else { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg, "in generateTilesVaa3DRaw(...): unknown internal representation (%d)", internal_rep); - throw IOException(err_msg); - } - - int slice_start_temp = 0; - for ( int j=0; j < n_stacks_D[i]; j++ ) { - sz[2] = stacks_depth[i][stack_row][stack_column][j]; - - std::stringstream abs_pos_z_temp; - abs_pos_z_temp.width(6); - abs_pos_z_temp.fill('0'); - abs_pos_z_temp << (int)(this->getMultiresABS_D(i) + // all stacks start at the same D position - (powInt(2,i)*(slice_start_temp)) * volume->getVXL_D()); - - std::stringstream img_path_temp; - img_path_temp << H_DIR_path.str() << "/" - << this->getMultiresABS_V_string(i,start_height) << "_" - << this->getMultiresABS_H_string(i,start_width) << "_" - << abs_pos_z_temp.str(); - - //if ( (err_rawfmt = initRawFile((char *)img_path_temp.str().c_str(),sz,datatype)) != 0 ) { - if ( ( !strcmp(saved_img_format,"Tiff3D") ? // format can be only "Tiff3D" or "Vaa3DRaw" - ( (err_rawfmt = initTiff3DFile((char *)img_path_temp.str().c_str(),sz[0],sz[1],sz[2],sz[3],datatype)) != 0 ) : - ( (err_rawfmt = initRawFile((char *)img_path_temp.str().c_str(),sz,datatype)) != 0 ) ) ) { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"VolumeConverter::generateTilesVaa3DRaw: error in initializing block file - %s", err_rawfmt); - throw IOException(err_msg); - }; - - slice_start_temp += (int)sz[2]; - } - delete [] sz; - } - } - - // 2015-01-30. Alessandro. @ADDED performance (time) measurement in 'generateTilesVaa3DRaw()' method. - #ifdef _VAA3D_TERAFLY_PLUGIN_MODE - TERAFLY_TIME_START(ConverterWriteBlockOperation) - #endif - - //saving HERE - - // 2015-02-10. Giulio. @CHANGED changed how img_path is constructed - std::stringstream partial_img_path; - partial_img_path << H_DIR_path.str() << "/" - << this->getMultiresABS_V_string(i,start_height) << "_" - << this->getMultiresABS_H_string(i,start_width) << "_"; - - int slice_ind = (int)(n_slices_pred - slice_start[i]); - - std::stringstream img_path; - img_path << partial_img_path.str() << abs_pos_z.str(); - - /* 2015-02-06. Giulio. @ADDED optimization to reduce the number of open/close operations in append operations - * Since slices of the same block in a group are appended in sequence, to minimize the overhead of append operations, - * all slices of a group to be appended to the same block file are appended leaving the file open and positioned at - * end of the file. - * The number of pages of block files of interest can be easily computed as: - * - * number of slice of current block = stacks_depth[i][0][0][stack_block[i]] - * number of slice of next block = stacks_depth[i][0][0][stack_block[i]+1] - */ - - void *fhandle = 0; - int n_pages_block = stacks_depth[i][0][0][stack_block[i]]; // number of pages of current block - bool block_changed = false; // true if block is changed executing the next for cycle - // fhandle = open file corresponding to current block - if ( strcmp(saved_img_format,"Tiff3D") == 0 ) - openTiff3DFile((char *)img_path.str().c_str(),(char *)(slice_ind ? "a" : "w"),fhandle); - - // WARNING: assumes that block size along z is not less that z_size/(powInt(2,i)) - for(int buffer_z=0; buffer_zD0) / powInt(2,i) + buffer_z) > slice_end[i] && !block_changed) { // start a new block along z - std::stringstream abs_pos_z_next; - abs_pos_z_next.width(6); - abs_pos_z_next.fill('0'); - abs_pos_z_next << (int)(this->getMultiresABS_D(i) + // all stacks start at the same D position - (powInt(2,i)*(slice_end[i]+1)) * volume->getVXL_D()); - img_path.str(""); - img_path << partial_img_path.str() << abs_pos_z_next.str(); - - slice_ind = 0; // 2015-02-10. Giulio. @CHANGED (int)(n_slices_pred - (slice_end[i]+1)) + buffer_z; - - // close(fhandle) i.e. file corresponding to current block - if ( strcmp(saved_img_format,"Tiff3D") == 0 ) - closeTiff3DFile(fhandle); - // fhandle = open file corresponding to next block - if ( strcmp(saved_img_format,"Tiff3D") == 0 ) - openTiff3DFile((char *)img_path.str().c_str(),(char *)"w",fhandle); - n_pages_block = stacks_depth[i][0][0][stack_block[i]+1]; - block_changed = true; - } - - if ( internal_rep == REAL_INTERNAL_REP ) - VirtualVolume::saveImage_to_Vaa3DRaw( - slice_ind, - img_path.str(), - rbuffer + buffer_z*(height/powInt(2,i))*(width/powInt(2,i)), // adds the stride - (int)height/(powInt(2,i)),(int)width/(powInt(2,i)), - start_height,end_height,start_width,end_width, - saved_img_format, saved_img_depth - ); - else // internal_rep == UINT8_INTERNAL_REP - if ( strcmp(saved_img_format,"Tiff3D")==0 ) { - VirtualVolume::saveImage_from_UINT8_to_Tiff3D( - slice_ind, - img_path.str(), - ubuffer, - channels, - buffer_z*(height/powInt(2,i))*(width/powInt(2,i))*bytes_chan, // stride to be added for slice buffer_z - (int)height/(powInt(2,i)),(int)width/(powInt(2,i)), - start_height,end_height,start_width,end_width, - saved_img_format, saved_img_depth,fhandle,n_pages_block,false); - } - else { // can be only Vaa3DRaw - VirtualVolume::saveImage_from_UINT8_to_Vaa3DRaw( - slice_ind, - img_path.str(), - ubuffer, - channels, - buffer_z*(height/powInt(2,i))*(width/powInt(2,i))*bytes_chan, // stride to be added for slice buffer_z - (int)height/(powInt(2,i)),(int)width/(powInt(2,i)), - start_height,end_height,start_width,end_width, - saved_img_format, saved_img_depth); - } - } - - // close(fhandle) i.e. currently opened file - if ( strcmp(saved_img_format,"Tiff3D") == 0 ) - closeTiff3DFile(fhandle); - - start_width += stacks_width [i][stack_row][stack_column][0]; // WARNING TO BE CHECKED FOR CORRECTNESS - - // 2015-01-30. Alessandro. @ADDED performance (time) measurement in 'generateTilesVaa3DRaw()' method. - #ifdef _VAA3D_TERAFLY_PLUGIN_MODE - TERAFLY_TIME_STOP(ConverterWriteBlockOperation, itm::ALL_COMPS, teramanager::strprintf("converter: written multiresolution image block x(%d-%d), y(%d-%d), z(%d-%d)",start_width, end_width, start_height, end_height, ((uint32)(z-D0)),((uint32)(z-D0+z_max_res-1)))) - #endif - } - start_height += stacks_height[i][stack_row][0][0]; // WARNING TO BE CHECKED FOR CORRECTNESS - } - } - } - - //releasing allocated memory - if ( internal_rep == REAL_INTERNAL_REP ) - delete rbuffer; - else // internal_rep == UINT8_INTERNAL_REP - delete ubuffer[0]; // other buffer pointers are only offsets - - // save next group data - saveResumerState(fhandle,resolutions_size,stack_block,slice_start,slice_end,z+z_max_res,z_parts+1); - } - - closeResumer(fhandle,output_path.c_str()); - - // reloads created volumes to generate .bin file descriptors at all resolutions - ref_sys reference(axis(1),axis(2),axis(3)); - TiledMCVolume *mcprobe; - TiledVolume *tprobe; - StackedVolume *sprobe; - int n_err = 0; - sprobe = dynamic_cast(volume); - if ( sprobe ) { - reference.first = sprobe->getAXS_1(); - reference.second = sprobe->getAXS_2(); - reference.third = sprobe->getAXS_3(); - } - else { - tprobe = dynamic_cast(volume); - if ( tprobe ) { - reference.first = tprobe->getAXS_1(); - reference.second = tprobe->getAXS_2(); - reference.third = tprobe->getAXS_3(); - } - else { - mcprobe = dynamic_cast(volume); - if ( mcprobe ) { - reference.first = mcprobe->getAXS_1(); - reference.second = mcprobe->getAXS_2(); - reference.third = mcprobe->getAXS_3(); - } - } - } - for(int res_i=0; res_i< resolutions_size; res_i++) - { - if(resolutions[res_i]) - { - //---- Alessandro 2013-04-22 partial fix: wrong voxel size computation. In addition, the predefined reference system {1,2,3} may not be the right - //one when dealing with CLSM data. The right reference system is stored in the object. A possible solution to implement - //is to check whether is a pointer to a object, then specialize it to and get its reference - //system. - try { - TiledVolume temp_vol(file_path[res_i].str().c_str(),reference, - volume->getVXL_V()*pow(2.0f,res_i), volume->getVXL_H()*pow(2.0f,res_i),volume->getVXL_D()*pow(2.0f,res_i)); - } - catch (IOException & ex) - { - printf("n VolumeConverter::generateTilesVaa3DRaw: cannot create file mdata.bin in %s [reason: %s]\n\n",file_path[res_i].str().c_str(), ex.what()); - n_err++; - } - catch ( ... ) - { - printf("in VolumeConverter::generateTilesVaa3DRaw: cannot create file mdata.bin in %s [no reason available]\n\n",file_path[res_i].str().c_str()); - n_err++; - } - -// StackedVolume temp_vol(file_path[res_i].str().c_str(),ref_sys(axis(1),axis(2),axis(3)), volume->getVXL_V()*(res_i+1), -// volume->getVXL_H()*(res_i+1),volume->getVXL_D()*(res_i+1)); - } - } - - - // ubuffer allocated anyway - delete ubuffer; - - // deallocate memory - for(int res_i=0; res_i< resolutions_size; res_i++) - { - for(int stack_row = 0; stack_row < n_stacks_V[res_i]; stack_row++) - { - for(int stack_col = 0; stack_col < n_stacks_H[res_i]; stack_col++) - { - delete []stacks_height[res_i][stack_row][stack_col]; - delete []stacks_width [res_i][stack_row][stack_col]; - delete []stacks_depth [res_i][stack_row][stack_col]; - } - delete []stacks_height[res_i][stack_row]; - delete []stacks_width [res_i][stack_row]; - delete []stacks_depth [res_i][stack_row]; - } - delete []stacks_height[res_i]; - delete []stacks_width[res_i]; - delete []stacks_depth[res_i]; - } - - if ( n_err ) { // errors in mdat.bin creation - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"VolumeConverter::generateTilesVaa3DRaw: %d errors in creating mdata.bin files", n_err); - throw IOException(err_msg); - } -} - - -/************************************************************************************************************* -* Functions used to obtain absolute coordinates at different resolutions from relative coordinates -**************************************************************************************************************/ -int VolumeConverter::getMultiresABS_V(int res, int REL_V) -{ - if(volume->getVXL_V() > 0) - return volume->getABS_V( V0 + REL_V*pow(2.0f,res) )*10; - else - return volume->getABS_V( V0 - 1 + REL_V*pow(2.0f,res))*10 + volume->getVXL_V()*pow(2.0f,res)*10; -} -std::string VolumeConverter::getMultiresABS_V_string(int res, int REL_V) -{ - std::stringstream multires_merging_x_pos; - multires_merging_x_pos.width(6); - multires_merging_x_pos.fill('0'); - multires_merging_x_pos << this->getMultiresABS_V(res, REL_V); - return multires_merging_x_pos.str(); -} -int VolumeConverter::getMultiresABS_H(int res, int REL_H) -{ - if(volume->getVXL_H() > 0) - return volume->getABS_H( H0 + REL_H*pow(2.0f,res) )*10; - else - return volume->getABS_H( H0 - 1 + REL_H*pow(2.0f,res))*10 + volume->getVXL_H()*pow(2.0f,res)*10; -} -std::string VolumeConverter::getMultiresABS_H_string(int res, int REL_H) -{ - std::stringstream multires_merging_y_pos; - multires_merging_y_pos.width(6); - multires_merging_y_pos.fill('0'); - multires_merging_y_pos << this->getMultiresABS_H(res, REL_H); - return multires_merging_y_pos.str(); -} -int VolumeConverter::getMultiresABS_D(int res) -{ - if(volume->getVXL_D() > 0) - return volume->getABS_D(D0); - else - return volume->getABS_D((int)(D0 - 1 + volume->getVXL_D()*pow(2.0f,res)*10.0f)); -} - - - -/************************************************************************************************************* -* NEW TILED FORMAT SUPPORTING MULTIPLE CHANNELS -**************************************************************************************************************/ - -# ifdef RES_IN_CHANS // resolutions directories in channels directories - -void VolumeConverter::generateTilesVaa3DRawMC ( std::string output_path, bool* resolutions, - int block_height, int block_width, int block_depth, int method, - bool show_progress_bar, const char* saved_img_format, - int saved_img_depth, std::string frame_dir ) throw (IOExcpetion) -{ - printf("in VolumeConverter::generateTilesVaa3DRawMC(path = \"%s\", resolutions = ", output_path.c_str()); - for(int i=0; i< S_MAX_MULTIRES; i++) - printf("%d", resolutions[i]); - printf(", block_height = %d, block_width = %d, block_depth = %d, method = %d, show_progress_bar = %s, saved_img_format = %s, saved_img_depth = %d, frame_dir = \"%s\")\n", - block_height, block_width, block_depth, method, show_progress_bar ? "true" : "false", saved_img_format, saved_img_depth, frame_dir.c_str()); - - if ( saved_img_depth == 0 ) // default is to generate an image with the same depth of the source - saved_img_depth = volume->getBYTESxCHAN() * 8; - - if ( saved_img_depth != (volume->getBYTESxCHAN() * 8) ) { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"VolumeConverter::generateTilesVaa3DRaw: mismatch between bits per channel of source (%d) and destination (%d)", - volume->getBYTESxCHAN() * 8, saved_img_depth); - throw IOExcpetion(err_msg); - } - - //LOCAL VARIABLES - sint64 height, width, depth; //height, width and depth of the whole volume that covers all stacks - real32* rbuffer; //buffer where temporary image data are stored (REAL_INTERNAL_REP) - uint8** ubuffer; //array of buffers where temporary image data of channels are stored (UINT8_INTERNAL_REP) - int bytes_chan = volume->getBYTESxCHAN(); - //uint8* ubuffer_ch2; //buffer temporary image data of channel 1 are stored (UINT8_INTERNAL_REP) - //uint8* ubuffer_ch3; //buffer temporary image data of channel 1 are stored (UINT8_INTERNAL_REP) - int org_channels = 0; //store the number of channels read the first time (for checking purposes) - //real32* stripe_up=NULL; //will contain up-stripe and down-stripe computed by calling 'getStripe' method (unused) - sint64 z_ratio, z_max_res; - int n_stacks_V[S_MAX_MULTIRES]; //arrays of number of tiles along V, H and D directions respectively at i-th resolution - int n_stacks_H[S_MAX_MULTIRES]; - int n_stacks_D[S_MAX_MULTIRES]; - int ***stacks_height[S_MAX_MULTIRES]; //array of matrices of tiles dimensions at i-th resolution - int ***stacks_width[S_MAX_MULTIRES]; - int ***stacks_depth[S_MAX_MULTIRES]; - std::string *chans_dir; - std::string resolution_dir; - std::stringstream file_path[S_MAX_MULTIRES]; //array of root directory name at i-th resolution - int resolutions_size = 0; - - /* DEFINITIONS OF VARIABILES THAT MANAGE TILES (BLOCKS) ALONG D-direction - * In the following the term 'group' means the groups of slices that are - * processed together to generate slices of all resolution requested - */ - - /* stack_block[i] is the index of current block along z (it depends on the resolution i) - * current block is the block in which falls the first slice of the group - * of slices that is currently being processed, i.e. from z to z+z_max_res-1 - */ - int stack_block[S_MAX_MULTIRES]; - - /* these arrays are the indices of first and last slice of current block at resolution i - * WARNING: the slice index refers to the index of the slice in the volume at resolution i - */ - int slice_start[S_MAX_MULTIRES]; - int slice_end[S_MAX_MULTIRES]; - - /* the number of slice of already processed groups at current resolution - * the index of the slice to be saved at current resolution is: - * - * n_slices_pred + z_buffer - */ - sint64 n_slices_pred; - - if ( volume == 0 ) { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"VolumeConverter::generateTilesVaa3DRawMC: undefined source volume"); - throw IOExcpetion(err_msg); - } - - //initializing the progress bar - char progressBarMsg[200]; - if(show_progress_bar) - { - imProgressBar::getInstance()->start("Multiresolution tile generation"); - imProgressBar::getInstance()->update(0,"Initializing..."); - imProgressBar::getInstance()->show(); - } - - // 2015-03-03. Giulio. @ADDED selection of IO plugin if not provided. - if(iom::IMOUT_PLUGIN.compare("empty") == 0) - { - iom::IMOUT_PLUGIN = "tiff3D"; - } - - //computing dimensions of volume to be stitched - //this->computeVolumeDims(exclude_nonstitchable_stacks, _ROW_START, _ROW_END, _COL_START, _COL_END, _D0, _D1); - width = this->H1-this->H0; - height = this->V1-this->V0; - depth = this->D1-this->D0; - - // code for testing - //uint8 *temp = volume->loadSubvolume_to_UINT8( - // 10,height-10,10,width-10,10,depth-10, - // &channels); - - //activating resolutions - block_height = (block_height == -1 ? (int)height : block_height); - block_width = (block_width == -1 ? (int)width : block_width); - block_depth = (block_depth == -1 ? (int)depth : block_depth); - if(block_height < S_MIN_SLICE_DIM || block_width < S_MIN_SLICE_DIM /* 2014-11-10. Giulio. @REMOVED (|| block_depth < S_MIN_SLICE_DIM) */) - { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"The minimum dimension for block height, width, and depth is %d", S_MIN_SLICE_DIM); - throw IOExcpetion(err_msg); - } - - if(resolutions == NULL) - { - resolutions = new bool; - *resolutions = true; - resolutions_size = 1; - } - else - for(int i=0; i D and hence: - * - * D >= B >= floor(D/2) - * since it is: - * - * 1/ceil(H/D) = 1/(H/D + alpha) = D/(H + alpha * D) > D/(2 * H) - * where alpha<1. - */ - - //ALLOCATING the MEMORY SPACE for image buffer - z_max_res = powInt(2,resolutions_size-1); - if ( z_max_res > block_depth/2 ) { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg, "in generateTilesVaa3DRaw(...): too much resolutions(%d): too much slices (%lld) in the buffer \n", resolutions_size, z_max_res); - throw IOException(err_msg); - } - z_ratio=depth/z_max_res; - - //allocated even if not used - ubuffer = new uint8 *[channels]; - memset(ubuffer,0,channels*sizeof(uint8)); - org_channels = channels; // save for checks - - //slice_start and slice_end of current block depend on the resolution - for(int res_i=0; res_i< resolutions_size; res_i++) { - stack_block[res_i] = 0; - //slice_start[res_i] = this->D0; - slice_start[res_i] = 0; // indices must start from 0 because they should have relative meaning - slice_end[res_i] = slice_start[res_i] + stacks_depth[res_i][0][0][0] - 1; - } - - // z must begin from D0 (absolute index into the volume) since it is used to compute tha file names (containing the absolute position along D) - for(sint64 z = this->D0, z_parts = 1; z < this->D1; z += z_max_res, z_parts++) - { - // fill one slice block - if ( internal_rep == REAL_INTERNAL_REP ) - rbuffer = volume->loadSubvolume_to_real32(V0,V1,H0,H1,(int)(z-D0),(z-D0+z_max_res <= D1) ? (int)(z-D0+z_max_res) : D1); - else { // internal_rep == UINT8_INTERNAL_REP - ubuffer[0] = volume->loadSubvolume_to_UINT8(V0,V1,H0,H1,(int)(z-D0),(z-D0+z_max_res <= D1) ? (int)(z-D0+z_max_res) : D1,&channels,iim::NATIVE_RTYPE); - if ( org_channels != channels ) { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"The volume contains images with a different number of channels (%d,%d)", org_channels, channels); - throw IOExcpetion(err_msg); - } - - for (int i=1; iupdate(((float)(z-D0+z_max_res-1)*100/(float)depth), progressBarMsg); - imProgressBar::getInstance()->show(); - } - - //saving current buffer data at selected resolutions and in multitile format - for(int i=0; i< resolutions_size; i++) - { - if(show_progress_bar) - { - sprintf(progressBarMsg, "Generating resolution %d of %d",i+1,std::max(resolutions_size, resolutions_size)); - imProgressBar::getInstance()->updateInfo(progressBarMsg); - imProgressBar::getInstance()->show(); - } - - // check if current block is changed - // D0 must be subtracted because z is an absolute index in volume while slice index should be computed on a relative basis (i.e. starting form 0) - if ( ((z - this->D0) / powInt(2,i)) > slice_end[i] ) { - stack_block[i]++; - slice_start[i] = slice_end[i] + 1; - slice_end[i] += stacks_depth[i][0][0][stack_block[i]]; - } - - // find abs_pos_z at resolution i - std::stringstream abs_pos_z; - abs_pos_z.width(6); - abs_pos_z.fill('0'); - abs_pos_z << (int)(this->getMultiresABS_D(i) + // all stacks start at the same D position - - D0 * volume->getVXL_D() * 10 + // WARNING: D0 is counted twice,both in getMultiresABS_D and in slice_start - (POW_INT(2,i)*slice_start[i]) * volume->getVXL_D()); - - //compute the number of slice of previous groups at resolution i - //note that z_parts in the number and not an index (starts from 1) - n_slices_pred = (z_parts - 1) * z_max_res / POW_INT(2,i); - - //buffer size along D is different when the remainder of the subdivision by z_max_res is considered - sint64 z_size = (z_parts<=z_ratio) ? z_max_res : (depth%z_max_res); - - //halvesampling resolution if current resolution is not the deepest one - if(i!=0) { - if ( internal_rep == REAL_INTERNAL_REP ) - VirtualVolume::halveSample(rbuffer,(int)height/(POW_INT(2,i-1)),(int)width/(POW_INT(2,i-1)),(int)z_size/(POW_INT(2,i-1)),method); - else // internal_rep == UINT8_INTERNAL_REP - VirtualVolume::halveSample_UINT8(ubuffer,(int)height/(POW_INT(2,i-1)),(int)width/(POW_INT(2,i-1)),(int)z_size/(POW_INT(2,i-1)),channels,method,bytes_chan); - } - - //saving at current resolution if it has been selected and iff buffer is at least 1 voxel (Z) deep - if(resolutions[i] && (z_size/(POW_INT(2,i))) > 0) - { - if(show_progress_bar) - { - sprintf(progressBarMsg, "Saving to disc resolution %d",i+1); - imProgressBar::getInstance()->updateInfo(progressBarMsg); - imProgressBar::getInstance()->show(); - } - - for ( int c=0; cgetMultiresABS_V_string(i,start_height); - if(z==D0 && !check_and_make_dir(V_DIR_path.str().c_str())) - { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg, "in generateTilesVaa3DRawMC(...): unable to create V_DIR = \"%s\"\n", V_DIR_path.str().c_str()); - throw IOExcpetion(err_msg); - } - - for(int stack_column = 0, start_width=0, end_width=0; stack_column < n_stacks_H[i]; stack_column++) - { - end_width = start_width + stacks_width [i][stack_row][stack_column][0]-1; - - //computing H_DIR_path and creating the directory the first time it is needed - std::stringstream H_DIR_path; - H_DIR_path << V_DIR_path.str() << "/" << this->getMultiresABS_V_string(i,start_height) << "_" << this->getMultiresABS_H_string(i,start_width); - if ( z==D0 ) { - if(!check_and_make_dir(H_DIR_path.str().c_str())) - { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg, "in generateTilesVaa3DRawMC(...): unable to create H_DIR = \"%s\"\n", H_DIR_path.str().c_str()); - throw IOExcpetion(err_msg); - } - else { // the directory has been created for the first time - // initialize block files - V3DLONG *sz = new V3DLONG[4]; - int datatype; - char *err_rawfmt; - - sz[0] = stacks_width[i][stack_row][stack_column][0]; - sz[1] = stacks_height[i][stack_row][stack_column][0]; - sz[3] = 1; // single channel files - - if ( internal_rep == REAL_INTERNAL_REP ) - datatype = 4; - else if ( internal_rep == UINT8_INTERNAL_REP ) { - if ( saved_img_depth == 16 ) - datatype = 2; - else if ( saved_img_depth == 8 ) - datatype = 1; - else { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg, "in generateTilesVaa3DRaw(...): unknown image depth (%d)", saved_img_depth); - throw IOExcpetion(err_msg); - } - } - else { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg, "in generateTilesVaa3DRaw(...): unknown internal representation (%d)", internal_rep); - throw IOExcpetion(err_msg); - } - - int slice_start_temp = 0; - for ( int j=0; j < n_stacks_D[i]; j++ ) { - sz[2] = stacks_depth[i][stack_row][stack_column][j]; - - std::stringstream abs_pos_z_temp; - abs_pos_z_temp.width(6); - abs_pos_z_temp.fill('0'); - abs_pos_z_temp << (int)(this->getMultiresABS_D(i) + // all stacks start at the same D position - (POW_INT(2,i)*(slice_start_temp)) * volume->getVXL_D()); - - std::stringstream img_path_temp; - img_path_temp << H_DIR_path.str() << "/" - << this->getMultiresABS_V_string(i,start_height) << "_" - << this->getMultiresABS_H_string(i,start_width) << "_" - << abs_pos_z_temp.str(); - - //if ( (err_rawfmt = initRawFile((char *)img_path_temp.str().c_str(),sz,datatype)) != 0 ) { - if ( ( !strcmp(saved_img_format,"Tiff3D") ? // format can be only "Tiff3D" or "Vaa3DRaw" - ( (err_rawfmt = initTiff3DFile((char *)img_path_temp.str().c_str(),sz[0],sz[1],sz[2],sz[3],datatype)) != 0 ) : - ( (err_rawfmt = initRawFile((char *)img_path_temp.str().c_str(),sz,datatype)) != 0 ) ) ) { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"VolumeConverter::generateTilesVaa3DRawMC: error in initializing block file - %s", err_rawfmt); - throw IOExcpetion(err_msg); - }; - - slice_start_temp += (int)sz[2]; - } - delete [] sz; - } - } - - //saving HERE - - // 2015-02-10. Giulio. @CHANGED changed how img_path is constructed - std::stringstream partial_img_path; - partial_img_path << H_DIR_path.str() << "/" - << this->getMultiresABS_V_string(i,start_height) << "_" - << this->getMultiresABS_H_string(i,start_width) << "_"; - - int slice_ind = (int)(n_slices_pred - slice_start[i]); - - std::stringstream img_path; - img_path << partial_img_path.str() << abs_pos_z.str(); - - /* 2015-02-06. Giulio. @ADDED optimization to reduce the number of open/close operations in append operations - * Since slices of the same block in a group are appended in sequence, to minimize the overhead of append operations, - * all slices of a group to be appended to the same block file are appended leaving the file open and positioned at - * end of the file. - * The number of pages of block files of interest can be easily computed as: - * - * number of slice of current block = stacks_depth[i][0][0][stack_block[i]] - * number of slice of next block = stacks_depth[i][0][0][stack_block[i]+1] - */ - - void *fhandle = 0; - int n_pages_block = stacks_depth[i][0][0][stack_block[i]]; // number of pages of current block - bool block_changed = false; // true if block is changed executing the next for cycle - // fhandle = open file corresponding to current block - if ( strcmp(saved_img_format,"Tiff3D") == 0 ) - openTiff3DFile((char *)img_path.str().c_str(),(char *)(slice_ind ? "a" : "w"),fhandle); - - // WARNING: assumes that block size along z is not less that z_size/(powInt(2,i)) - for(int buffer_z=0; buffer_zD0) /powInt(2,i)+buffer_z) > slice_end[i] && !block_changed) { // start a new block along z - std::stringstream abs_pos_z_next; - abs_pos_z_next.width(6); - abs_pos_z_next.fill('0'); - abs_pos_z_next << (int)(this->getMultiresABS_D(i) + // all stacks start at the same D position - (powInt(2,i)*(slice_end[i]+1)) * volume->getVXL_D()); - img_path.str(""); - img_path << partial_img_path.str() << abs_pos_z_next.str(); - - slice_ind = 0; // 2015-02-10. Giulio. @CHANGED (int)(n_slices_pred - (slice_end[i]+1)) + buffer_z; - - // close(fhandle) i.e. file corresponding to current block - if ( strcmp(saved_img_format,"Tiff3D") == 0 ) - closeTiff3DFile(fhandle); - // fhandle = open file corresponding to next block - if ( strcmp(saved_img_format,"Tiff3D") == 0 ) - openTiff3DFile((char *)img_path.str().c_str(),(char *)"w",fhandle); - openTiff3DFile((char *)img_path.str().c_str(),(char *)"w",fhandle); - n_pages_block = stacks_depth[i][0][0][stack_block[i]+1]; - block_changed = true; - } - - if ( internal_rep == REAL_INTERNAL_REP ) - VirtualVolume::saveImage_to_Vaa3DRaw( - slice_ind, - img_path.str(), - rbuffer + buffer_z*(height/POW_INT(2,i))*(width/POW_INT(2,i)), // adds the stride - (int)height/(POW_INT(2,i)),(int)width/(POW_INT(2,i)), - start_height,end_height,start_width,end_width, - saved_img_format, saved_img_depth - ); - else {// internal_rep == UINT8_INTERNAL_REP - if ( strcmp(saved_img_format,"Tiff3D")==0 ) { - VirtualVolume::saveImage_from_UINT8_to_Tiff3D( - slice_ind, - img_path.str(), - ubuffer + c, - 1, - buffer_z*(height/powInt(2,i))*(width/powInt(2,i))*bytes_chan, // stride to be added for slice buffer_z - (int)height/(powInt(2,i)),(int)width/(powInt(2,i)), - start_height,end_height,start_width,end_width, - saved_img_format, saved_img_depth,fhandle,n_pages_block,false); - } - else { // can be only Vaa3DRaw - VirtualVolume::saveImage_from_UINT8_to_Vaa3DRaw( - slice_ind, - img_path.str(), - ubuffer + c, - 1, - buffer_z*(height/powInt(2,i))*(width/powInt(2,i))*bytes_chan, // stride to be added for slice buffer_z - (int)height/(powInt(2,i)),(int)width/(powInt(2,i)), - start_height,end_height,start_width,end_width, - saved_img_format, saved_img_depth); - } - } - } - - // close(fhandle) i.e. currently opened file - if ( strcmp(saved_img_format,"Tiff3D") == 0 ) - closeTiff3DFile(fhandle); - - start_width += stacks_width [i][stack_row][stack_column][0]; // WARNING TO BE CHECKED FOR CORRECTNESS - } - start_height += stacks_height[i][stack_row][0][0]; // WARNING TO BE CHECKED FOR CORRECTNESS - } - } - } - } - - //releasing allocated memory - if ( internal_rep == REAL_INTERNAL_REP ) - delete rbuffer; - else // internal_rep == UINT8_INTERNAL_REP - delete ubuffer[0]; // other buffer pointers are only offsets - } - - // reloads created volumes to generate .bin file descriptors at all resolutions - ref_sys reference(axis(1),axis(2),axis(3)); - TiledMCVolume *mcprobe; - TiledVolume *tprobe; - StackedVolume *sprobe; - sprobe = dynamic_cast(volume); - if ( sprobe ) { - reference.first = sprobe->getAXS_1(); - reference.second = sprobe->getAXS_2(); - reference.third = sprobe->getAXS_3(); - } - else { - tprobe = dynamic_cast(volume); - if ( tprobe ) { - reference.first = tprobe->getAXS_1(); - reference.second = tprobe->getAXS_2(); - reference.third = tprobe->getAXS_3(); - } - else { - mcprobe = dynamic_cast(volume); - if ( mcprobe ) { - reference.first = mcprobe->getAXS_1(); - reference.second = mcprobe->getAXS_2(); - reference.third = mcprobe->getAXS_3(); - } - } - } - for ( int c=0; c object. A possible solution to implement - //is to check whether is a pointer to a object, then specialize it to and get its reference - //system. - TiledVolume temp_vol(resolution_dir.c_str(),reference, - volume->getVXL_V()*pow(2.0f,res_i), volume->getVXL_H()*pow(2.0f,res_i),volume->getVXL_D()*pow(2.0f,res_i)); - - // StackedVolume temp_vol(file_path[res_i].str().c_str(),ref_sys(axis(1),axis(2),axis(3)), volume->getVXL_V()*(res_i+1), - // volume->getVXL_H()*(res_i+1),volume->getVXL_D()*(res_i+1)); - } - } - } - - - // ubuffer allocated anyway - delete ubuffer; - - // deallocate memory - for(int res_i=0; res_i< resolutions_size; res_i++) - { - for(int stack_row = 0; stack_row < n_stacks_V[res_i]; stack_row++) - { - for(int stack_col = 0; stack_col < n_stacks_H[res_i]; stack_col++) - { - delete[] stacks_height[res_i][stack_row][stack_col]; - delete[] stacks_width [res_i][stack_row][stack_col]; - delete[] stacks_depth [res_i][stack_row][stack_col]; - } - delete[] stacks_height[res_i][stack_row]; - delete[] stacks_width [res_i][stack_row]; - delete[] stacks_depth [res_i][stack_row]; - } - delete[] stacks_height[res_i]; - delete[] stacks_width[res_i]; - delete[] stacks_depth[res_i]; - } - delete[] chans_dir; -} - -# else // channels directories in resolutions directories - -void VolumeConverter::generateTilesVaa3DRawMC ( std::string output_path, bool* resolutions, - int block_height, int block_width, int block_depth, int method, - bool show_progress_bar, const char* saved_img_format, - int saved_img_depth, std::string frame_dir ) throw (IOException) -{ - printf("in VolumeConverter::generateTilesVaa3DRawMC(path = \"%s\", resolutions = ", output_path.c_str()); - for(int i=0; i< TMITREE_MAX_HEIGHT; i++) - printf("%d", resolutions[i]); - printf(", block_height = %d, block_width = %d, block_depth = %d, method = %d, show_progress_bar = %s, saved_img_format = %s, saved_img_depth = %d, frame_dir = \"%s\")\n", - block_height, block_width, block_depth, method, show_progress_bar ? "true" : "false", saved_img_format, saved_img_depth, frame_dir.c_str()); - - if ( saved_img_depth == 0 ) // default is to generate an image with the same depth of the source - saved_img_depth = volume->getBYTESxCHAN() * 8; - - if ( saved_img_depth != (volume->getBYTESxCHAN() * 8) ) { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"VolumeConverter::generateTilesVaa3DRaw: mismatch between bits per channel of source (%d) and destination (%d)", - volume->getBYTESxCHAN() * 8, saved_img_depth); - throw IOException(err_msg); - } - - //LOCAL VARIABLES - sint64 height, width, depth; //height, width and depth of the whole volume that covers all stacks - real32* rbuffer; //buffer where temporary image data are stored (REAL_INTERNAL_REP) - uint8** ubuffer; //array of buffers where temporary image data of channels are stored (UINT8_INTERNAL_REP) - int bytes_chan = volume->getBYTESxCHAN(); - //uint8* ubuffer_ch2; //buffer temporary image data of channel 1 are stored (UINT8_INTERNAL_REP) - //uint8* ubuffer_ch3; //buffer temporary image data of channel 1 are stored (UINT8_INTERNAL_REP) - int org_channels = 0; //store the number of channels read the first time (for checking purposes) - //real32* stripe_up=NULL; //will contain up-stripe and down-stripe computed by calling 'getStripe' method (unused) - sint64 z_ratio, z_max_res; - int n_stacks_V[TMITREE_MAX_HEIGHT]; //arrays of number of tiles along V, H and D directions respectively at i-th resolution - int n_stacks_H[TMITREE_MAX_HEIGHT]; - int n_stacks_D[TMITREE_MAX_HEIGHT]; - int ***stacks_height[TMITREE_MAX_HEIGHT]; //array of matrices of tiles dimensions at i-th resolution - int ***stacks_width[TMITREE_MAX_HEIGHT]; - int ***stacks_depth[TMITREE_MAX_HEIGHT]; - std::string *chans_dir; - std::string resolution_dir; - std::stringstream file_path[TMITREE_MAX_HEIGHT]; //array of root directory name at i-th resolution - int resolutions_size = 0; - - /* DEFINITIONS OF VARIABILES THAT MANAGE TILES (BLOCKS) ALONG D-direction - * In the following the term 'group' means the groups of slices that are - * processed together to generate slices of all resolution requested - */ - - /* stack_block[i] is the index of current block along z (it depends on the resolution i) - * current block is the block in which falls the first slice of the group - * of slices that is currently being processed, i.e. from z to z+z_max_res-1 - */ - int stack_block[TMITREE_MAX_HEIGHT]; - - /* these arrays are the indices of first and last slice of current block at resolution i - * WARNING: the slice index refers to the index of the slice in the volume at resolution i - */ - int slice_start[TMITREE_MAX_HEIGHT]; - int slice_end[TMITREE_MAX_HEIGHT]; - - /* the number of slice of already processed groups at current resolution - * the index of the slice to be saved at current resolution is: - * - * n_slices_pred + z_buffer - */ - sint64 n_slices_pred; - - if ( volume == 0 ) { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"VolumeConverter::generateTilesVaa3DRawMC: undefined source volume"); - throw IOException(err_msg); - } - - //initializing the progress bar - char progressBarMsg[200]; - if(show_progress_bar) - { - imProgressBar::getInstance()->start("Multiresolution tile generation"); - imProgressBar::getInstance()->update(0,"Initializing..."); - imProgressBar::getInstance()->show(); - } - - // 2015-03-03. Giulio. @ADDED selection of IO plugin if not provided. - if(iom::IMOUT_PLUGIN.compare("empty") == 0) - { - iom::IMOUT_PLUGIN = "tiff3D"; - } - - //computing dimensions of volume to be stitched - //this->computeVolumeDims(exclude_nonstitchable_stacks, _ROW_START, _ROW_END, _COL_START, _COL_END, _D0, _D1); - width = this->H1-this->H0; - height = this->V1-this->V0; - depth = this->D1-this->D0; - - // code for testing - //uint8 *temp = volume->loadSubvolume_to_UINT8( - // 10,height-10,10,width-10,10,depth-10, - // &channels); - - //activating resolutions - block_height = (block_height == -1 ? (int)height : block_height); - block_width = (block_width == -1 ? (int)width : block_width); - block_depth = (block_depth == -1 ? (int)depth : block_depth); - if(block_height < TMITREE_MIN_BLOCK_DIM || block_width < TMITREE_MIN_BLOCK_DIM /* 2014-11-10. Giulio. @REMOVED (|| block_depth < TMITREE_MIN_BLOCK_DIM9 */) - { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"The minimum dimension for block height, width, and depth is %d", TMITREE_MIN_BLOCK_DIM); - throw IOException(err_msg); - } - - if(resolutions == NULL) - { - resolutions = new bool; - *resolutions = true; - resolutions_size = 1; - } - else - for(int i=0; i D and hence: - * - * D >= B >= floor(D/2) - * since it is: - * - * 1/ceil(H/D) = 1/(H/D + alpha) = D/(H + alpha * D) > D/(2 * H) - * where alpha<1. - */ - - //ALLOCATING the MEMORY SPACE for image buffer - z_max_res = powInt(2,resolutions_size-1); - if ( z_max_res > block_depth/2 ) { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg, "in generateTilesVaa3DRaw(...): too much resolutions(%d): too much slices (%lld) in the buffer \n", resolutions_size, z_max_res); - throw IOException(err_msg); - } - z_ratio=depth/z_max_res; - - //allocated even if not used - ubuffer = new uint8 *[channels]; - memset(ubuffer,0,channels*sizeof(uint8)); - org_channels = channels; // save for checks - - //slice_start and slice_end of current block depend on the resolution - for(int res_i=0; res_i< resolutions_size; res_i++) { - stack_block[res_i] = 0; - //slice_start[res_i] = this->D0; - slice_start[res_i] = 0; // indices must start from 0 because they should have relative meaning - slice_end[res_i] = slice_start[res_i] + stacks_depth[res_i][0][0][0] - 1; - } - - // z must begin from D0 (absolute index into the volume) since it is used to compute tha file names (containing the absolute position along D) - for(sint64 z = this->D0, z_parts = 1; z < this->D1; z += z_max_res, z_parts++) - { - // fill one slice block - if ( internal_rep == REAL_INTERNAL_REP ) - rbuffer = volume->loadSubvolume_to_real32(V0,V1,H0,H1,(int)(z-D0),(z-D0+z_max_res <= D1) ? (int)(z-D0+z_max_res) : D1); - else { // internal_rep == UINT8_INTERNAL_REP - ubuffer[0] = volume->loadSubvolume_to_UINT8(V0,V1,H0,H1,(int)(z-D0),(z-D0+z_max_res <= D1) ? (int)(z-D0+z_max_res) : D1,&channels,iim::NATIVE_RTYPE); - if ( org_channels != channels ) { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"The volume contains images with a different number of channels (%d,%d)", org_channels, channels); - throw IOException(err_msg); - } - - for (int i=1; iupdate(((float)(z-D0+z_max_res-1)*100/(float)depth), progressBarMsg); - imProgressBar::getInstance()->show(); - } - - //saving current buffer data at selected resolutions and in multitile format - for(int i=0; i< resolutions_size; i++) - { - if(show_progress_bar) - { - sprintf(progressBarMsg, "Generating resolution %d of %d",i+1,std::max(resolutions_size, resolutions_size)); - imProgressBar::getInstance()->updateInfo(progressBarMsg); - imProgressBar::getInstance()->show(); - } - - // check if current block is changed - // D0 must be subtracted because z is an absolute index in volume while slice index should be computed on a relative basis (i.e. starting form 0) - if ( ((z - this->D0) / powInt(2,i)) > slice_end[i] ) { - stack_block[i]++; - slice_start[i] = slice_end[i] + 1; - slice_end[i] += stacks_depth[i][0][0][stack_block[i]]; - } - - // find abs_pos_z at resolution i - std::stringstream abs_pos_z; - abs_pos_z.width(6); - abs_pos_z.fill('0'); - abs_pos_z << (int)(this->getMultiresABS_D(i) + // all stacks start at the same D position - - D0 * volume->getVXL_D() * 10 + // WARNING: D0 is counted twice,both in getMultiresABS_D and in slice_start - (powInt(2,i)*slice_start[i]) * volume->getVXL_D()); - - //compute the number of slice of previous groups at resolution i - //note that z_parts in the number and not an index (starts from 1) - n_slices_pred = (z_parts - 1) * z_max_res / powInt(2,i); - - //buffer size along D is different when the remainder of the subdivision by z_max_res is considered - sint64 z_size = (z_parts<=z_ratio) ? z_max_res : (depth%z_max_res); - - //halvesampling resolution if current resolution is not the deepest one - if(i!=0) { - if ( internal_rep == REAL_INTERNAL_REP ) - VirtualVolume::halveSample(rbuffer,(int)height/(powInt(2,i-1)),(int)width/(powInt(2,i-1)),(int)z_size/(powInt(2,i-1)),method); - else // internal_rep == UINT8_INTERNAL_REP - VirtualVolume::halveSample_UINT8(ubuffer,(int)height/(powInt(2,i-1)),(int)width/(powInt(2,i-1)),(int)z_size/(powInt(2,i-1)),channels,method,bytes_chan); - } - - //saving at current resolution if it has been selected and iff buffer is at least 1 voxel (Z) deep - if(resolutions[i] && (z_size/(powInt(2,i))) > 0) - { - if(show_progress_bar) - { - sprintf(progressBarMsg, "Saving to disc resolution %d",i+1); - imProgressBar::getInstance()->updateInfo(progressBarMsg); - imProgressBar::getInstance()->show(); - } - - for ( int c=0; cgetMultiresABS_V_string(i,start_height); - if(z==D0 && !check_and_make_dir(V_DIR_path.str().c_str())) - { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg, "in generateTilesVaa3DRawMC(...): unable to create V_DIR = \"%s\"\n", V_DIR_path.str().c_str()); - throw IOException(err_msg); - } - - for(int stack_column = 0, start_width=0, end_width=0; stack_column < n_stacks_H[i]; stack_column++) - { - end_width = start_width + stacks_width [i][stack_row][stack_column][0]-1; - - //computing H_DIR_path and creating the directory the first time it is needed - std::stringstream H_DIR_path; - H_DIR_path << V_DIR_path.str() << "/" << this->getMultiresABS_V_string(i,start_height) << "_" << this->getMultiresABS_H_string(i,start_width); - if ( z==D0 ) { - if(!check_and_make_dir(H_DIR_path.str().c_str())) - { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg, "in generateTilesVaa3DRawMC(...): unable to create H_DIR = \"%s\"\n", H_DIR_path.str().c_str()); - throw IOException(err_msg); - } - else { // the directory has been created for the first time - // initialize block files - V3DLONG *sz = new V3DLONG[4]; - int datatype; - char *err_rawfmt; - - sz[0] = stacks_width[i][stack_row][stack_column][0]; - sz[1] = stacks_height[i][stack_row][stack_column][0]; - sz[3] = 1; // single channel files - - if ( internal_rep == REAL_INTERNAL_REP ) - datatype = 4; - else if ( internal_rep == UINT8_INTERNAL_REP ) { - if ( saved_img_depth == 16 ) - datatype = 2; - else if ( saved_img_depth == 8 ) - datatype = 1; - else { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg, "in generateTilesVaa3DRaw(...): unknown image depth (%d)", saved_img_depth); - throw IOException(err_msg); - } - } - else { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg, "in generateTilesVaa3DRaw(...): unknown internal representation (%d)", internal_rep); - throw IOException(err_msg); - } - - int slice_start_temp = 0; - for ( int j=0; j < n_stacks_D[i]; j++ ) { - sz[2] = stacks_depth[i][stack_row][stack_column][j]; - - std::stringstream abs_pos_z_temp; - abs_pos_z_temp.width(6); - abs_pos_z_temp.fill('0'); - abs_pos_z_temp << (int)(this->getMultiresABS_D(i) + // all stacks start at the same D position - (powInt(2,i)*(slice_start_temp)) * volume->getVXL_D()); - - std::stringstream img_path_temp; - img_path_temp << H_DIR_path.str() << "/" - << this->getMultiresABS_V_string(i,start_height) << "_" - << this->getMultiresABS_H_string(i,start_width) << "_" - << abs_pos_z_temp.str(); - - //if ( (err_rawfmt = initRawFile((char *)img_path_temp.str().c_str(),sz,datatype)) != 0 ) { - if ( ( !strcmp(saved_img_format,"Tiff3D") ? // format can be only "Tiff3D" or "Vaa3DRaw" - ( (err_rawfmt = initTiff3DFile((char *)img_path_temp.str().c_str(),sz[0],sz[1],sz[2],sz[3],datatype)) != 0 ) : - ( (err_rawfmt = initRawFile((char *)img_path_temp.str().c_str(),sz,datatype)) != 0 ) ) ) { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"VolumeConverter::generateTilesVaa3DRawMC: error in initializing block file - %s", err_rawfmt); - throw IOException(err_msg); - }; - - slice_start_temp += (int)sz[2]; - } - delete [] sz; - } - } - - //saving HERE - - // 2015-02-10. Giulio. @CHANGED changed how img_path is constructed - std::stringstream partial_img_path; - partial_img_path << H_DIR_path.str() << "/" - << this->getMultiresABS_V_string(i,start_height) << "_" - << this->getMultiresABS_H_string(i,start_width) << "_"; - - int slice_ind = (int)(n_slices_pred - slice_start[i]); - - std::stringstream img_path; - img_path << partial_img_path.str() << abs_pos_z.str(); - - /* 2015-02-06. Giulio. @ADDED optimization to reduce the number of open/close operations in append operations - * Since slices of the same block in a group are appended in sequence, to minimize the overhead of append operations, - * all slices of a group to be appended to the same block file are appended leaving the file open and positioned at - * end of the file. - * The number of pages of block files of interest can be easily computed as: - * - * number of slice of current block = stacks_depth[i][0][0][stack_block[i]] - * number of slice of next block = stacks_depth[i][0][0][stack_block[i]+1] - */ - - void *fhandle = 0; - int n_pages_block = stacks_depth[i][0][0][stack_block[i]]; // number of pages of current block - bool block_changed = false; // true if block is changed executing the next for cycle - // fhandle = open file corresponding to current block - if ( strcmp(saved_img_format,"Tiff3D") == 0 ) - openTiff3DFile((char *)img_path.str().c_str(),(char *)(slice_ind ? "a" : "w"),fhandle); - - // WARNING: assumes that block size along z is not less that z_size/(powInt(2,i)) - for(int buffer_z=0; buffer_zD0) /powInt(2,i)+buffer_z) > slice_end[i] ) { // start a new block along z - std::stringstream abs_pos_z_next; - abs_pos_z_next.width(6); - abs_pos_z_next.fill('0'); - abs_pos_z_next << (int)(this->getMultiresABS_D(i) + // all stacks start at the same D position - (powInt(2,i)*(slice_end[i]+1)) * volume->getVXL_D()); - img_path.str(""); - img_path << partial_img_path.str() << abs_pos_z_next.str(); - - slice_ind = 0; // 2015-02-10. Giulio. @CHANGED (int)(n_slices_pred - (slice_end[i]+1)) + buffer_z; - - // close(fhandle) i.e. file corresponding to current block - if ( strcmp(saved_img_format,"Tiff3D") == 0 ) - closeTiff3DFile(fhandle); - // fhandle = open file corresponding to next block - if ( strcmp(saved_img_format,"Tiff3D") == 0 ) - openTiff3DFile((char *)img_path.str().c_str(),(char *)"w",fhandle); - n_pages_block = stacks_depth[i][0][0][stack_block[i]+1]; - block_changed = true; - } - - if ( internal_rep == REAL_INTERNAL_REP ) - VirtualVolume::saveImage_to_Vaa3DRaw( - slice_ind, - img_path.str(), - rbuffer + buffer_z*(height/powInt(2,i))*(width/powInt(2,i)), // adds the stride - (int)height/(powInt(2,i)),(int)width/(powInt(2,i)), - start_height,end_height,start_width,end_width, - saved_img_format, saved_img_depth - ); - else {// internal_rep == UINT8_INTERNAL_REP - if ( strcmp(saved_img_format,"Tiff3D")==0 ) { - VirtualVolume::saveImage_from_UINT8_to_Tiff3D( - slice_ind, - img_path.str(), - ubuffer + c, - 1, - buffer_z*(height/powInt(2,i))*(width/powInt(2,i))*bytes_chan, // stride to be added for slice buffer_z - (int)height/(powInt(2,i)),(int)width/(powInt(2,i)), - start_height,end_height,start_width,end_width, - saved_img_format, saved_img_depth,fhandle,n_pages_block,false); - } - else { // can be only Vaa3DRaw - VirtualVolume::saveImage_from_UINT8_to_Vaa3DRaw( - slice_ind, - img_path.str(), - ubuffer + c, - 1, - buffer_z*(height/powInt(2,i))*(width/powInt(2,i))*bytes_chan, // stride to be added for slice buffer_z - (int)height/(powInt(2,i)),(int)width/(powInt(2,i)), - start_height,end_height,start_width,end_width, - saved_img_format, saved_img_depth); - } - } - } - - // close(fhandle) i.e. currently opened file - if ( strcmp(saved_img_format,"Tiff3D") == 0 ) - closeTiff3DFile(fhandle); - - start_width += stacks_width [i][stack_row][stack_column][0]; // WARNING TO BE CHECKED FOR CORRECTNESS - } - start_height += stacks_height[i][stack_row][0][0]; // WARNING TO BE CHECKED FOR CORRECTNESS - } - } - } - } - - //releasing allocated memory - if ( internal_rep == REAL_INTERNAL_REP ) - delete rbuffer; - else // internal_rep == UINT8_INTERNAL_REP - delete ubuffer[0]; // other buffer pointers are only offsets - } - - // reloads created volumes to generate .bin file descriptors at all resolutions - ref_sys reference(axis(1),axis(2),axis(3)); - TiledMCVolume *mcprobe; - TiledVolume *tprobe; - StackedVolume *sprobe; - sprobe = dynamic_cast(volume); - if ( sprobe ) { - reference.first = sprobe->getAXS_1(); - reference.second = sprobe->getAXS_2(); - reference.third = sprobe->getAXS_3(); - } - else { - tprobe = dynamic_cast(volume); - if ( tprobe ) { - reference.first = tprobe->getAXS_1(); - reference.second = tprobe->getAXS_2(); - reference.third = tprobe->getAXS_3(); - } - else { - mcprobe = dynamic_cast(volume); - if ( mcprobe ) { - reference.first = mcprobe->getAXS_1(); - reference.second = mcprobe->getAXS_2(); - reference.third = mcprobe->getAXS_3(); - } - } - } - for(int res_i=0; res_i< resolutions_size; res_i++) { - - if(resolutions[res_i]) { - - for ( int c=0; c object. A possible solution to implement - //is to check whether is a pointer to a object, then specialize it to and get its reference - //system. - TiledVolume temp_vol(resolution_dir.c_str(),reference, - volume->getVXL_V()*pow(2.0f,res_i), volume->getVXL_H()*pow(2.0f,res_i),volume->getVXL_D()*pow(2.0f,res_i)); - - // StackedVolume temp_vol(file_path[res_i].str().c_str(),ref_sys(axis(1),axis(2),axis(3)), volume->getVXL_V()*(res_i+1), - // volume->getVXL_H()*(res_i+1),volume->getVXL_D()*(res_i+1)); - } - - TiledMCVolume temp_mc_vol(file_path[res_i].str().c_str(),reference, - volume->getVXL_V()*pow(2.0f,res_i), volume->getVXL_H()*pow(2.0f,res_i),volume->getVXL_D()*pow(2.0f,res_i)); - - } - } - - - // ubuffer allocated anyway - delete ubuffer; - - // deallocate memory - for(int res_i=0; res_i< resolutions_size; res_i++) - { - for(int stack_row = 0; stack_row < n_stacks_V[res_i]; stack_row++) - { - for(int stack_col = 0; stack_col < n_stacks_H[res_i]; stack_col++) - { - delete[] stacks_height[res_i][stack_row][stack_col]; - delete[] stacks_width [res_i][stack_row][stack_col]; - delete[] stacks_depth [res_i][stack_row][stack_col]; - } - delete[] stacks_height[res_i][stack_row]; - delete[] stacks_width [res_i][stack_row]; - delete[] stacks_depth [res_i][stack_row]; - } - delete[] stacks_height[res_i]; - delete[] stacks_width[res_i]; - delete[] stacks_depth[res_i]; - } - - delete[] chans_dir; -} - -#endif - - -void VolumeConverter::generateTilesBDV_HDF5 ( std::string output_path, bool* resolutions, - int block_height, int block_width, int block_depth, int method, - bool show_progress_bar, const char* saved_img_format, - int saved_img_depth, std::string frame_dir ) throw (IOException) -{ - printf("in VolumeConverter::generateTilesBDV_HDF5(path = \"%s\", resolutions = ", output_path.c_str()); - for(int i=0; i< TMITREE_MAX_HEIGHT; i++) - printf("%d", resolutions[i]); - printf(", block_height = %d, block_width = %d, block_depth = %d, method = %d, show_progress_bar = %s, saved_img_format = %s, saved_img_depth = %d, frame_dir = \"%s\")\n", - block_height, block_width, block_depth, method, show_progress_bar ? "true" : "false", saved_img_format, saved_img_depth, frame_dir.c_str()); - - if ( saved_img_depth == 0 ) // default is to generate an image with the same depth of the source - saved_img_depth = volume->getBYTESxCHAN() * 8; - - if ( saved_img_depth != (volume->getBYTESxCHAN() * 8) ) { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"VolumeConverter::generateTilesVaa3DRaw: mismatch between bits per channel of source (%d) and destination (%d)", - volume->getBYTESxCHAN() * 8, saved_img_depth); - throw IOException(err_msg); - } - - //LOCAL VARIABLES - sint64 height, width, depth; //height, width and depth of the whole volume that covers all stacks - real32* rbuffer; //buffer where temporary image data are stored (REAL_INTERNAL_REP) - uint8** ubuffer; //array of buffers where temporary image data of channels are stored (UINT8_INTERNAL_REP) - int bytes_chan = volume->getBYTESxCHAN(); - int org_channels = 0; //store the number of channels read the first time (for checking purposes) - sint64 z_ratio, z_max_res; - int resolutions_size = 0; - - void *file_descr; - sint64 *hyperslab_descr = new sint64[4*3]; // four 3-valued parameters: [ start(offset), stride count(size), block ] - memset(hyperslab_descr,0,4*3*sizeof(sint64)); - sint64 *buf_dims = new sint64[3]; // dimensions of the buffer in which the subvolume is stored at a given resolution - memset(buf_dims,0,3*sizeof(sint64)); - - if ( volume == 0 ) { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"VolumeConverter::generateTilesBDV_HDF5: undefined source volume"); - throw IOException(err_msg); - } - - // HDF5 crea il file HDF5 se non esiste altrimenti determina i setup e i time point gia' presenti - BDV_HDF5init(output_path,file_descr,volume->getBYTESxCHAN()); - - //initializing the progress bar - char progressBarMsg[200]; - if(show_progress_bar) - { - imProgressBar::getInstance()->start("Multiresolution tile generation"); - imProgressBar::getInstance()->update(0,"Initializing..."); - imProgressBar::getInstance()->show(); - } - - // 2015-03-03. Giulio. @ADDED selection of IO plugin if not provided. - if(iom::IMOUT_PLUGIN.compare("empty") == 0) - { - iom::IMOUT_PLUGIN = "tiff3D"; - } - - //computing dimensions of volume to be stitched - //this->computeVolumeDims(exclude_nonstitchable_stacks, _ROW_START, _ROW_END, _COL_START, _COL_END, _D0, _D1); - width = this->H1-this->H0; - height = this->V1-this->V0; - depth = this->D1-this->D0; - - // code for testing - //uint8 *temp = volume->loadSubvolume_to_UINT8( - // 10,height-10,10,width-10,10,depth-10, - // &channels); - - //these parameters are used here for chunk dimensions; the default values should be passed without changes to BDV_HDF5 routines - //block_height = (block_height == -1 ? (int)height : block_height); - //block_width = (block_width == -1 ? (int)width : block_width); - //block_depth = (block_depth == -1 ? (int)depth : block_depth); - //if(block_height < TMITREE_MIN_BLOCK_DIM || block_width < TMITREE_MIN_BLOCK_DIM /* 2014-11-10. Giulio. @REMOVED (|| block_depth < TMITREE_MIN_BLOCK_DIM9 */) - //{ - // char err_msg[STATIC_STRINGS_SIZE]; - // sprintf(err_msg,"The minimum dimension for block height, width, and depth is %d", TMITREE_MIN_BLOCK_DIM); - // throw IOException(err_msg); - //} - - if(resolutions == NULL) - { - resolutions = new bool; - *resolutions = true; - resolutions_size = 1; - } - else - for(int i=0; igetVXL_V(),volume->getVXL_H(),volume->getVXL_D(), - resolutions,resolutions_size,channels,block_height,block_width,block_depth); - - BDV_HDF5addTimepoint(file_descr); - - //BDV_HDF5close(file_descr); - - //ALLOCATING the MEMORY SPACE for image buffer - z_max_res = powInt(2,resolutions_size-1); - - // the following check does not make sense for Fiji_HDF5 format - //if ( z_max_res > block_depth/2 ) { - // char err_msg[STATIC_STRINGS_SIZE]; - // sprintf(err_msg, "in generateTilesVaa3DRaw(...): too much resolutions(%d): too much slices (%lld) in the buffer \n", resolutions_size, z_max_res); - // throw IOException(err_msg); - //} - z_ratio=depth/z_max_res; - - //allocated even if not used - ubuffer = new uint8 *[channels]; - memset(ubuffer,0,channels*sizeof(uint8)); - org_channels = channels; // save for checks - - // z must begin from D0 (absolute index into the volume) since it is used to compute tha file names (containing the absolute position along D) - for(sint64 z = this->D0, z_parts = 1; z < this->D1; z += z_max_res, z_parts++) - { - // fill one slice block - if ( internal_rep == REAL_INTERNAL_REP ) - rbuffer = volume->loadSubvolume_to_real32(V0,V1,H0,H1,(int)(z-D0),(z-D0+z_max_res <= D1) ? (int)(z-D0+z_max_res) : D1); - else { // internal_rep == UINT8_INTERNAL_REP - ubuffer[0] = volume->loadSubvolume_to_UINT8(V0,V1,H0,H1,(int)(z-D0),(z-D0+z_max_res <= D1) ? (int)(z-D0+z_max_res) : D1,&channels,iim::NATIVE_RTYPE); - if ( org_channels != channels ) { - char err_msg[STATIC_STRINGS_SIZE]; - sprintf(err_msg,"The volume contains images with a different number of channels (%d,%d)", org_channels, channels); - throw IOException(err_msg); - } - - for (int i=1; iupdate(((float)(z-D0+z_max_res-1)*100/(float)depth), progressBarMsg); - imProgressBar::getInstance()->show(); - } - - //saving current buffer data at selected resolutions and in multitile format - for(int i=0; i< resolutions_size; i++) - { - // HDF5 crea i gruppi relativi a questa risoluzione in ciascun setup del time point corrente - - if(show_progress_bar) - { - sprintf(progressBarMsg, "Generating resolution %d of %d",i+1,std::max(resolutions_size, resolutions_size)); - imProgressBar::getInstance()->updateInfo(progressBarMsg); - imProgressBar::getInstance()->show(); - } - - //buffer size along D is different when the remainder of the subdivision by z_max_res is considered - sint64 z_size = (z_parts<=z_ratio) ? z_max_res : (depth%z_max_res); - - //halvesampling resolution if current resolution is not the deepest one - if(i!=0) { - if ( internal_rep == REAL_INTERNAL_REP ) - VirtualVolume::halveSample(rbuffer,(int)height/(powInt(2,i-1)),(int)width/(powInt(2,i-1)),(int)z_size/(powInt(2,i-1)),method); - else // internal_rep == UINT8_INTERNAL_REP - VirtualVolume::halveSample_UINT8(ubuffer,(int)height/(powInt(2,i-1)),(int)width/(powInt(2,i-1)),(int)z_size/(powInt(2,i-1)),channels,method,bytes_chan); - } - - //saving at current resolution if it has been selected and iff buffer is at least 1 voxel (Z) deep - if(resolutions[i] && (z_size/(powInt(2,i))) > 0) - { - if(show_progress_bar) - { - sprintf(progressBarMsg, "Saving to disc resolution %d",i+1); - imProgressBar::getInstance()->updateInfo(progressBarMsg); - imProgressBar::getInstance()->show(); - } - - //std::stringstream res_name; - //res_name << i; - - for ( int c=0; cgetDIM_T(); t++) - { - imProgressBar::instance()->setMessage(1, strprintf("Converting time frame %d/%d", t+1, volume->getDIM_T()).c_str()); - volume->setActiveFrames(t,t); - std::string frame_dir = iim::TIME_FRAME_PREFIX + strprintf("%06d", t); - if(output_format.compare(iim::STACKED_FORMAT) == 0) - generateTiles(output_path, resolutions, block_height, block_width, method, true, iim::DEF_IMG_FORMAT.c_str(), output_bitdepth, frame_dir); - else if(output_format.compare(iim::TILED_FORMAT) == 0) - generateTilesVaa3DRaw(output_path, resolutions, block_height, block_width, block_depth, method, true, "raw", output_bitdepth, frame_dir); - else if(output_format.compare(iim::TILED_MC_FORMAT) == 0) - generateTilesVaa3DRawMC(output_path, resolutions, block_height, block_width, block_depth, method, true, "raw", output_bitdepth, frame_dir); - else if(output_format.compare(iim::TILED_TIF3D_FORMAT) == 0) - generateTilesVaa3DRaw(output_path, resolutions, block_height, block_width, block_depth, method, true, "Tiff3D", output_bitdepth, frame_dir); - else if(output_format.compare(iim::TILED_MC_TIF3D_FORMAT) == 0) - generateTilesVaa3DRawMC(output_path, resolutions, block_height, block_width, block_depth, method, true, "Tiff3D", output_bitdepth, frame_dir); - else - throw iim::IOException(strprintf("Output format \"%s\" not supported", output_format.c_str()).c_str()); - } - imProgressBar::instance()->reset(); - } - else - { - if(output_format.compare(iim::STACKED_FORMAT) == 0) - generateTiles(output_path, resolutions, block_height, block_width, method, true, iim::DEF_IMG_FORMAT.c_str(), output_bitdepth); - else if(output_format.compare(iim::TILED_FORMAT) == 0) - generateTilesVaa3DRaw(output_path, resolutions, block_height, block_width, block_depth, method, true, "raw", output_bitdepth); - else if(output_format.compare(iim::TILED_MC_FORMAT) == 0) - generateTilesVaa3DRawMC(output_path, resolutions, block_height, block_width, block_depth, method, true, "raw", output_bitdepth); - else if(output_format.compare(iim::TILED_TIF3D_FORMAT) == 0) - generateTilesVaa3DRaw(output_path, resolutions, block_height, block_width, block_depth, method, true, "Tiff3D", output_bitdepth); - else if(output_format.compare(iim::TILED_MC_TIF3D_FORMAT) == 0) - generateTilesVaa3DRawMC(output_path, resolutions, block_height, block_width, block_depth, method, true, "Tiff3D", output_bitdepth); - else if(output_format.compare(iim::BDV_HDF5_FORMAT) == 0) - generateTilesBDV_HDF5(output_path,resolutions, block_height,block_width,block_depth,method, true,"Tiff3D",output_bitdepth); - else - throw iim::IOException(strprintf("Output format \"%s\" not supported", output_format.c_str()).c_str()); - } -} - - diff --git a/v3d_main/terafly/src/core/volumeconverter/VolumeConverter.h b/v3d_main/terafly/src/core/volumeconverter/VolumeConverter.h deleted file mode 100755 index afdab6edd3..0000000000 --- a/v3d_main/terafly/src/core/volumeconverter/VolumeConverter.h +++ /dev/null @@ -1,262 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -#ifndef VOLUME_CONVERTER_H -#define VOLUME_CONVERTER_H - -/* - * class VolumeConverter implements a converter form 3D-4D images in several formats - * to the stacked format used by the tolls TeraStitcher and TeraFly (aka TeraManager) - * - * To use the class the user has to: - - * 1. call the method setSrcVolume on a newly created instance of the class passing - * the following parameters: - * - * - directory or file name of the source image (the file name if the image - * is stored in a single file, e.g. in V3D raw format) - * - format of the source image ("Stacked" for Terastitcher stacked format, - * "Simple" for sequence of numbered .tif images in the same directory, - * "Raw" for V3D raw 4D format) - * - format of the output image ("intensity" for real valued pixels in [0,1], - * "graylevel" for integer valued pixels in [0,255], "RGB" for pixel represented - * according to RGB format) - * - * If the source image is multi channel the format of the output image is - * automatically set to "RGB" - * - * WARNINIG: - * graylevel output format not supported yet for Simple source format - * intensity output format not supported yet for Raw source format - * - * Allowed suffixes for V3D raw 4D format are: .raw .RAW, .v3draw .V3DRAW - * - * - * 2. call the method generateTiles passing the following parameters: - * - * - directory where to store the output image - * - number of resolutions to be generated - * - the height of the slices of the substacks in the output image - * - the width of the slices of the substacks in the output image - */ - - -#include -#include - -#include "../imagemanager/VirtualVolume.h" - -// possible output format -#define REAL_REPRESENTATION "intensity" // images are managed internally with REAL_INTERNAL_REP representation - // and saved as graylevel images -#define UINT8_REPRESENTATION "graylevel" // images are managed internally with UINT8_INTERNAL_REP representation - // and saved as graylevel images -#define UINT8x3_REPRESENTATION "RGB" // images are managed internally with UINT8_INTERNAL_REP representation - // and saved as RGB images - -#define REAL_INTERNAL_REP 1 // gray level images, pixels are represented ad real numbers in [0,1] -#define UINT8_INTERNAL_REP 2 // multi-channel images, pixels are represented as 8 bit integers - - -class VolumeConverter -{ - private: - - /******OBJECT MEMBERS******/ - iim::VirtualVolume *volume; //pointer to the object to be stitched - int V0, V1, H0, H1, D0, D1; //voxel intervals that identify the final stitched volume - int ROW_START, COL_START, ROW_END, COL_END; //stack indexes that identify the stacks involved in stitching - - int internal_rep; // internal representation of pixels: - // REAL_INTERNAL_REP: gray level images, pixels are represented ad real numbers in [0,1] - // UINT8_INTERNAL_REP: multi-channel images, pixels are represented as 8 bit integers - - int channels; // set only if internal_rep = UINT8_INTERNAL_REP - // possible values: 1 for gray level images - // 3 for color images represented in RGB format - - const char *out_fmt; // output format (for future use, currently not used: the output format is derived - // implicitly from internal_rep and the format of the source image) - - public: - - // Constructors - VolumeConverter(void); - - // Desctructor - ~VolumeConverter(); - - /************************************************************************************************************* - * Method to set (create) the source volume to be converted - * _root_dir : directory path where the volume is stored - * _fmt : format in which the source volume is stored (default: STACKED_FORMAT) - * _internal_fmt : format in which the pixels are represented internally (default: REAL_REPRESENTATION) - * - * When _out_fmt=REAL_REPRESENTATION the image must be graylevel - * When _out_fmt=UINT8_REPRESENTATION or _out_fmt=UINT8x3_REPRESENTATION the image can be both - * graylevel and multi channel and it will be saved as RGB; at most three channels are supported; if channels - * of original image are two, the third RGB channel (Blue channel) is set to all zero - *************************************************************************************************************/ - void setSrcVolume(const char* _root_dir, const char* _fmt = iim::STACKED_FORMAT.c_str(), - const char* _out_fmt = REAL_REPRESENTATION, bool time_series = false) throw (iim::IOException); - - // unified access point for volume conversion (@ADDED by Alessandro on 2014-02-24) - void convertTo( - std::string output_path, // path where to save the converted volume - std::string output_format, // format of the converted volume (see IM_config.h) - int output_bitdepth = iim::NUL_IMG_DEPTH, // output image bitdepth - bool isTimeSeries = false, // whether the volume is a time series - bool *resolutions = 0, // array of resolutions - int block_height = -1, // tile's height (for tiled formats) - int block_width = -1, // tile's width (for tiled formats) - int block_depth = -1, // tile's depth (for tiled formats) - int method = HALVE_BY_MEAN // downsampling method - ) throw (iim::IOException); - - /************************************************************************************************************* - * Method to be called for tile generation. <> parameters are mandatory, while [] are optional. - * : absolute directory path where generated tiles have to be stored. - * [resolutions] : pointer to an array of S_MAX_MULTIRES size which boolean entries identify the acti- - * vaction/deactivation of the i-th resolution. If not given, all resolutions will be - * activated. - * [slice_height/width] : desired dimensions of tiles slices after merging. It is actually an upper-bound of - * the actual slice dimensions, which will be computed in such a way that all tiles di- - * mensions can differ by 1 pixel only along both directions. If not given, the maximum - * allowed dimensions will be set, which will result in a volume composed by one large - * tile only. - * [method] : method used to compute pixel whel halving image size (default: by mean) - * [show_progress_bar] : enables/disables progress bar with estimated time remaining. - * [saved_img_format] : determines saved images format ("png","tif","jpeg", etc.). - * [saved_img_depth] : determines saved images bitdepth (16 or 8). - **************************************************************************************************************/ - void generateTiles(std::string output_path, bool* resolutions = NULL, - int slice_height = -1, int slice_width = -1, int method = HALVE_BY_MEAN, bool show_progress_bar = true, - const char* saved_img_format = iim::DEF_IMG_FORMAT.c_str(), int saved_img_depth = iim::NUL_IMG_DEPTH, - std::string frame_dir = "") throw (iim::IOException); - - - /************************************************************************************************************* - * Method to be called for tile generation. <> parameters are mandatory, while [] are optional. - * : absolute directory path where generated tiles have to be stored. - * [resolutions] : pointer to an array of S_MAX_MULTIRES size which boolean entries identify the acti- - * vaction/deactivation of the i-th resolution. If not given, all resolutions will be - * activated. - * [block_height] : desired dimensions of tiled blocks after merging. It is actually an upper-bound of - * [block_width] the actual slice dimensions, which will be computed in such a way that all tiles di- - * [block_depth] mensions can differ by 1 pixel only along both directions. If not given, the maximum - * allowed dimensions will be set, which will result in a volume composed by one large - * tile only. - * [method] : method used to compute pixel whel halving image size (default: by mean) - * [show_progress_bar] : enables/disables progress bar with estimated time remaining. - * [saved_img_format] : determines saved images format ("raw", "png","tif","jpeg", etc.). - * [saved_img_depth] : determines saved images bitdepth (16 or 8). - * [frame_dir] : name of the directory containing a frame (without the final "/") - * if it is a null string the image does not belong to a time serie (default) - **************************************************************************************************************/ - void generateTilesVaa3DRaw(std::string output_path, bool* resolutions = NULL, - int block_height = -1, int block_width = -1, int block_depth = -1, int method = HALVE_BY_MEAN, bool show_progress_bar = true, - const char* saved_img_format = "Vaa3DRaw", int saved_img_depth = iim::NUL_IMG_DEPTH, - std::string frame_dir = "") throw (iim::IOException); - - - /************************************************************************************************************* - * Get methods - **************************************************************************************************************/ - int getV0(){return V0;} - int getV1(){return V1;} - int getH0(){return H0;} - int getH1(){return H1;} - int getD0(){return D0;} - int getD1(){return D1;} - int getROW0(){return ROW_START;} - int getROW1(){return ROW_END;} - int getCOL0(){return COL_START;} - int getCOL1(){return COL_END;} - iim::VirtualVolume *getVolume() {return volume;} - - /************************************************************************************************************* - * Functions used to obtain absolute coordinates at different resolutions from relative coordinates - **************************************************************************************************************/ - int getMultiresABS_V(int res, int REL_V); - std::string getMultiresABS_V_string(int res, int REL_V); - int getMultiresABS_H(int res, int REL_H); - std::string getMultiresABS_H_string(int res, int REL_H); - int getMultiresABS_D(int res); - - - /************************************************************************************************************* - * NEW TILED FORMAT SUPPORTING MULTIPLE CHANNELS - **************************************************************************************************************/ - - /************************************************************************************************************* - * Method to be called for tile generation. <> parameters are mandatory, while [] are optional. - * : absolute directory path where generated tiles have to be stored. - * [resolutions] : pointer to an array of S_MAX_MULTIRES size which boolean entries identify the acti- - * vaction/deactivation of the i-th resolution. If not given, all resolutions will be - * activated. - * [block_height] : desired dimensions of tiled blocks after merging. It is actually an upper-bound of - * [block_width] the actual slice dimensions, which will be computed in such a way that all tiles di- - * [block_depth] mensions can differ by 1 pixel only along both directions. If not given, the maximum - * allowed dimensions will be set, which will result in a volume composed by one large - * tile only. - * [method] : method used to compute pixel whel halving image size (default: by mean) - * [show_progress_bar] : enables/disables progress bar with estimated time remaining. - * [saved_img_format] : determines saved images format ("raw", "png","tif","jpeg", etc.). - * [saved_img_depth] : determines saved images bitdepth (16 or 8). - **************************************************************************************************************/ - void generateTilesVaa3DRawMC ( std::string output_path, bool* resolutions = NULL, - int block_height = -1, int block_width = -1, int block_depth = -1, int method = HALVE_BY_MEAN, bool show_progress_bar = true, - const char* saved_img_format = "Vaa3DRaw", int saved_img_depth = iim::NUL_IMG_DEPTH, - std::string frame_dir = "") throw (iim::IOException); - - /************************************************************************************************************* - * NEW FORMAT SUPPORTING BDV HDF5 custom format - **************************************************************************************************************/ - - /************************************************************************************************************* - * Method to be called for tile generation. <> parameters are mandatory, while [] are optional. - * : absolute directory path where generated tiles have to be stored. - * [resolutions] : pointer to an array of S_MAX_MULTIRES size which boolean entries identify the acti- - * vaction/deactivation of the i-th resolution. If not given, all resolutions will be - * activated. - * [block_height] : desired dimensions of tiled blocks after merging. It is actually an upper-bound of - * [block_width] the actual slice dimensions, which will be computed in such a way that all tiles di- - * [block_depth] mensions can differ by 1 pixel only along both directions. If not given, the maximum - * allowed dimensions will be set, which will result in a volume composed by one large - * tile only. - * [method] : method used to compute pixel whel halving image size (default: by mean) - * [show_progress_bar] : enables/disables progress bar with estimated time remaining. - * [saved_img_format] : determines saved images format ("raw", "png","tif","jpeg", etc.). - * [saved_img_depth] : determines saved images bitdepth (16 or 8). - **************************************************************************************************************/ - void generateTilesBDV_HDF5 ( std::string output_path, bool* resolutions = NULL, - int block_height = -1, int block_width = -1, int block_depth = -1, int method = HALVE_BY_MEAN, bool show_progress_bar = true, - const char* saved_img_format = "h5", int saved_img_depth = iim::NUL_IMG_DEPTH, - std::string frame_dir = "") throw (iim::IOException); - -}; - -#endif - - diff --git a/v3d_main/terafly/src/core/volumeconverter/dirent_win.h b/v3d_main/terafly/src/core/volumeconverter/dirent_win.h deleted file mode 100755 index 6425174092..0000000000 --- a/v3d_main/terafly/src/core/volumeconverter/dirent_win.h +++ /dev/null @@ -1,230 +0,0 @@ -/***************************************************************************** - * dirent.h - dirent API for Microsoft Visual Studio - * - * Copyright (C) 2006 Toni Ronkko - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * ``Software''), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL TONI RONKKO BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - * - * Dec 15, 2009, John Cunningham - * Added rewinddir member function - * - * Jan 18, 2008, Toni Ronkko - * Using FindFirstFileA and WIN32_FIND_DATAA to avoid converting string - * between multi-byte and unicode representations. This makes the - * code simpler and also allows the code to be compiled under MingW. Thanks - * to Azriel Fasten for the suggestion. - * - * Mar 4, 2007, Toni Ronkko - * Bug fix: due to the strncpy_s() function this file only compiled in - * Visual Studio 2005. Using the new string functions only when the - * compiler version allows. - * - * Nov 2, 2006, Toni Ronkko - * Major update: removed support for Watcom C, MS-DOS and Turbo C to - * simplify the file, updated the code to compile cleanly on Visual - * Studio 2005 with both unicode and multi-byte character strings, - * removed rewinddir() as it had a bug. - * - * Aug 20, 2006, Toni Ronkko - * Removed all remarks about MSVC 1.0, which is antiqued now. Simplified - * comments by removing SGML tags. - * - * May 14 2002, Toni Ronkko - * Embedded the function definitions directly to the header so that no - * source modules need to be included in the Visual Studio project. Removed - * all the dependencies to other projects so that this very header can be - * used independently. - * - * May 28 1998, Toni Ronkko - * First version. - *****************************************************************************/ -#ifndef DIRENT_H -#define DIRENT_H - -#include -#include -#include - - -typedef struct dirent -{ - char d_name[MAX_PATH + 1]; /* current dir entry (multi-byte char string) */ - WIN32_FIND_DATAA data; /* file attributes */ -} dirent; - - -typedef struct DIR -{ - dirent current; /* Current directory entry */ - int cached; /* Indicates un-processed entry in memory */ - HANDLE search_handle; /* File search handle */ - char patt[MAX_PATH + 3]; /* search pattern (3 = pattern + "\\*\0") */ -} DIR; - - -/* Forward declarations */ -static DIR *opendir (const char *dirname); -static struct dirent *readdir (DIR *dirp); -static int closedir (DIR *dirp); -static void rewinddir(DIR* dirp); - - -/* Use the new safe string functions introduced in Visual Studio 2005 */ -#if defined(_MSC_VER) && _MSC_VER >= 1400 -# define STRNCPY(dest,src,size) strncpy_s((dest),(size),(src),_TRUNCATE) -#else -# define STRNCPY(dest,src,size) strncpy((dest),(src),(size)) -#endif - - -/***************************************************************************** - * Open directory stream DIRNAME for read and return a pointer to the - * internal working area that is used to retrieve individual directory - * entries. - */ -static DIR *opendir(const char *dirname) -{ - DIR *dirp; - assert (dirname != NULL); - assert (strlen (dirname) < MAX_PATH); - - /* construct new DIR structure */ - dirp = (DIR*) malloc (sizeof (struct DIR)); - if (dirp != NULL) { - char *p; - - /* take directory name... */ - STRNCPY (dirp->patt, dirname, sizeof(dirp->patt)); - dirp->patt[MAX_PATH] = '\0'; - - /* ... and append search pattern to it */ - p = strchr (dirp->patt, '\0'); - if (dirp->patt < p && *(p-1) != '\\' && *(p-1) != ':') { - *p++ = '\\'; - } - *p++ = '*'; - *p = '\0'; - - /* open stream and retrieve first file */ - dirp->search_handle = FindFirstFileA (dirp->patt, &dirp->current.data); - if (dirp->search_handle == INVALID_HANDLE_VALUE) { - /* invalid search pattern? */ - free (dirp); - return NULL; - } - - /* there is an un-processed directory entry in memory now */ - dirp->cached = 1; - } - - return dirp; -} - - -/***************************************************************************** - * Read a directory entry, and return a pointer to a dirent structure - * containing the name of the entry in d_name field. Individual directory - * entries returned by this very function include regular files, - * sub-directories, pseudo-directories "." and "..", but also volume labels, - * hidden files and system files may be returned. - */ -static struct dirent *readdir(DIR *dirp) -{ - assert (dirp != NULL); - - if (dirp->search_handle == INVALID_HANDLE_VALUE) { - /* directory stream was opened/rewound incorrectly or ended normally */ - return NULL; - } - - /* get next directory entry */ - if (dirp->cached != 0) { - /* a valid directory entry already in memory */ - dirp->cached = 0; - } else { - /* read next directory entry from disk */ - if (FindNextFileA (dirp->search_handle, &dirp->current.data) == FALSE) { - /* the very last file has been processed or an error occured */ - FindClose (dirp->search_handle); - dirp->search_handle = INVALID_HANDLE_VALUE; - return NULL; - } - } - - /* copy as a multibyte character string */ - STRNCPY ( dirp->current.d_name, - dirp->current.data.cFileName, - sizeof(dirp->current.d_name) ); - dirp->current.d_name[MAX_PATH] = '\0'; - - return &dirp->current; -} - - -/***************************************************************************** - * Close directory stream opened by opendir() function. Close of the - * directory stream invalidates the DIR structure as well as any previously - * read directory entry. - */ -static int closedir(DIR *dirp) -{ - assert (dirp != NULL); - - /* release search handle */ - if (dirp->search_handle != INVALID_HANDLE_VALUE) { - FindClose (dirp->search_handle); - dirp->search_handle = INVALID_HANDLE_VALUE; - } - - /* release directory handle */ - free (dirp); - return 0; -} - - -/***************************************************************************** - * Resets the position of the directory stream to which dirp refers to the - * beginning of the directory. It also causes the directory stream to refer - * to the current state of the corresponding directory, as a call to opendir() - * would have done. If dirp does not refer to a directory stream, the effect - * is undefined. - */ -static void rewinddir(DIR* dirp) -{ - /* release search handle */ - if (dirp->search_handle != INVALID_HANDLE_VALUE) { - FindClose (dirp->search_handle); - dirp->search_handle = INVALID_HANDLE_VALUE; - } - - /* open new search handle and retrieve first file */ - dirp->search_handle = FindFirstFileA (dirp->patt, &dirp->current.data); - if (dirp->search_handle == INVALID_HANDLE_VALUE) { - /* invalid search pattern? */ - free (dirp); - return; - } - - /* there is an un-processed directory entry in memory now */ - dirp->cached = 1; -} - - -#endif /*DIRENT_H*/ diff --git a/v3d_main/terafly/src/core/volumemanager/CMakeLists.txt b/v3d_main/terafly/src/core/volumemanager/CMakeLists.txt deleted file mode 100644 index ce35050540..0000000000 --- a/v3d_main/terafly/src/core/volumemanager/CMakeLists.txt +++ /dev/null @@ -1,14 +0,0 @@ -# CmakeLists.txt in volumemanager dir - -# add used modules to include path -include_directories (${TeraStitcher_SOURCE_DIR}/iomanager) -include_directories (${TeraStitcher_SOURCE_DIR}/stitcher) -include_directories (${TeraStitcher_SOURCE_DIR}/tinyxml) - -# add 3rd party modules to include path -include_directories(${TeraStitcher_SOURCE_DIR}/3rdparty) - -# add STATIC library from the all .h and .cpp files -file(GLOB volumemanager_headers *.h) -file(GLOB volumemanager_sources *.cpp) -add_library(volumemanager STATIC ${volumemanager_headers} ${volumemanager_sources}) \ No newline at end of file diff --git a/v3d_main/terafly/src/core/volumemanager/dirent_win.h b/v3d_main/terafly/src/core/volumemanager/dirent_win.h deleted file mode 100644 index 6425174092..0000000000 --- a/v3d_main/terafly/src/core/volumemanager/dirent_win.h +++ /dev/null @@ -1,230 +0,0 @@ -/***************************************************************************** - * dirent.h - dirent API for Microsoft Visual Studio - * - * Copyright (C) 2006 Toni Ronkko - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * ``Software''), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL TONI RONKKO BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - * - * Dec 15, 2009, John Cunningham - * Added rewinddir member function - * - * Jan 18, 2008, Toni Ronkko - * Using FindFirstFileA and WIN32_FIND_DATAA to avoid converting string - * between multi-byte and unicode representations. This makes the - * code simpler and also allows the code to be compiled under MingW. Thanks - * to Azriel Fasten for the suggestion. - * - * Mar 4, 2007, Toni Ronkko - * Bug fix: due to the strncpy_s() function this file only compiled in - * Visual Studio 2005. Using the new string functions only when the - * compiler version allows. - * - * Nov 2, 2006, Toni Ronkko - * Major update: removed support for Watcom C, MS-DOS and Turbo C to - * simplify the file, updated the code to compile cleanly on Visual - * Studio 2005 with both unicode and multi-byte character strings, - * removed rewinddir() as it had a bug. - * - * Aug 20, 2006, Toni Ronkko - * Removed all remarks about MSVC 1.0, which is antiqued now. Simplified - * comments by removing SGML tags. - * - * May 14 2002, Toni Ronkko - * Embedded the function definitions directly to the header so that no - * source modules need to be included in the Visual Studio project. Removed - * all the dependencies to other projects so that this very header can be - * used independently. - * - * May 28 1998, Toni Ronkko - * First version. - *****************************************************************************/ -#ifndef DIRENT_H -#define DIRENT_H - -#include -#include -#include - - -typedef struct dirent -{ - char d_name[MAX_PATH + 1]; /* current dir entry (multi-byte char string) */ - WIN32_FIND_DATAA data; /* file attributes */ -} dirent; - - -typedef struct DIR -{ - dirent current; /* Current directory entry */ - int cached; /* Indicates un-processed entry in memory */ - HANDLE search_handle; /* File search handle */ - char patt[MAX_PATH + 3]; /* search pattern (3 = pattern + "\\*\0") */ -} DIR; - - -/* Forward declarations */ -static DIR *opendir (const char *dirname); -static struct dirent *readdir (DIR *dirp); -static int closedir (DIR *dirp); -static void rewinddir(DIR* dirp); - - -/* Use the new safe string functions introduced in Visual Studio 2005 */ -#if defined(_MSC_VER) && _MSC_VER >= 1400 -# define STRNCPY(dest,src,size) strncpy_s((dest),(size),(src),_TRUNCATE) -#else -# define STRNCPY(dest,src,size) strncpy((dest),(src),(size)) -#endif - - -/***************************************************************************** - * Open directory stream DIRNAME for read and return a pointer to the - * internal working area that is used to retrieve individual directory - * entries. - */ -static DIR *opendir(const char *dirname) -{ - DIR *dirp; - assert (dirname != NULL); - assert (strlen (dirname) < MAX_PATH); - - /* construct new DIR structure */ - dirp = (DIR*) malloc (sizeof (struct DIR)); - if (dirp != NULL) { - char *p; - - /* take directory name... */ - STRNCPY (dirp->patt, dirname, sizeof(dirp->patt)); - dirp->patt[MAX_PATH] = '\0'; - - /* ... and append search pattern to it */ - p = strchr (dirp->patt, '\0'); - if (dirp->patt < p && *(p-1) != '\\' && *(p-1) != ':') { - *p++ = '\\'; - } - *p++ = '*'; - *p = '\0'; - - /* open stream and retrieve first file */ - dirp->search_handle = FindFirstFileA (dirp->patt, &dirp->current.data); - if (dirp->search_handle == INVALID_HANDLE_VALUE) { - /* invalid search pattern? */ - free (dirp); - return NULL; - } - - /* there is an un-processed directory entry in memory now */ - dirp->cached = 1; - } - - return dirp; -} - - -/***************************************************************************** - * Read a directory entry, and return a pointer to a dirent structure - * containing the name of the entry in d_name field. Individual directory - * entries returned by this very function include regular files, - * sub-directories, pseudo-directories "." and "..", but also volume labels, - * hidden files and system files may be returned. - */ -static struct dirent *readdir(DIR *dirp) -{ - assert (dirp != NULL); - - if (dirp->search_handle == INVALID_HANDLE_VALUE) { - /* directory stream was opened/rewound incorrectly or ended normally */ - return NULL; - } - - /* get next directory entry */ - if (dirp->cached != 0) { - /* a valid directory entry already in memory */ - dirp->cached = 0; - } else { - /* read next directory entry from disk */ - if (FindNextFileA (dirp->search_handle, &dirp->current.data) == FALSE) { - /* the very last file has been processed or an error occured */ - FindClose (dirp->search_handle); - dirp->search_handle = INVALID_HANDLE_VALUE; - return NULL; - } - } - - /* copy as a multibyte character string */ - STRNCPY ( dirp->current.d_name, - dirp->current.data.cFileName, - sizeof(dirp->current.d_name) ); - dirp->current.d_name[MAX_PATH] = '\0'; - - return &dirp->current; -} - - -/***************************************************************************** - * Close directory stream opened by opendir() function. Close of the - * directory stream invalidates the DIR structure as well as any previously - * read directory entry. - */ -static int closedir(DIR *dirp) -{ - assert (dirp != NULL); - - /* release search handle */ - if (dirp->search_handle != INVALID_HANDLE_VALUE) { - FindClose (dirp->search_handle); - dirp->search_handle = INVALID_HANDLE_VALUE; - } - - /* release directory handle */ - free (dirp); - return 0; -} - - -/***************************************************************************** - * Resets the position of the directory stream to which dirp refers to the - * beginning of the directory. It also causes the directory stream to refer - * to the current state of the corresponding directory, as a call to opendir() - * would have done. If dirp does not refer to a directory stream, the effect - * is undefined. - */ -static void rewinddir(DIR* dirp) -{ - /* release search handle */ - if (dirp->search_handle != INVALID_HANDLE_VALUE) { - FindClose (dirp->search_handle); - dirp->search_handle = INVALID_HANDLE_VALUE; - } - - /* open new search handle and retrieve first file */ - dirp->search_handle = FindFirstFileA (dirp->patt, &dirp->current.data); - if (dirp->search_handle == INVALID_HANDLE_VALUE) { - /* invalid search pattern? */ - free (dirp); - return; - } - - /* there is an un-processed directory entry in memory now */ - dirp->cached = 1; -} - - -#endif /*DIRENT_H*/ diff --git a/v3d_main/terafly/src/core/volumemanager/vmBlock.cpp b/v3d_main/terafly/src/core/volumemanager/vmBlock.cpp deleted file mode 100644 index a0614ed49e..0000000000 --- a/v3d_main/terafly/src/core/volumemanager/vmBlock.cpp +++ /dev/null @@ -1,988 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* -* Bria, A., Iannello, G., "TeraStitcher - A Tool for Fast 3D Automatic Stitching of Teravoxel-sized Microscopy Images", (2012) BMC Bioinformatics, 13 (1), art. no. 316. -* -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -* 2015-08-05. Giulio. @ADDED detailed error messages in loadImageStack and compute_z_ranges -* 2015-08-01. Giulio. @FIXED bugs in sparse data management (compute_z_ranges) -* 2015-07-22. Giluio. @ADDED support for spase data. -* 2015-02-13. Giulio. @CHANGED 3D ioplugin is called instead of Tiff3DMngr functions -* 2015-01-17. Alessandro. @ADDED constructor for initialization from XML. -* 2015-01-17. Alessandro. @ADDED support for all-in-one-folder data (import from xml only). -* 2015-01-17. Alessandro. @FIXED missing throw(iom::exception) declaration in many methods. -* 2014-11-04. Giulio. @FIXED bug in conversion from pixel uint16 to float -* 2014-09-09. Alessandro. @FIXED 'getXML()' method to deal with empty stacks. -* 2014-09-09. Alessandro. @BUG in 'loadImageStack()'. 'first_file' and 'last_file' are set to '-1' by default. But here, they are never checked nor corrected. -* 2014-09-09. Alessandro. @FIXED 'loadImageStack()' method to deal with empty tiles. -* 2014-09-09. Alessandro. @TODO add support for sparse tiles. -* 2014-09-09. Alessandro. @FIXED 'init()' method to deal with empty tiles. -* 2014-09-05. Alessandro. @ADDED 'z_end' parameter in 'loadXML()' method to support sparse data feature. -* 2014-09-05. Alessandro & Iannello. @MODIFIED 'init()' and 'loadImageStack()' methods to deal with IO plugins -* 2014-08-30. Alessandro. @ADDED regular expression based filenames matching in 'init()' method. -* 2014-08-30. Alessandro. @FIXED all error messages starting with 'Stack...' and corrected to 'Block...'. -* 2014-08-30. Alessandro. @FIXED error messages in the 'init()' method (see checks of N_BYTESxCHAN and N_CHANS). -* 2014-08-25. Alessandro. @ADDED missing 'throw (iom::iom::exception)' statement in the 'loadImageStack()' method's signature. -* 2014-08-25. Alessandro. @REMOVED unused 'entry_k' variable declared in 'init()'. -*/ - - -#ifdef _WIN32 - #include "dirent_win.h" -#else - #include -#endif -#include -#include -#include -#include -#include "vmBlock.h" -#include "vmBlockVolume.h" -#include "vmVirtualVolume.h" -#include "StackStitcher.h" -#include "Displacement.h" -#include "IOPluginAPI.h" - - -using namespace std; -using namespace iom; -using namespace vm; - -//CONSTRUCTOR WITH ARGUMENTS -Block::Block(BlockVolume* _CONTAINER, int _ROW_INDEX, int _COL_INDEX, const char* _DIR_NAME) throw (iom::exception) - : VirtualStack() -{ - #if VM_VERBOSE > 3 - printf("\t\t\t\tin Block::Block(BlockVolume* _CONTAINER, int _ROW_INDEX=%d, int _COL_INDEX=%d, char* _DIR_NAME=%s)\n", - _ROW_INDEX, _COL_INDEX, _DIR_NAME); - #endif - - CONTAINER = _CONTAINER; - DIR_NAME = new char[strlen(_DIR_NAME)+1]; - strcpy(DIR_NAME, _DIR_NAME); - ROW_INDEX = _ROW_INDEX; - COL_INDEX = _COL_INDEX; - - - N_BLOCKS = -1; - BLOCK_SIZE = 0; - BLOCK_ABS_D = 0; - - init(); -} - -// 2015-01-17. Alessandro. @ADDED constructor for initialization from XML. -Block::Block(BlockVolume* _CONTAINER, int _ROW_INDEX, int _COL_INDEX, TiXmlElement* stack_node, int z_end) throw (iom::exception) - : VirtualStack() -{ - #if VM_VERBOSE > 3 - printf("\t\t\t\tin Block::Block(BlockVolume* _CONTAINER, int _ROW_INDEX=%d, int _COL_INDEX=%d, TiXmlElement*, int z_end=%d)\n", - _ROW_INDEX, _COL_INDEX, z_end); - #endif - - // check for valid stack node - if(!stack_node) - throw iom::exception("not an xml node", __iom__current__function__); - if( strcmp(stack_node->ToElement()->Value(), "Stack") != 0) - throw iom::exception(iom::strprintf("invalid xml node name: expected \"Stack\", found \"%s\"", stack_node->ToElement()->Value()), __iom__current__function__); - - CONTAINER = _CONTAINER; - DIR_NAME = new char[strlen(stack_node->Attribute("DIR_NAME"))+1]; - strcpy(DIR_NAME, stack_node->Attribute("DIR_NAME")); - ROW_INDEX = _ROW_INDEX; - COL_INDEX = _COL_INDEX; - - N_BLOCKS = -1; - BLOCK_SIZE = 0; - BLOCK_ABS_D = 0; - - // first read image regex field (if any) from xml node - readImgRegex(stack_node); - - // then scan folder for images - init(); - - // finally load other xml attributes - loadXML(stack_node, z_end); -} - -Block::Block(BlockVolume* _CONTAINER, int _ROW_INDEX, int _COL_INDEX, FILE* bin_file) throw (iom::exception) - : VirtualStack() -{ - #if VM_VERBOSE > 3 - printf("\t\t\t\tin Block::Block(BlockVolume* _CONTAINER, int _ROW_INDEX=%d, int _COL_INDEX=%d, FILE* bin_file)\n", - _ROW_INDEX, _COL_INDEX); - #endif - - CONTAINER = _CONTAINER; - ROW_INDEX = _ROW_INDEX; - COL_INDEX = _COL_INDEX; - - N_BLOCKS = -1; - BLOCK_SIZE = 0; - BLOCK_ABS_D = 0; - - unBinarizeFrom(bin_file); -} - -Block::~Block(void) -{ - #if IM_VERBOSE > 3 - printf("\t\t\t\tin Block[%d,%d]::~Block()\n",ROW_INDEX, COL_INDEX); - #endif - - if (BLOCK_SIZE) - delete[] BLOCK_SIZE; - if (BLOCK_ABS_D) - delete[] BLOCK_ABS_D; - - for(int z=0; z 3 - printf("\t\t\t\tin Block[%d,%d]::init()\n",ROW_INDEX, COL_INDEX); - #endif - - //LOCAL variables - string tmp; - DIR *cur_dir_lev3; - dirent *entry_lev3; - list entries_lev3; - string entry; - - //opening stack directory - char abs_path[S_STATIC_STRINGS_SIZE]; - sprintf(abs_path,"%s/%s", CONTAINER->getSTACKS_DIR(), DIR_NAME); - cur_dir_lev3 = opendir(abs_path); - if (!cur_dir_lev3) - { - char errMsg[S_STATIC_STRINGS_SIZE]; - sprintf(errMsg, "in Block::init(): can't open directory \"%s\"", abs_path); - throw iom::exception(errMsg); - } - - //scanning third level of hierarchy which entries need to be ordered alphabetically. This is done using STL. - while ((entry_lev3=readdir(cur_dir_lev3))) - { - tmp = entry_lev3->d_name; - - // 2015-01-17. Alessandro. @ADDED support for all-in-one-folder data (import from xml only). - if(img_regex.empty()) - { - if(tmp.compare(".") != 0 && tmp.compare("..") != 0 && tmp.find(".") != string::npos) - entries_lev3.push_back(tmp); - } - else - { - boost::xpressive::sregex rex = boost::xpressive::sregex::compile(img_regex.c_str()); - boost::xpressive::smatch what; - if(boost::xpressive::regex_match(tmp, what, rex)) - entries_lev3.push_back(tmp); - } - } - entries_lev3.sort(); - N_BLOCKS = (int)entries_lev3.size(); - - //closing dir - closedir(cur_dir_lev3); - - // 2014-09-09. Alessandro. @FIXED to deal with empty tiles. - // if stack is empty... - if(N_BLOCKS == 0) - { - // ...and SPARSE_DATA option is active, then exit - if(vm::SPARSE_DATA) - return; - // ...otherwise throw an exception - else - throw iom::exception(vm::strprintf("in Block[%s]::init(): stack is empty", DIR_NAME).c_str()); - } - - //converting filenames_list (STL list of objects) into FILENAMES (1-D array of C-strings) - FILENAMES = new char*[N_BLOCKS]; - for(int z=0; zreadMetadata( - iom::strprintf("%s/%s/%s", CONTAINER->getSTACKS_DIR(), DIR_NAME, FILENAMES[ib]), - WIDTH, HEIGHT, BLOCK_SIZE[ib], N_BYTESxCHAN, N_CHANS); - } - catch ( iom::exception& exception ) { - if ( strstr(exception.what(),"unable to open image") ) // the image is corrupted: capture the exception - BLOCK_SIZE[ib] = 0; - else // raise the exception again - throw iom::exception(exception.what()); - } - BLOCK_ABS_D[ib] = DEPTH; - DEPTH += BLOCK_SIZE[ib]; - } - - // 2015-07-22. Giulio. TO BE CHECKED: it should be subsitituted by sparse support (see above) - // 2014-09-09. Alessandro. @FIXED to deal with empty tiles. - // add to 'z_ranges' the full range - // @TODO: support sparsity along Z. - z_ranges.clear(); - z_ranges.push_back(vm::interval(0, DEPTH)); -} - - - -//binarizing-unbinarizing methods -void Block::binarizeInto(FILE* file) throw (iom::exception) -{ - #if VM_VERBOSE > 3 - printf("\t\t\t\tin Block[%d,%d]::binarizeInto(...)\n",ROW_INDEX, COL_INDEX); - #endif - - //LOCAL VARIABLES - uint16 str_size; - int i; - - fwrite(&HEIGHT, sizeof(int), 1, file); - fwrite(&WIDTH, sizeof(int), 1, file); - fwrite(&DEPTH, sizeof(int), 1, file); - fwrite(&ABS_V, sizeof(int), 1, file); - fwrite(&ABS_H, sizeof(int), 1, file); - fwrite(&ABS_D, sizeof(int), 1, file); - str_size = (uint16)strlen(DIR_NAME) + 1; - fwrite(&str_size, sizeof(uint16), 1, file); - fwrite(DIR_NAME, str_size, 1, file); - - fwrite(&N_BLOCKS, sizeof(int), 1, file); - for(i = 0; i < N_BLOCKS; i++) - { - // 2015-07-25. Giulio. support for sparse data: missing blocks have store an empty string as filename - str_size = static_cast( FILENAMES[i] ? strlen(FILENAMES[i]) + 1 : 0); - fwrite(&str_size, sizeof(uint16), 1, file); - if(FILENAMES[i]) - fwrite(FILENAMES[i], str_size, 1, file); - fwrite(BLOCK_SIZE+i, sizeof(int), 1, file); - fwrite(BLOCK_ABS_D+i, sizeof(int), 1, file); - } - - fwrite(&N_CHANS, sizeof(int), 1, file); - fwrite(&N_BYTESxCHAN, sizeof(int), 1, file); -} - -void Block::unBinarizeFrom(FILE* file) throw (iom::exception) -{ - #if VM_VERBOSE > 3 - printf("\t\t\t\tin Block[%d,%d]::unBinarizeFrom(...)\n",ROW_INDEX, COL_INDEX); - #endif - - //LOCAL VARIABLES - uint16 str_size; - int i; - size_t fread_return_val; - - fread_return_val = fread(&HEIGHT, sizeof(int), 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in Block::unBinarizeFrom(...): error while reading binary metadata file"); - } - fread_return_val = fread(&WIDTH, sizeof(int), 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in Block::unBinarizeFrom(...): error while reading binary metadata file"); - } - fread_return_val = fread(&DEPTH, sizeof(int), 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in Block::unBinarizeFrom(...): error while reading binary metadata file"); - } - fread_return_val = fread(&ABS_V, sizeof(int), 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in Block::unBinarizeFrom(...): error while reading binary metadata file"); - } - fread_return_val = fread(&ABS_H, sizeof(int), 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in Block::unBinarizeFrom(...): error while reading binary metadata file"); - } - fread_return_val = fread(&ABS_D, sizeof(int), 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in Block::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&str_size, sizeof(uint16), 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in Block::unBinarizeFrom(...): error while reading binary metadata file"); - } - DIR_NAME = new char[str_size]; - fread_return_val = fread(DIR_NAME, str_size, 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in Block::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&N_BLOCKS, sizeof(int), 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in Block::unBinarizeFrom(...): error while reading binary metadata file"); - } - FILENAMES = new char*[N_BLOCKS]; - BLOCK_SIZE = new int[N_BLOCKS]; - BLOCK_ABS_D = new int[N_BLOCKS]; - for(i = 0; i < N_BLOCKS; i++) - { - fread_return_val = fread(&str_size, sizeof(uint16), 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in Block::unBinarizeFrom(...): error while reading binary metadata file"); - } - // 2015-07-25. Giulio. support for sparse data: missing blocks have an empty string as filename in the binarized file - FILENAMES[i] = str_size ? new char[str_size] : 0; - if(str_size) - { - fread_return_val = fread(FILENAMES[i], str_size, 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in Block::unBinarizeFrom(...): error while reading binary metadata file"); - } - } - - fread_return_val = fread(BLOCK_SIZE+i, sizeof(int), 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in Block::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(BLOCK_ABS_D+i, sizeof(int), 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in Block::unBinarizeFrom(...): error while reading binary metadata file"); - } - } - - fread_return_val = fread(&N_CHANS, sizeof(int), 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in Block::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&N_BYTESxCHAN, sizeof(int), 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in Block::unBinarizeFrom(...): error while reading binary metadata file"); - } - - // 2015-07-22. Giulio. @ADDED support for sparse data. - compute_z_ranges(); -} - - -//loads image stack from to extremes included, if not specified loads entire Stack -iom::real_t* Block::loadImageStack(int first_file, int last_file) throw (iom::exception) -{ - #if VM_VERBOSE > 3 - printf("\t\t\t\tin Block[%d,%d]::loadImageStack(first_file = %d, last_file = %d)\n",ROW_INDEX, COL_INDEX, first_file, last_file); - #endif - int first, last; - float scale_factor; - char slice_fullpath[2000]; - - // 2014-09-09. Alessandro. @BUG. 'first_file' and 'last_file' are set to '-1' by default. But here, they are never checked nor corrected. - // I added a very simple (but not complete) check here. - // Be careful if you want to adjust 'last_file' to 'DEPTH' when 'last_file == -1'. 'DEPTH' could be 0 if stack is empty. - if(first_file < 0 || last_file < 0 || first_file > last_file) - throw iom::exception(vm::strprintf("in Block[%s]::loadImageStack(): invalid file selection [%d,%d]", DIR_NAME, first_file, last_file).c_str()); - - - // 2014-09-09. Alessandro. @FIXED 'loadImageStack()' method to deal with empty tiles. - // if stack is empty in the given range, just return a black image - if(isEmpty(first_file, last_file)) - { - // allocate and initialize a black stack - uint64 image_size = static_cast(WIDTH) * static_cast(HEIGHT) * static_cast(last_file-first_file+1); - STACKED_IMAGE = new iom::real_t[image_size]; - for(uint64 k=0; kind0; i <= intersect_segm->ind1; i++) - { - //if ( temp - data > (HEIGHT * WIDTH * (last_file-first_file+1) * N_BYTESxCHAN * N_CHANS) ) - // throw iom::exception(vm::strprintf("in Block[%s]::loadImageStack(): buffer overrun at block %d", DIR_NAME, i-1).c_str()); - - first = (first_file > BLOCK_ABS_D[i]) ? first_file-BLOCK_ABS_D[i] : 0 ; - last = (last_file < BLOCK_ABS_D[i]+BLOCK_SIZE[i]-1) ? last_file-BLOCK_ABS_D[i] : BLOCK_SIZE[i]-1 ; - if ( FILENAMES[i] ) { // 2015-07-26. Giulio. @ADDED sparsedata support - sprintf(slice_fullpath, "%s/%s/%s", CONTAINER->getSTACKS_DIR(), DIR_NAME, FILENAMES[i]); - - // 2014-09-05. Alessandro & Iannello. @MODIFIED to deal with IO plugins - //iom::IOPluginFactory::getPlugin3D(iom::IMIN_PLUGIN)->readData(slice_fullpath, WIDTH, HEIGHT, temp, first, last); - iom::IOPluginFactory::getPlugin3D(iom::IMIN_PLUGIN)->readData(slice_fullpath,WIDTH,HEIGHT,BLOCK_SIZE[i],N_BYTESxCHAN,N_CHANS,temp,first,last+1); - } - temp += HEIGHT * WIDTH * (last-first+1) * N_BYTESxCHAN * N_CHANS; - } - - //conversion from unsigned char to iom::real_t - if (N_CHANS == 2 || N_CHANS > 3) // only monocromatic or RGB images are supported - { - char errMsg[2000]; - sprintf(errMsg, "in Block[%d,%d]::loadImageStack(...): %d channels are not supported.", ROW_INDEX, COL_INDEX, N_CHANS); - throw iom::exception(errMsg); - } - - if ( N_BYTESxCHAN == 1 ) - scale_factor = 255.0F; - else if ( N_BYTESxCHAN == 2 ) - scale_factor = 65535.0F; - else - { - char errMsg[2000]; - sprintf(errMsg, "in Block[%d,%d]::loadImageStack(...): Too many bytes per channel (%d).", ROW_INDEX, COL_INDEX, N_BYTESxCHAN); - throw iom::exception(errMsg); - } - - STACKED_IMAGE = new iom::real_t[HEIGHT * WIDTH * (last_file-first_file+1)]; // this image is an intensity image (only one channel) - - int offset; - - if ( N_CHANS == 1 ) { - // 2014-11-04. Giulio. @FIXED - if ( N_BYTESxCHAN == 1 ) - for(int i = 0; i isChansInterleaved() ) { - if ( iom::CHANS == iom::ALL ) { - char errMsg[2000]; - sprintf(errMsg, "in Block[%d,%d]::loadImageStack(...): conversion from multi-channel to intensity images not supported.", ROW_INDEX, COL_INDEX); - throw iom::exception(errMsg); - } - else if ( iom::CHANS == iom::R ) { - offset = 0; - } - else if ( iom::CHANS == iom::G ) { - offset = 1; - } - else if ( iom::CHANS == iom::B ) { - offset = 2; - } - else { - char errMsg[2000]; - sprintf(errMsg, "in Block[%d,%d]::loadImageStack(...): wrong value for parameter iom::CHANNEL_SELECTION.", ROW_INDEX, COL_INDEX); - throw iom::exception(errMsg); - } - // 2014-11-04. Giulio. @FIXED - if ( N_BYTESxCHAN == 1 ) - for(int i = 0; i 3 - printf("......in Block[%d,%d]::getXML()\n",ROW_INDEX, COL_INDEX); - #endif - - string blockSizes, blocksAbsD; - TiXmlElement *xml_representation = new TiXmlElement("Stack"); - - xml_representation->SetAttribute("N_BLOCKS",N_BLOCKS); - - // 2014-09-09. Alessandro. @FIXED 'getXML()' method to deal with empty stacks. - char str_buf[1000]; - if(N_BLOCKS) - { - #if __cplusplus == 201103L // C++11 compliant compiler - blockSizes.append(to_string(BLOCK_SIZE[0])); - blocksAbsD.append(to_string(BLOCK_ABS_D[0])); - #else - sprintf(str_buf,"%i",BLOCK_SIZE[0]); - blockSizes.append(str_buf); - sprintf(str_buf,"%i",BLOCK_ABS_D[0]); - blocksAbsD.append(str_buf); - #endif - } - - for(int j =1;jSetAttribute("BLOCK_SIZES",BLOCK_SIZES); - xml_representation->SetAttribute("BLOCKS_ABS_D",BLOCKS_ABS_D); - - xml_representation->SetAttribute("N_CHANS",N_CHANS); - xml_representation->SetAttribute("N_BYTESxCHAN",N_BYTESxCHAN); - xml_representation->SetAttribute("ROW",ROW_INDEX); - xml_representation->SetAttribute("COL",COL_INDEX); - xml_representation->SetAttribute("ABS_V",ABS_V); - xml_representation->SetAttribute("ABS_H",ABS_H); - xml_representation->SetAttribute("ABS_D",ABS_D); - xml_representation->SetAttribute("STITCHABLE",stitchable ? "yes" : "no"); - xml_representation->SetAttribute("DIR_NAME",DIR_NAME); - - // 2015-07-22. Giulio. @ADDED 'Z_RANGES' attribute in the xml node - std::string z_ranges_string; - for(int k=0; kSetAttribute("Z_RANGES",z_ranges_string.c_str()); - writeImgRegex(xml_representation); - - vector::iterator i; - TiXmlElement *NORTH_displacements = new TiXmlElement("NORTH_displacements"); - for(i = NORTH.begin(); i != NORTH.end(); i++) - NORTH_displacements->LinkEndChild((*i)->getXML()); - TiXmlElement *EAST_displacements = new TiXmlElement("EAST_displacements"); - for(i = EAST.begin(); i != EAST.end(); i++) - EAST_displacements->LinkEndChild((*i)->getXML()); - TiXmlElement *SOUTH_displacements = new TiXmlElement("SOUTH_displacements"); - for(i = SOUTH.begin(); i != SOUTH.end(); i++) - SOUTH_displacements->LinkEndChild((*i)->getXML()); - TiXmlElement *WEST_displacements = new TiXmlElement("WEST_displacements"); - for(i = WEST.begin(); i != WEST.end(); i++) - WEST_displacements->LinkEndChild((*i)->getXML()); - xml_representation->LinkEndChild(NORTH_displacements); - xml_representation->LinkEndChild(EAST_displacements); - xml_representation->LinkEndChild(SOUTH_displacements); - xml_representation->LinkEndChild(WEST_displacements); - - return xml_representation; -} - -void Block::loadXML( - TiXmlElement *stack_node, - int z_end) // 2014-09-05. Alessandro. @ADDED 'z_end' parameter to support sparse data feature - // Here 'z_end' identifies the range [0, z_end) that slices can span -throw (iom::exception) -{ - #if VM_VERBOSE > 3 - printf("\t\t\t\tin Block[%d,%d]::loadXML(TiXmlElement *stack_node)\n",ROW_INDEX, COL_INDEX); - #endif - - stack_node->QueryIntAttribute("N_BLOCKS",&N_BLOCKS); - - const char *BLOCK_SIZES=stack_node->Attribute("BLOCK_SIZES"); - char *BLOCK_SIZES2 = new char [strlen (BLOCK_SIZES) + 1]; - strcpy (BLOCK_SIZES2,BLOCK_SIZES); - char * pch=strtok (BLOCK_SIZES2,","); - int j=0; - while (pch != NULL) - { - BLOCK_SIZE[j]=atoi(pch); - j++; //141027_Onofri: added missing increment - pch = strtok (NULL, ","); - } - delete[] BLOCK_SIZES2; - - const char *BLOCKS_ABS_D=stack_node->Attribute("BLOCKS_ABS_D"); - char *BLOCKS_ABS_D2 = new char [strlen (BLOCKS_ABS_D) + 1]; - strcpy (BLOCKS_ABS_D2,BLOCKS_ABS_D); - pch=strtok (BLOCKS_ABS_D2,","); - j=0; - while (pch != NULL) - { - BLOCK_ABS_D[j]=atoi(pch); - j++; - pch = strtok (NULL, ","); - } - delete[] BLOCKS_ABS_D2; - stack_node->QueryIntAttribute("N_CHANS",&N_CHANS); - stack_node->QueryIntAttribute("N_BYTESxCHAN",&N_BYTESxCHAN); - stack_node->QueryIntAttribute("ABS_V", &ABS_V); - stack_node->QueryIntAttribute("ABS_H", &ABS_H); - stack_node->QueryIntAttribute("ABS_D", &ABS_D); - stitchable = strcmp(stack_node->Attribute("STITCHABLE"),"yes")==0 ? true : false; - if(strcmp(stack_node->Attribute("DIR_NAME"), DIR_NAME) != 0) - { - char errMsg[2000]; - sprintf(errMsg, "in Block[%d,%d]::loadXML(...): Mismatch between xml file and %s in field.", ROW_INDEX, COL_INDEX, vm::BINARY_METADATA_FILENAME.c_str()); - throw iom::exception(errMsg); - } - - // 2015-01-17. Alessandro. @ADDED support for all-in-one-folder data (import from xml only). - readImgRegex(stack_node); - - // 2015-07-22. Alessandro. @ADDED 'Z_RANGES' attribute in the xml node - const char* z_ranges_c = stack_node->Attribute("Z_RANGES"); - if( z_ranges_c ) // field is present: we can run 'sparse data' code - { - // nonempty tile - if ( strlen(z_ranges_c) != 0 ) - { - // parse 'Z_RANGES' field - z_ranges.clear(); - std::string z_ranges_c_str = z_ranges_c; - std::string z_ranges_string = vm::cls(z_ranges_c_str); - std::vector tokens; - vm::split(z_ranges_string, ";", tokens); - for(int i=0; i extremes; - vm::split(tokens[i].substr(1, tokens[i].size()-2), ",", extremes); - - // check correct parsing - if(extremes.size() != 2) - throw iom::exception(vm::strprintf("in Block(%s)::loadXML(): cannot parse 'Z_RANGES' subentry \"%s\"", DIR_NAME, tokens[i].c_str()).c_str()); - - // get integral range - int start = vm::str2num(extremes[0]); - int end = vm::str2num(extremes[1]); - - // check valid range - if(start < 0 || start >= end || end > z_end) - throw iom::exception(vm::strprintf("in Block(%s)::loadXML(): 'Z_RANGES' subentry \"%s\" is out of range [%d,%d) ", DIR_NAME, tokens[i].c_str(), 0, z_end).c_str()); - - // push range - z_ranges.push_back(vm::interval(start, end)); - } - - // check precondition: z_ranges should contain consecutive but not contiguous intervals [a_1,b_1), [a_2,b_2), ... such that a_n > b_(n-1) - for(int i=1; i b_(n-1). " - "Found a_%d(%d) <= b_%d(%d)", DIR_NAME, i, z_ranges[i].start, i-1, z_ranges[i-1].end).c_str()); - - // if 'FILENAMES' is not a sparse list... - if(DEPTH != z_end) - { - // make 'FILENAMES' a sparse list - char **FILENAMES_sparse = new char*[z_end]; - for(int z=0; z= DEPTH) - throw iom::exception(vm::strprintf("in Block(%s)::loadXML(): no more slices available to cover z-range [%d,%d)", - DIR_NAME, z_ranges[k].start, z_ranges[k].end).c_str()); - - FILENAMES_sparse[z] = FILENAMES[i++]; - } - - // substitute list of filenames with its sparse version - if(FILENAMES) - delete[] FILENAMES; - FILENAMES = FILENAMES_sparse; - DEPTH = z_end; - } - // ...otherwise check if the sparse list matches with z_ranges - else - { - for(int i=0; i(0, DEPTH)); - } - - - TiXmlElement *NORTH_displacements = stack_node->FirstChildElement("NORTH_displacements"); - for(TiXmlElement *displ_node = NORTH_displacements->FirstChildElement("Displacement"); displ_node; displ_node = displ_node->NextSiblingElement()) - NORTH.push_back(Displacement::getDisplacementFromXML(displ_node)); - TiXmlElement *EAST_displacements = stack_node->FirstChildElement("EAST_displacements"); - for(TiXmlElement *displ_node = EAST_displacements->FirstChildElement("Displacement"); displ_node; displ_node = displ_node->NextSiblingElement()) - EAST.push_back(Displacement::getDisplacementFromXML(displ_node)); - TiXmlElement *SOUTH_displacements = stack_node->FirstChildElement("SOUTH_displacements"); - for(TiXmlElement *displ_node = SOUTH_displacements->FirstChildElement("Displacement"); displ_node; displ_node = displ_node->NextSiblingElement()) - SOUTH.push_back(Displacement::getDisplacementFromXML(displ_node)); - TiXmlElement *WEST_displacements = stack_node->FirstChildElement("WEST_displacements"); - for(TiXmlElement *displ_node = WEST_displacements->FirstChildElement("Displacement"); displ_node; displ_node = displ_node->NextSiblingElement()) - WEST.push_back(Displacement::getDisplacementFromXML(displ_node)); - - // 2015-07-22. Giulio. TO BE CHECKED: it should be subsitituted by sparse support (see above) - // 2014-09-09. Alessandro. @FIXED to deal with empty tiles. - // if tile is not empty, add to 'z_ranges' the full range - // @TODO: support sparsity along Z. - //if(N_BLOCKS > 0) - //{ - // z_ranges.clear(); - // z_ranges.push_back(vm::interval(0, z_end)); - //} -} - -Segm_t* Block::Intersects(int D0, int D1) { - - if ( D0 >= BLOCK_ABS_D[N_BLOCKS-1]+BLOCK_SIZE[N_BLOCKS-1] || D1 <= 0 ) - // there is no intersection - return NULL; - - bool found0, found1; - int i0, i1; - - found0 = false; - i0 = 0; - while ( i0<(int)(N_BLOCKS-1) && !found0 ) - if ( D0 < BLOCK_ABS_D[i0+1] ) - found0 = true; - else - i0++; - // !found0 -> i0 = N_BLOCKS-1 - - found1 = false; - i1 = (int)(N_BLOCKS-1); - while ( i1>0 && !found1 ) - if ( D1 > BLOCK_ABS_D[i1] ) // GI_141110 re-changed '>=' to '>' (D1 is the last index + 1) - found1 = true; - else - i1--; - // !found1 -> i1 = 0 - - Segm_t *intersect_segm = new Segm_t; - intersect_segm->D0 = max(D0,0); - intersect_segm->D1 = min(D1,(int)DEPTH); - intersect_segm->ind0 = i0; - intersect_segm->ind1 = i1; - - return intersect_segm; -} - -// compute 'z_ranges' -void - Block::compute_z_ranges( - std::pair const * z_coords /*= 0*/) // pair of z-coordinates corresponding to the whole volume depth - throw (iom::exception) // if null, 'z_ranges' will be compute based on 'FILENAMES' vector -{ - // if 'z_coords' has been provided, we use it to associate each file in 'FILENAMES' to the correspondent z-coordinate - if(z_coords) - { - // compute the number of slices corresponding to the volume - int n_slices = (int) floor((float)(z_coords->second - z_coords->first) / (10 * CONTAINER->getVXL_D()) + 0.5); - // check non-zero N_SLICES - if (CONTAINER->getN_SLICES() != n_slices) { - char msg[S_STATIC_STRINGS_SIZE]; - sprintf(msg,"in Block::compute_z_ranges(...): in stack [%d,%d] error in the number of slices (CONTAINER->getN_SLICES()=%d, z_coords=[%d,%d], CONTAINER->getVXL_D()=%f, n_slices=%d)", - ROW_INDEX, COL_INDEX, CONTAINER->getN_SLICES(), z_coords->first, z_coords->second, CONTAINER->getVXL_D(), n_slices); - throw iom::exception(msg); - } - - char **FILENAMES_temp = new char*[2*N_BLOCKS+1]; - int *BLOCK_SIZE_temp = new int[2*N_BLOCKS+1]; - int *BLOCK_ABS_D_temp = new int[2*N_BLOCKS+1]; - - int n_blocks = 0; - int n = 0; // index of the first slice of the block to be processed - int z_next; // D coordinate of block to be processed - int z = z_coords->first; // current D coordinate - for ( int i=0; i z ) { - FILENAMES_temp[n_blocks] = 0; - BLOCK_SIZE_temp[n_blocks] = (int) floor((float)(z_next - z)/(10 * CONTAINER->getVXL_D())); // 2015-08-01. Giulio. floor is used to avoid the introduction of one more empty slice; if some slice is missing it will be added at the bottom of the stack - BLOCK_ABS_D_temp[n_blocks] = n; - n += BLOCK_SIZE_temp[n_blocks]; - n_blocks++; - } - FILENAMES_temp[n_blocks] = FILENAMES[i]; - BLOCK_SIZE_temp[n_blocks] = BLOCK_SIZE[i]; - BLOCK_ABS_D_temp[n_blocks] = n; - n += BLOCK_SIZE_temp[n_blocks]; - n_blocks++; - z = (int) floor(z_next + BLOCK_SIZE[i] * 10 * CONTAINER->getVXL_D() + 0.5); - } - if ( n < n_slices ) { - FILENAMES_temp[n_blocks] = 0; - BLOCK_SIZE_temp[n_blocks] = n_slices - n; - BLOCK_ABS_D_temp[n_blocks] = n; - n_blocks++; - } - else if ( n > n_slices ) { - char msg[S_STATIC_STRINGS_SIZE]; - sprintf(msg,"in Block::compute_z_ranges(...): in stack [%d,%d] too many slices (%d instead of %d)", ROW_INDEX, COL_INDEX, n, n_slices); - throw iom::exception(msg); - } - - if ( N_BLOCKS ) { - delete[] FILENAMES; - delete[] BLOCK_SIZE; - delete[] BLOCK_ABS_D; - } - - FILENAMES = new char *[n_blocks]; - memcpy(FILENAMES,FILENAMES_temp,n_blocks*sizeof(char *)); - delete[] FILENAMES_temp; - - BLOCK_SIZE = new int[n_blocks]; - memcpy(BLOCK_SIZE,BLOCK_SIZE_temp,n_blocks*sizeof(int)); - delete[] BLOCK_SIZE_temp; - - BLOCK_ABS_D = new int[n_blocks]; - memcpy(BLOCK_ABS_D,BLOCK_ABS_D_temp,n_blocks*sizeof(int)); - delete[] BLOCK_ABS_D_temp; - - N_BLOCKS = n_blocks; - DEPTH = n_slices; - } - - // compute 'z_range' from 'FILENAMES' - bool interval_start = true; - bool interval_stop = false; - int last_slice; - z_ranges.clear(); - for(int k=0; k(BLOCK_ABS_D[k], -1)); - last_slice = BLOCK_ABS_D[k] + BLOCK_SIZE[k]; - } - if(FILENAMES[k] == 0 && interval_stop) - { - interval_start = true; - interval_stop = false; - z_ranges.back().end = last_slice; - } - } - if(!z_ranges.empty() && z_ranges.back().end == -1) - z_ranges.back().end = DEPTH; -} \ No newline at end of file diff --git a/v3d_main/terafly/src/core/volumemanager/vmBlock.h b/v3d_main/terafly/src/core/volumemanager/vmBlock.h deleted file mode 100644 index 216185b819..0000000000 --- a/v3d_main/terafly/src/core/volumemanager/vmBlock.h +++ /dev/null @@ -1,116 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -* 2015-07-22. Giluio. @ADDED supporto for spase data. -* 2015-01-17. Alessandro. @ADDED constructor for initialization from XML. -* 2015-01-17. Alessandro. @FIXED missing throw(iom::exception) declaration in many methods. -* 2014-09-05. Alessandro. @ADDED 'z_end' parameter in 'loadXML()' method to support sparse data feature. -* 2014-08-25. Alessandro. @ADDED missing 'throw (iom::iom::exception)' statement in the 'loadImageStack()' method's signature -*/ - -#ifndef _VM_BLOCK_H -#define _VM_BLOCK_H - -#include - -#include "volumemanager.config.h" -#include "iomanager.config.h" -#include "tinyxml.h" -#include "vmVirtualStack.h" - - - -class Displacement; - -//TYPE DEFINITIONS -//structure representing a substack -//D0: first slice, D1: last slice, ind0: index of 1st block (containing D0), ind1: index of last block (containing D1) -typedef struct {int D0, D1, ind0, ind1;} Segm_t; - -class vm::Block : public vm::VirtualStack -{ - private: - - vm::BlockVolume* CONTAINER; //pointer to object that contains the current object - int N_BLOCKS; //number of blocks along z - int *BLOCK_SIZE; //dimensions of blocks along z - int *BLOCK_ABS_D; //absolute D voxel coordinates of blocks - - //******** OBJECT PRIVATE METHODS ********* - Block(void){} - - //Initializes all object's members given DIR_NAME - void init() throw (iom::exception); - - //binarizing-unbinarizing methods - void binarizeInto(FILE* file) throw (iom::exception); - void unBinarizeFrom(FILE* file) throw (iom::exception); - - // compute 'z_ranges' - void - compute_z_ranges( - std::pair const * z_coords = 0) // set of z-coordinates where at least one slice (of a certain stack) is available - throw (iom::exception); // if null, 'z_ranges' will be compute based on 'FILENAMES' vector - - //returns a pointer to the intersection segment (along D) if the given segment (D0,D1-1) intersects current stack, otherwise returns NULL - //D0 first index of the segment - //D1 last index of the segment + 1 - Segm_t* Intersects(int D0, int D1); - - //******** FRIEND CLASS DECLARATION ********* - //BlockVolume can access Block private members and methods - friend class vm::BlockVolume; - - public: - //CONSTRUCTORS - Block(vm::BlockVolume* _CONTAINER, int _ROW_INDEX, int _COL_INDEX, const char* _DIR_NAME) throw (iom::exception); // build from scratch - Block(vm::BlockVolume* _CONTAINER, int _ROW_INDEX, int _COL_INDEX, FILE* bin_file) throw (iom::exception); // build from mdata.bin - Block(vm::BlockVolume* _CONTAINER, int _ROW_INDEX, int _COL_INDEX, TiXmlElement* stack_node, int z_end) throw (iom::exception); // build from XML - ~Block(void); - - //GET methods - int getN_BLOCKS() {return N_BLOCKS;} - - int *getBLOCK_SIZE() {return BLOCK_SIZE;} - int *getBLOCK_ABS_D() {return BLOCK_ABS_D;} - - void *getCONTAINER() {return CONTAINER;} - - //LOAD and RELEASE methods - iom::real_t* loadImageStack(int first_file=-1, int last_file=-1) throw (iom::exception); - void releaseImageStack(); - - //XML methods - TiXmlElement* getXML(); - void loadXML( - TiXmlElement *stack_node, - int z_end) // 2014-09-05. Alessandro. @ADDED 'z_end' parameter to support sparse data feature - // Here 'z_end' identifies the range [0, z_end) that slices can span - throw (iom::exception); -}; - -#endif //_BLOCK_H diff --git a/v3d_main/terafly/src/core/volumemanager/vmBlockVolume.cpp b/v3d_main/terafly/src/core/volumemanager/vmBlockVolume.cpp deleted file mode 100644 index fff64ebd7c..0000000000 --- a/v3d_main/terafly/src/core/volumemanager/vmBlockVolume.cpp +++ /dev/null @@ -1,1235 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -* 2015-08-27. Giluio. @ADDED control on coherence between block lenghts and filenames in 'check' method -* 2015-07-30. Giluio. @FIXED bug in applyReference system. -* 2015-07-30. Giluio. @FIXED bug in extractCoordinates. -* 2015-07-22. Giluio. @ADDED support for spase data (see comments below). -* 2015-06-12. Giulio @ADDED 'check' method to check completeness and coherence of a volume -* 2015-02-26. Giulio. @ADDED implementation of initChannels private method to initialize fields DIM_C and BYTESxCHAN -* 2015-01-17. Alessandro. @FIXED missing throw(iom::exception) declaration in loadXML and initFromXML methods. -* 2015-01-17. Alessandro. @ADDED support for all-in-one-folder data (import from xml only). -* 2014-11-06. Giulio. @ADDED saved reference system into XML file -* 2014-09-20. Alessandro. @ADDED overwrite_mdata flag to the XML-based constructor. -* 2014-09-10. Alessandro. @ADDED 'volume_format' attribute to XML node -* 2014-09-10. Alessandro. @ADDED plugin creation/registration functions to make 'StackedVolume' a volume format plugin. -* 2014-09-09. Alessandro. @FIXED. Added default reference system if volume is imported from xml. -* 2014-09-09. Alessandro. @FIXED both 'init()' and 'initFromXML()' methods to deal with empty stacks. Added call of 'normalize_stacks_attributes()' method. -* 2014-09-05. Alessandro. @ADDED 'normalize_stacks_attributes()' method to normalize stacks attributes (width, height, etc.) -* 2014-09-02. Alessandro. @FIXED both 'loadBinaryMetadata()' and 'saveBinaryMetadata()' as 'N_SLICES' changed from 'uint16' to 'int' type. See vmVirtualVolume.h. -*/ - -/**************************** -* Management of sparse data * -***************************** -* -* If --sparse_data flag is set, in the import step, after reading files names missing blocks are detected -* -* Each tile is a list of blocks some of which may be empty -* empty blocks have a null pointer as file name, but have first index and size correctly set -* this structure is binarized into the mdata.bin file -* the z_ranges variable store for each tile the intervals corresponding to exisiting blocks -* thi information is stored into the xml file -* both internal tile structure and z_ranges field are set every time the volume is created -*/ - -#ifdef _WIN32 -#include "dirent_win.h" -#else -#include -#endif -#include -#include -#include -#include -#include "vmBlockVolume.h" -#include "S_config.h" -//#include - -using namespace std; -using namespace iom; -using namespace vm; - -// 2014-09-10. Alessandro. @ADDED plugin creation/registration functions to make 'StackedVolume' a volume format plugin. -const std::string BlockVolume::id = "TiledXY|3Dseries"; -const std::string BlockVolume::creator_id1 = volumemanager::VirtualVolumeFactory::registerPluginCreatorXML(&createFromXML, BlockVolume::id); -const std::string BlockVolume::creator_id2 = volumemanager::VirtualVolumeFactory::registerPluginCreatorData(&createFromData, BlockVolume::id); - - -BlockVolume::BlockVolume(const char* _stacks_dir, vm::ref_sys _reference_system, float VXL_1, float VXL_2, float VXL_3, bool overwrite_mdata) throw (iom::exception) - : VirtualVolume(_stacks_dir, _reference_system, VXL_1, VXL_2, VXL_3) -{ - #if VM_VERBOSE > 3 - printf("\t\t\t\tin BlockVolume::BlockVolume(_stacks_dir=%s, reference_system = {%d,%d,%d}, VXL_1 = %.2f, VXL_2 = %.2f, VXL_3 = %.2f)\n", - _stacks_dir,reference_system.first, reference_system.second, reference_system.third, VXL_1, VXL_2, VXL_3); - #endif - - //trying to unserialize an already existing metadata file, if it doesn't exist the full initialization procedure is performed and metadata is saved - char mdata_filepath[VM_STATIC_STRINGS_SIZE]; - sprintf(mdata_filepath, "%s/%s", stacks_dir, vm::BINARY_METADATA_FILENAME.c_str()); - if(fileExists(mdata_filepath) && !overwrite_mdata) - loadBinaryMetadata(mdata_filepath); - else - { - if(_reference_system.first == vm::axis_invalid || _reference_system.second == vm::axis_invalid || - _reference_system.third == vm::axis_invalid || VXL_1 == 0 || VXL_2 == 0 || VXL_3 == 0) - throw iom::exception("in BlockVolume::BlockVolume(...): invalid importing parameters"); - reference_system = _reference_system; // GI_140501: stores the refrence system to generate the mdata.bin file for the output volumes - init(); - applyReferenceSystem(reference_system, VXL_1, VXL_2, VXL_3); - saveBinaryMetadata(mdata_filepath); - } - - initChannels(); - - // check all stacks have the same number of slices (@ADDED by Giulio on 2015-07-22) - if(!vm::SPARSE_DATA) - { - for(int i=0; igetDEPTH() != N_SLICES) - { - throw iom::exception(iom::strprintf("in BlockVolume::StackedVolume(): unequal number of slices detected. Stack \"%s\" has %d, stack \"%s\" has %d. " - "Please activate the sparse data option if stacks are not complete", - BLOCKS[0][0]->getDIR_NAME(), BLOCKS[0][0]->getDEPTH(), BLOCKS[i][j]->getDIR_NAME(), BLOCKS[i][j]->getDEPTH()).c_str()); - } - } - } -} - -BlockVolume::BlockVolume(const char *xml_filepath, bool overwrite_mdata) throw (iom::exception) - : VirtualVolume(xml_filepath) -{ - #if VM_VERBOSE > 3 - printf("\t\t\t\tin BlockVolume::BlockVolume(xml_filepath=%s)\n", xml_filepath); - #endif - - //extracting field from XML - TiXmlDocument xml; - if(!xml.LoadFile(xml_filepath)) - { - char errMsg[2000]; - sprintf(errMsg,"in BlockVolume::BlockVolume(xml_filepath = \"%s\") : unable to load xml", xml_filepath); - throw iom::exception(errMsg); - } - TiXmlHandle hRoot(xml.FirstChildElement("TeraStitcher")); - TiXmlElement * pelem = hRoot.FirstChildElement("stacks_dir").Element(); - this->stacks_dir = new char[strlen(pelem->Attribute("value"))+1]; - strcpy(this->stacks_dir, pelem->Attribute("value")); - - //trying to unserialize an already existing metadata file, if it doesn't exist the full initialization procedure is performed and metadata is saved - char mdata_filepath[2000]; - sprintf(mdata_filepath, "%s/%s", stacks_dir, vm::BINARY_METADATA_FILENAME.c_str()); - - // 2014-09-20. Alessandro. @ADDED overwrite_mdata flag - if(fileExists(mdata_filepath) && !overwrite_mdata) - { - // load mdata.bin content and xml content, also perform consistency check between mdata.bin and xml content - loadBinaryMetadata(mdata_filepath); - loadXML(xml_filepath); - } - else - { - // load xml content and generate mdata.bin - initFromXML(xml_filepath); - saveBinaryMetadata(mdata_filepath); - } - - initChannels(); - - // check all stacks have the same number of slices (@ADDED by Giulio on 2015-07-22) - if(!vm::SPARSE_DATA) - { - for(int i=0; igetDEPTH() != N_SLICES) - { - throw iom::exception(iom::strprintf("in BlockVolume::StackedVolume(): unequal number of slices detected. Stack \"%s\" has %d, stack \"%s\" has %d. " - "Please activate the sparse data option if stacks are not complete", - BLOCKS[0][0]->getDIR_NAME(), BLOCKS[0][0]->getDEPTH(), BLOCKS[i][j]->getDIR_NAME(), BLOCKS[i][j]->getDEPTH()).c_str()); - } - } - } -} - -BlockVolume::~BlockVolume() -{ - #if VM_VERBOSE > 3 - printf("\t\t\t\tin BlockVolume::~BlockVolume(void)\n"); - #endif - - if(stacks_dir) - delete[] stacks_dir; - - if(BLOCKS) - { - for(int row=0; row 3 - printf("\t\t\t\tin BlockVolume::init()\n"); - #endif - - //LOCAL VARIABLES - string tmp_path; //string that contains temp paths during computation - string tmp; //string that contains temp data during computation - string tmp2; //string that contains temp data during computation - DIR *cur_dir_lev1; //pointer to DIR, the data structure that represents a DIRECTORY (level 1 of hierarchical structure) - DIR *cur_dir_lev2; //pointer to DIR, the data structure that represents a DIRECTORY (level 2 of hierarchical structure) - dirent *entry_lev1; //pointer to DIRENT, the data structure that represents a DIRECTORY ENTRY inside a directory (level 1) - dirent *entry_lev2; //pointer to DIRENT, the data structure that represents a DIRECTORY ENTRY inside a directory (level 2) - int i=0,j=0; //for counting of N_ROWS, N_COLS - list stacks_list; //each stack found in the hierarchy is pushed into this list - list entries_lev1; //list of entries of first level of hierarchy - list::iterator entry_i; //iterator for list 'entries_lev1' - list entries_lev2; //list of entries of second level of hierarchy - list::iterator entry_j; //iterator for list 'entries_lev2' - char stack_i_j_path[S_STATIC_STRINGS_SIZE]; - - //obtaining DIR pointer to stacks_dir (=NULL if directory doesn't exist) - if (!(cur_dir_lev1=opendir(stacks_dir))) - { - char msg[S_STATIC_STRINGS_SIZE]; - sprintf(msg,"in BlockVolume::init(...): Unable to open directory \"%s\"", stacks_dir); - throw iom::exception(msg); - } - - //scanning first level of hierarchy which entries need to be ordered alphabetically. This is done using STL. - while ((entry_lev1=readdir(cur_dir_lev1))) - { - tmp=entry_lev1->d_name; - if(tmp.find(".") == string::npos && tmp.find(" ") == string::npos) - entries_lev1.push_front(entry_lev1->d_name); - } - closedir(cur_dir_lev1); - entries_lev1.sort(); - N_ROWS = (uint16) entries_lev1.size(); - N_COLS = 0; - if(N_ROWS == 0) - throw iom::exception("in BlockVolume::init(...): Unable to find stacks in the given directory"); - - - //for each entry of first level, scanning second level - for(entry_i = entries_lev1.begin(), i=0; entry_i!= entries_lev1.end(); entry_i++, i++) - { - //building absolute path of first level entry to be used for "opendir(...)" - tmp_path=stacks_dir; - tmp_path.append("/"); - tmp_path.append(*entry_i); - cur_dir_lev2 = opendir(tmp_path.c_str()); - if (!cur_dir_lev2) - throw iom::exception("in BlockVolume::init(...): A problem occurred during scanning of subdirectories"); - - //scanning second level of hierarchy which entries need to be ordered alphabetically. This is done using STL. - while ((entry_lev2=readdir(cur_dir_lev2))) - { - tmp=entry_lev2->d_name; - if(tmp.find(".") == string::npos && tmp.find(" ") == string::npos) - entries_lev2.push_back(entry_lev2->d_name); - } - closedir(cur_dir_lev2); - entries_lev2.sort(); - - //for each entry of the second level, allocating a new Stack - for(entry_j = entries_lev2.begin(), j=0; entry_j!= entries_lev2.end(); entry_j++, j++) - { - //allocating new stack - sprintf(stack_i_j_path,"%s/%s",(*entry_i).c_str(), (*entry_j).c_str()); - Block *new_stk = new Block(this,i,j,stack_i_j_path); - stacks_list.push_back(new_stk); - } - entries_lev2.clear(); - if(N_COLS == 0) - N_COLS = j; - else if(j != N_COLS) - throw iom::exception("in BlockVolume::init(...): Number of second-level directories is not the same for all first-level directories!"); - } - entries_lev1.clear(); - - //intermediate check - if(N_ROWS == 0 || N_COLS == 0) - throw iom::exception("in BlockVolume::init(...): Unable to find stacks in the given directory"); - - // 2015-07-22. Giulio. @ADDED sparse data support - // precondition: files must be named according to one of the two formats supported (see 'name2coordZ()') - if(SPARSE_DATA) - { - // compute N_SLICES as the cardinality of the set of all Z-coordinates extracted from the filenames of the entire volume - int start_z = 999999; //atoi(name2coordZ(stacks_list.front()->FILENAMES[0]).c_str()); - int end_z = 0; - int start_cur, end_cur; - N_SLICES = 0; - for(list::iterator i = stacks_list.begin(); i != stacks_list.end(); i++) { - if ( (*i)->N_BLOCKS ) { - start_cur = atoi(name2coordZ((*i)->FILENAMES[0]).c_str()); - if ( start_cur < start_z ) - start_z = start_cur; - end_cur = atoi(name2coordZ((*i)->FILENAMES[(*i)->N_BLOCKS-1]).c_str()) + (int)floor((*i)->BLOCK_SIZE[(*i)->N_BLOCKS-1] * 10 * VXL_D + 0.5); - if ( end_cur > end_z ) - end_z = end_cur; - if ( N_SLICES < (*i)->DEPTH ) - N_SLICES = (*i)->DEPTH; - } - } - // check if no stacks are complete - // WARNING: VXL_D is assumed positive, it should be used the absolute value - if ( N_SLICES < ((int)floor((float)(end_z - start_z) / (10 * VXL_D) + 0.5)) ) - N_SLICES = (int)floor((float)(end_z - start_z) / (10 * VXL_D) + 0.5); - - // check non-zero N_SLICES - if (N_SLICES == 0) - throw iom::exception("in BlockVolume::init(...): Unable to find image files in the given directory"); - - // set the origin along D direction to overcome the possible incompleteness of first block - ORG_D = start_z/10000.0F; - - // for each tile, compute the range of available slices - std::pair z_coords(start_z,end_z); - for(list::iterator i = stacks_list.begin(); i != stacks_list.end(); i++) { - (*i)->compute_z_ranges(&z_coords); - } - } - - //converting stacks_list (STL list of Stack*) into STACKS (2-D array of Stack*) - BLOCKS = new Block**[N_ROWS]; - for(int row=0; row < N_ROWS; row++) - BLOCKS[row] = new Block*[N_COLS]; - for(list::iterator i = stacks_list.begin(); i != stacks_list.end(); i++) - BLOCKS[(*i)->getROW_INDEX()][(*i)->getCOL_INDEX()] = (*i); - - // 2014-09-09. Alessandro. @FIXED both 'init()' and 'initFromXML()' methods to deal with empty stacks. Added call of 'normalize_stacks_attributes()' method. - // make stacks have the same attributes - normalize_stacks_attributes(); -} - -void BlockVolume::initChannels() throw (iom::exception) -{ - DIM_C = BLOCKS[0][0]->getN_CHANS(); - BYTESxCHAN = BLOCKS[0][0]->getN_BYTESxCHAN(); -} - -void BlockVolume::applyReferenceSystem(vm::ref_sys reference_system, float VXL_1, float VXL_2, float VXL_3) throw (iom::exception) -{ - #if VM_VERBOSE > 3 - printf("\t\t\t\tin BlockVolume::applyReferenceSystem(reference_system = {%d,%d,%d}, VXL_1 = %.2f, VXL_2 = %.2f, VXL_3 = %.2f)\n", - reference_system.first, reference_system.second, reference_system.third, VXL_1, VXL_2, VXL_3); - #endif - - /******************* 2) SETTING THE REFERENCE SYSTEM ******************** - The entire application uses a vertical-horizontal reference system, so - it is necessary to fit the original reference system into the new one. - *************************************************************************/ - - //adjusting possible sign mismatch between reference system and VXL - //in these cases VXL is adjusted to match with reference system - if(SIGN(reference_system.first) != SIGN(VXL_1)) - VXL_1*=-1.0f; - if(SIGN(reference_system.second) != SIGN(VXL_2)) - VXL_2*=-1.0f; - if(SIGN(reference_system.third) != SIGN(VXL_3)) - VXL_3*=-1.0f; - - //HVD --> VHD - if (abs(reference_system.first)==2 && abs(reference_system.second)==1 && reference_system.third==3) - { - this->rotate(90); - this->mirror(vm::axis(2)); - - if(reference_system.first == -2) - this->mirror(vm::axis(2)); - if(reference_system.second == -1) - this->mirror(vm::axis(1)); - - int computed_ORG_1, computed_ORG_2, computed_ORG_3; - - // 2015-07-30. Giulio. @FIXED bug: sparse data support - if(SPARSE_DATA) - { - extractCoordinates(BLOCKS[0][0], 0, &computed_ORG_1, &computed_ORG_2); - } - else { - // 2014-09-01. Alessandro. @FIXED: check that this tile has a slice at z=0. Otherwise it's not possible to compute the origin. - if(BLOCKS[0][0]->isComplete(0,0) == false) - throw iom::exception(vm::strprintf("in StackedVolume::applyReferenceSystem(): cannot compute origin. Tile (0,0) [%s] has no slice at z=0", BLOCKS[0][0]->getDIR_NAME()).c_str()); - - extractCoordinates(BLOCKS[0][0], 0, &computed_ORG_1, &computed_ORG_2, &computed_ORG_3); - ORG_D = computed_ORG_3/10000.0F; - } - ORG_V = computed_ORG_2/10000.0F; // 2015-08-03. Giulio. @FIXED bug - ORG_H = computed_ORG_1/10000.0F; - VXL_V = VXL_2 ; - VXL_H = VXL_1 ; - VXL_D = VXL_3 ; - int tmp_coord_1, tmp_coord_2, tmp_coord_4, tmp_coord_5; - extractCoordinates(BLOCKS[0][0], 0, &tmp_coord_1, &tmp_coord_2); - if(N_ROWS > 1) - { - extractCoordinates(BLOCKS[1][0], 0, &tmp_coord_4, &tmp_coord_5); - this->MEC_V = (tmp_coord_5 - tmp_coord_2)/10.0F; - } - else - this->MEC_V = getStacksHeight()*VXL_V; - if(N_COLS > 1) - { - extractCoordinates(BLOCKS[0][1], 0, &tmp_coord_4, &tmp_coord_5); - this->MEC_H = (tmp_coord_4 - tmp_coord_1)/10.0F; - } - else - this->MEC_H = getStacksWidth()*VXL_H; - this->N_SLICES = BLOCKS[0][0]->getDEPTH(); - } - //VHD --> VHD - else if (abs(reference_system.first)==1 && abs(reference_system.second)==2 && reference_system.third==3) - { - if(reference_system.first == -1) - this->mirror(vm::axis(1)); - if(reference_system.second == -2) - this->mirror(vm::axis(2)); - - int computed_ORG_1, computed_ORG_2, computed_ORG_3; - - // 2015-07-22. Giulio. @ADDED sparse data support - if(SPARSE_DATA) - { - extractCoordinates(BLOCKS[0][0], 0, &computed_ORG_1, &computed_ORG_2); - } - else { - // 2014-09-01. Alessandro. @FIXED: check that this tile has a slice at z=0. Otherwise it's not possible to compute the origin. - if(BLOCKS[0][0]->isComplete(0,0) == false) - throw iom::exception(vm::strprintf("in StackedVolume::applyReferenceSystem(): cannot compute origin. Tile (0,0) [%s] has no slice at z=0", BLOCKS[0][0]->getDIR_NAME()).c_str()); - - extractCoordinates(BLOCKS[0][0], 0, &computed_ORG_1, &computed_ORG_2, &computed_ORG_3); - ORG_D = computed_ORG_3/10000.0F; - } - ORG_V = computed_ORG_1/10000.0F; - ORG_H = computed_ORG_2/10000.0F; - VXL_V = VXL_1; - VXL_H = VXL_2; - VXL_D = VXL_3; - int tmp_coord_1, tmp_coord_2, tmp_coord_4, tmp_coord_5; - extractCoordinates(BLOCKS[0][0], 0, &tmp_coord_1, &tmp_coord_2); - - if(N_ROWS > 1) - { - extractCoordinates(BLOCKS[1][0], 0, &tmp_coord_4, &tmp_coord_5); - this->MEC_V = (tmp_coord_4 - tmp_coord_1)/10.0F; - } - else - this->MEC_V = getStacksHeight()*VXL_V; - if(N_COLS > 1) - { - extractCoordinates(BLOCKS[0][1], 0, &tmp_coord_4, &tmp_coord_5); - this->MEC_H = (tmp_coord_5 - tmp_coord_2)/10.0F; - } - else - this->MEC_H = getStacksWidth()*VXL_H; - this->N_SLICES = BLOCKS[0][0]->getDEPTH(); - } - else //unsupported reference system - { - char msg[500]; - sprintf(msg, "in BlockVolume::init(...): the reference system {%d,%d,%d} is not supported.", - reference_system.first, reference_system.second, reference_system.third); - throw iom::exception(msg); - } - - //some little adjustments of the origin - if(VXL_V < 0) - ORG_V -= (BLOCKS[0][0]->getHEIGHT()-1)* VXL_V/1000.0F; - - if(VXL_H < 0) - ORG_H -= (BLOCKS[0][0]->getWIDTH() -1)* VXL_H/1000.0F; - - //inserting motorized stages coordinates - for(int i=0; isetABS_V(BLOCKS[i-1][j]->getABS_V() + getDEFAULT_DISPLACEMENT_V()); - else - BLOCKS[i][j]->setABS_V(0); - if(j!=0) - BLOCKS[i][j]->setABS_H(BLOCKS[i][j-1]->getABS_H() + getDEFAULT_DISPLACEMENT_H()); - else - BLOCKS[i][j]->setABS_H(0); - BLOCKS[i][j]->setABS_D(getDEFAULT_DISPLACEMENT_D()); - } -} - -void BlockVolume::saveBinaryMetadata(char *metadata_filepath) throw (iom::exception) -{ - #if VM_VERBOSE > 3 - printf("\t\t\t\tin BlockVolume::saveBinaryMetadata(char *metadata_filepath = %s)\n", metadata_filepath); - #endif - - //LOCAL VARIABLES - uint16 str_size; - FILE *file; - int i,j; - - if(!(file = fopen(metadata_filepath, "wb"))) - throw iom::exception("in BlockVolume::saveBinaryMetadata(...): unable to save binary metadata file"); - str_size = (uint16) strlen(stacks_dir) + 1; - fwrite(&str_size, sizeof(uint16), 1, file); - fwrite(stacks_dir, str_size, 1, file); - fwrite(&reference_system.first, sizeof(vm::axis), 1, file); // GI_140501 - fwrite(&reference_system.second, sizeof(vm::axis), 1, file); // GI_140501 - fwrite(&reference_system.third, sizeof(vm::axis), 1, file); // GI_140501 - fwrite(&VXL_V, sizeof(float), 1, file); - fwrite(&VXL_H, sizeof(float), 1, file); - fwrite(&VXL_D, sizeof(float), 1, file); - fwrite(&ORG_V, sizeof(float), 1, file); - fwrite(&ORG_H, sizeof(float), 1, file); - fwrite(&ORG_D, sizeof(float), 1, file); - fwrite(&MEC_V, sizeof(float), 1, file); - fwrite(&MEC_H, sizeof(float), 1, file); - fwrite(&N_ROWS, sizeof(uint16), 1, file); - fwrite(&N_COLS, sizeof(uint16), 1, file); - - // 2014-09-02. Alessandro. @FIXED as 'N_SLICES' changed from 'uint16' to 'int' type. See vmVirtualVolume.h. - fwrite(&N_SLICES, sizeof(int), 1, file); - - for(i = 0; i < N_ROWS; i++) - for(j = 0; j < N_COLS; j++) - BLOCKS[i][j]->binarizeInto(file); - - fclose(file); -} - -void BlockVolume::loadBinaryMetadata(char *metadata_filepath) throw (iom::exception) -{ - #if VM_VERBOSE > 3 - printf("\t\t\t\tin BlockVolume::loadBinaryMetadata(char *metadata_filepath = %s)\n", metadata_filepath); - #endif - - //LOCAL VARIABLES - uint16 str_size; - char *temp; // GI_140425 - bool regen = false; - FILE *file; - int i,j; - size_t fread_return_val; - - if(!(file = fopen(metadata_filepath, "rb"))) - throw iom::exception("in BlockVolume::loadBinaryMetadata(...): unable to load binary metadata file"); - // str_size = (uint16) strlen(stacks_dir) + 1; // GI_140425 remodev because has with no effect - fread_return_val = fread(&str_size, sizeof(uint16), 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in BlockVolume::loadBinaryMetadata(...) error while reading binary metadata file"); - } - // GI_140425 a check has been introduced to avoid that an out-of-date mdata.bin contains a wrong rood directory - temp = new char[str_size]; - fread_return_val = fread(temp, str_size, 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in BlockVolume::loadBinaryMetadata(...) error while reading binary metadata file"); - } - if ( !strcmp(temp,stacks_dir) ) // the two strings are equal - delete []temp; - else { // GI_140626: allow moving mdata.bin to other machine - delete []temp; - regen = true; - //fclose(file); - //throw iom::iom::exception("in BlockVolume::loadBinaryMetadata(...): binary metadata file is out-of-date"); - #if VM_VERBOSE > 3 - printf("\t\t\t\tin BlockVolume::loadBinaryMetadata(...): binary metadata file is out-of-date\n"); - #endif - } - - // GI_140501 - fread_return_val = fread(&reference_system.first, sizeof(vm::axis), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw iom::exception("in BlockVolume::unBinarizeFrom(...): error while reading binary metadata file"); - } - - // GI_140501 - fread_return_val = fread(&reference_system.second, sizeof(vm::axis), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw iom::exception("in BlockVolume::unBinarizeFrom(...): error while reading binary metadata file"); - } - - // GI_140501 - fread_return_val = fread(&reference_system.third, sizeof(vm::axis), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw iom::exception("in BlockVolume::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&VXL_V, sizeof(float), 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in BlockVolume::loadBinaryMetadata(...) error while reading binary metadata file"); - } - fread_return_val = fread(&VXL_H, sizeof(float), 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in BlockVolume::loadBinaryMetadata(...) error while reading binary metadata file"); - } - fread_return_val = fread(&VXL_D, sizeof(float), 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in BlockVolume::loadBinaryMetadata(...) error while reading binary metadata file"); - } - fread_return_val = fread(&ORG_V, sizeof(float), 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in BlockVolume::loadBinaryMetadata(...) error while reading binary metadata file"); - } - fread_return_val = fread(&ORG_H, sizeof(float), 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in BlockVolume::loadBinaryMetadata(...) error while reading binary metadata file"); - } - fread_return_val = fread(&ORG_D, sizeof(float), 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in BlockVolume::loadBinaryMetadata(...) error while reading binary metadata file"); - } - fread_return_val = fread(&MEC_V, sizeof(float), 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in BlockVolume::loadBinaryMetadata(...) error while reading binary metadata file"); - } - fread_return_val = fread(&MEC_H, sizeof(float), 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in BlockVolume::loadBinaryMetadata(...) error while reading binary metadata file"); - } - fread_return_val = fread(&N_ROWS, sizeof(uint16), 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in BlockVolume::loadBinaryMetadata(...) error while reading binary metadata file"); - } - fread_return_val = fread(&N_COLS, sizeof(uint16), 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in BlockVolume::loadBinaryMetadata(...) error while reading binary metadata file"); - } - - // 2014-09-02. Alessandro. @FIXED as 'N_SLICES' changed from 'uint16' to 'int' type. See vmVirtualVolume.h. - fread_return_val = fread(&N_SLICES, sizeof(int), 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in BlockVolume::loadBinaryMetadata(...) error while reading binary metadata file"); - } - BLOCKS = new Block **[N_ROWS]; - for(i = 0; i < N_ROWS; i++) - { - BLOCKS[i] = new Block *[N_COLS]; - for(j = 0; j < N_COLS; j++) - BLOCKS[i][j] = new Block(this, i, j, file); - } - - fclose(file); - - if ( regen ) { // GI_140626: directory name is changed, mdata.bin must be regenerated - saveBinaryMetadata(metadata_filepath); - } -} - -//rotate stacks matrix around D vm::axis (accepted values are theta=0,90,180,270) -void BlockVolume::rotate(int theta) -{ - #if VM_VERBOSE > 3 - printf("\t\t\t\tin BlockVolume::rotate(theta = %d)\n", theta); - #endif - - Block*** new_STACK_2D_ARRAY = NULL; - int new_N_ROWS=0, new_N_COLS=0; - - switch(theta) - { - case(0): break; - - case(90): - { - new_N_COLS = N_ROWS; - new_N_ROWS = N_COLS; - - //allocating new_STACK_2D_ARRAY - new_STACK_2D_ARRAY = new Block**[new_N_ROWS]; - for(int i=0; isetROW_INDEX(i); - new_STACK_2D_ARRAY[i][j]->setCOL_INDEX(j); - } - break; - } - case(180): - { - new_N_COLS=N_COLS; - new_N_ROWS=N_ROWS; - - //allocating new_STACK_2D_ARRAY - new_STACK_2D_ARRAY = new Block**[new_N_ROWS]; - for(int i=0; isetROW_INDEX(i); - new_STACK_2D_ARRAY[i][j]->setCOL_INDEX(j); - } - break; - } - case(270): - { - new_N_COLS=N_ROWS; - new_N_ROWS=N_COLS; - - //allocating new_STACK_2D_ARRAY - new_STACK_2D_ARRAY = new Block**[new_N_ROWS]; - for(int i=0; isetROW_INDEX(i); - new_STACK_2D_ARRAY[i][j]->setCOL_INDEX(j); - } - break; - } - } - - //deallocating current STACK_2DARRAY object - for(int row=0; row 3 - printf("\t\t\t\tin BlockVolume::mirror(mrr_axis = %d)\n", mrr_axis); - #endif - - if(mrr_axis!= 1 && mrr_axis != 2) - { - char msg[1000]; - sprintf(msg,"in BlockVolume::mirror(vm::axis mrr_axis=%d): unsupported vm::axis mirroring", mrr_axis); - throw iom::exception(msg); - } - - Block*** new_STACK_2D_ARRAY; - - switch(mrr_axis) - { - case(1): - { - //allocating new_STACK_2D_ARRAY - new_STACK_2D_ARRAY = new Block**[N_ROWS]; - for(int i=0; isetROW_INDEX(i); - new_STACK_2D_ARRAY[i][j]->setCOL_INDEX(j); - } - break; - } - case(2): - { - //allocating new_STACK_2D_ARRAY - new_STACK_2D_ARRAY = new Block**[N_ROWS]; - for(int i=0; isetROW_INDEX(i); - new_STACK_2D_ARRAY[i][j]->setCOL_INDEX(j); - } - break; - } - default: break; - } - - //deallocating current STACK_2DARRAY object - for(int row=0; rowgetDEPTH(); - - for ( int i=0; igetN_BLOCKS()-1) && coherent ) { - if ( current->getFILENAMES()[k] && current->getFILENAMES()[k+1] ) { // block is not empty and it is immediately followed by a non empty block - f_slice = atoi(name2coordZ(current->getFILENAMES()[k]).c_str()); - l_slice = atoi(name2coordZ(current->getFILENAMES()[k+1]).c_str()); - coherent = ( current->getBLOCK_SIZE()[k] == (int)floor( ((l_slice - f_slice) / (this->VXL_D * 10)) + 0.5 ) ); - } - k++; - } - if ( !coherent || (depth != BLOCKS[i][j]->getDEPTH()) ) { - if ( ok ) { // first anomaly: open and initialize the errlog file - if ( errlogFileName ) { - if ( (errlogf = fopen(errlogFileName,"w")) == 0 ) { - char errMsg[2000]; - sprintf(errMsg,"in BlockVolume::check(errlogFileName = \"%s\") : unable to open log file", errlogFileName); - throw iom::exception(errMsg); - } - - fprintf(errlogf,"errlog file of volume (BlockVolume): \"%s\"\n",stacks_dir); - fprintf(errlogf,"\tdepth: %d\n",depth); - } - - ok = false; - } - if ( errlogFileName && depth != BLOCKS[i][j]->getDEPTH() ) // reports error on stack depth - fprintf(errlogf,"\trow=%d, col=%d, depth=%d\n",i,j,BLOCKS[i][j]->getDEPTH()); - if ( errlogFileName && !coherent ) // reports error on coherence between block lenghts and filenames - fprintf(errlogf,"\trow=%d, col=%d, block lengths and filenames are not coherent\n",i,j); - } - } - } - - if ( errlogFileName && !ok ) // there are anomalies: close the errlog file - fclose(errlogf); - - return ok; -} - - -void BlockVolume::loadXML(const char *xml_filepath) throw (iom::exception) -{ - #if VM_VERBOSE > 3 - printf("\t\t\t\tin BlockVolume::loadXML(char *xml_filepath = %s)\n", xml_filepath); - #endif - - TiXmlDocument xml; - if(!xml.LoadFile(xml_filepath)) - { - char errMsg[2000]; - sprintf(errMsg,"in BlockVolume::loadXML(xml_filepath = \"%s\") : unable to load xml", xml_filepath); - throw iom::exception(errMsg); - } - - //setting ROOT element (that is the first child, i.e. node) - TiXmlHandle hRoot(xml.FirstChildElement("TeraStitcher")); - - // 2014-09-10. Alessandro. @ADDED 'volume_format' attribute to XML node - const char *volformat = hRoot.ToElement()->Attribute("volume_format"); - if(volformat && strcmp(volformat, id.c_str()) != 0) - throw iom::exception(vm::strprintf("in StackedVolume::initFromXML(): unsupported volume_format = \"%s\" (current format is \"%s\")", volformat, id.c_str()).c_str()); - - //reading fields and checking coherence with metadata previously read from VM_BIN_METADATA_FILE_NAME - TiXmlElement * pelem = hRoot.FirstChildElement("stacks_dir").Element(); - if(strcmp(pelem->Attribute("value"), stacks_dir) != 0) - { - char errMsg[2000]; - sprintf(errMsg, "in BlockVolume::loadXML(...): Mismatch in field between xml file (=\"%s\") and %s (=\"%s\").", pelem->Attribute("value"), vm::BINARY_METADATA_FILENAME.c_str(), stacks_dir); - throw iom::exception(errMsg); - } - // 2014-11-06. Giulio. @ADDED saved reference system into XML file - vm::ref_sys reference_system_read; - if ( (pelem = hRoot.FirstChildElement("ref_sys").Element()) != 0 ) { // skip if not present (for compatibility with previous versions) - pelem->QueryIntAttribute("ref1", (int *) &reference_system_read.first); - pelem->QueryIntAttribute("ref2", (int *) &reference_system_read.second); - pelem->QueryIntAttribute("ref3", (int *) &reference_system_read.third); - if (reference_system_read.first != reference_system.first || reference_system_read.second != reference_system.second || reference_system_read.third != reference_system.third ) - { - char errMsg[2000]; - sprintf(errMsg, "in BlockVolume::loadXML(...): Mismatch in field between xml file (= (%d,%d,%d) ) and %s (= (%d,%d,%d) ).", - reference_system_read.first, reference_system_read.second, reference_system_read.third, vm::BINARY_METADATA_FILENAME.c_str(), reference_system.first, reference_system.second, reference_system.third); - throw iom::exception(errMsg); - } - } - pelem = hRoot.FirstChildElement("voxel_dims").Element(); - float VXL_V_read=0.0f, VXL_H_read=0.0f, VXL_D_read=0.0f; - pelem->QueryFloatAttribute("V", &VXL_V_read); - pelem->QueryFloatAttribute("H", &VXL_H_read); - pelem->QueryFloatAttribute("D", &VXL_D_read); - if(VXL_V_read != VXL_V || VXL_H_read != VXL_H || VXL_D_read != VXL_D) - { - char errMsg[2000]; - sprintf(errMsg, "in BlockVolume::loadXML(...): Mismatch in field between xml file (= %.2f x %.2f x %.2f ) and %s (= %.2f x %.2f x %.2f ).", VXL_V_read, VXL_H_read, VXL_D_read, vm::BINARY_METADATA_FILENAME.c_str(), VXL_V, VXL_H, VXL_D); - throw iom::exception(errMsg); - } - pelem = hRoot.FirstChildElement("origin").Element(); - float ORG_V_read=0.0f, ORG_H_read=0.0f, ORG_D_read=0.0f; - pelem->QueryFloatAttribute("V", &ORG_V_read); - pelem->QueryFloatAttribute("H", &ORG_H_read); - pelem->QueryFloatAttribute("D", &ORG_D_read); - /*if(ORG_V_read != ORG_V || ORG_H_read != ORG_H || ORG_D_read != ORG_D) - { - char errMsg[2000]; - sprintf(errMsg, "in BlockVolume::loadXML(...): Mismatch in field between xml file (= {%.7f, %.7f, %.7f} ) and %s (= {%.7f, %.7f, %.7f} ).", ORG_V_read, ORG_H_read, ORG_D_read, VM_BIN_METADATA_FILE_NAME, ORG_V, ORG_H, ORG_D); - throw iom::iom::exception(errMsg); - } @TODO: bug with float precision causes often mismatch */ - pelem = hRoot.FirstChildElement("mechanical_displacements").Element(); - float MEC_V_read=0.0f, MEC_H_read=0.0f; - pelem->QueryFloatAttribute("V", &MEC_V_read); - pelem->QueryFloatAttribute("H", &MEC_H_read); - if(MEC_V_read != MEC_V || MEC_H_read != MEC_H) - { - char errMsg[2000]; - sprintf(errMsg, "in BlockVolume::loadXML(...): Mismatch in field between xml file (= %.1f x %.1f ) and %s (= %.1f x %.1f ).", MEC_V_read, MEC_H_read, vm::BINARY_METADATA_FILENAME.c_str(), MEC_V, MEC_H); - throw iom::exception(errMsg); - } - pelem = hRoot.FirstChildElement("dimensions").Element(); - int N_ROWS_read, N_COLS_read, N_SLICES_read; - pelem->QueryIntAttribute("stack_rows", &N_ROWS_read); - pelem->QueryIntAttribute("stack_columns", &N_COLS_read); - pelem->QueryIntAttribute("stack_slices", &N_SLICES_read); - if(N_ROWS_read != N_ROWS || N_COLS_read != N_COLS || N_SLICES_read != N_SLICES) - { - char errMsg[2000]; - sprintf(errMsg, "in BlockVolume::loadXML(...): Mismatch between in field xml file (= %d x %d ) and %s (= %d x %d ).", N_ROWS_read, N_COLS_read, vm::BINARY_METADATA_FILENAME.c_str(), N_ROWS, N_COLS); - throw iom::exception(errMsg); - } - - pelem = hRoot.FirstChildElement("STACKS").Element()->FirstChildElement(); - int i,j; - for(i=0; iNextSiblingElement()) - BLOCKS[i][j]->loadXML(pelem, N_SLICES); -} - -void BlockVolume::initFromXML(const char *xml_filepath) throw (iom::exception) -{ - #if VM_VERBOSE > 3 - printf("\t\t\t\tin BlockVolume::initFromXML(char *xml_filename = %s)\n", xml_filename); - #endif - - TiXmlDocument xml; - if(!xml.LoadFile(xml_filepath)) - { - char errMsg[2000]; - sprintf(errMsg,"in BlockVolume::initFromXML(xml_filepath = \"%s\") : unable to load xml", xml_filepath); - throw iom::exception(errMsg); - } - - //setting ROOT element (that is the first child, i.e. node) - TiXmlHandle hRoot(xml.FirstChildElement("TeraStitcher")); - - // 2014-09-10. Alessandro. @ADDED 'volume_format' attribute to XML node - const char *volformat = hRoot.ToElement()->Attribute("volume_format"); - if(volformat && strcmp(volformat, id.c_str()) != 0) - throw iom::exception(vm::strprintf("in StackedVolume::initFromXML(): unsupported volume_format = \"%s\" (current format is \"%s\")", volformat, id.c_str()).c_str()); - - //reading fields - TiXmlElement * pelem = hRoot.FirstChildElement("stacks_dir").Element(); - // 2014-11-06. Giulio. @ADDED saved reference system into XML file - if ( (pelem = hRoot.FirstChildElement("ref_sys").Element()) != 0 ) { // skip if not present (for compatibility with previous versions) - pelem->QueryIntAttribute("ref1", (int *) &reference_system.first); - pelem->QueryIntAttribute("ref2", (int *) &reference_system.second); - pelem->QueryIntAttribute("ref3", (int *) &reference_system.third); - } - else { - // 2014-11-06. Giulio. @MOVED in case XML is old - // 2014-09-09. Alessandro. @FIXED. Added default reference system if volume is imported from xml. - reference_system = vm::ref_sys(vm::vertical,vm::horizontal,vm::depth); - } - pelem = hRoot.FirstChildElement("voxel_dims").Element(); - pelem->QueryFloatAttribute("V", &VXL_V); - pelem->QueryFloatAttribute("H", &VXL_H); - pelem->QueryFloatAttribute("D", &VXL_D); - pelem = hRoot.FirstChildElement("origin").Element(); - pelem->QueryFloatAttribute("V", &ORG_V); - pelem->QueryFloatAttribute("H", &ORG_H); - pelem->QueryFloatAttribute("D", &ORG_D); - pelem = hRoot.FirstChildElement("mechanical_displacements").Element(); - pelem->QueryFloatAttribute("V", &MEC_V); - pelem->QueryFloatAttribute("H", &MEC_H); - pelem = hRoot.FirstChildElement("dimensions").Element(); - int nrows, ncols, nslices; - pelem->QueryIntAttribute("stack_rows", &nrows); - pelem->QueryIntAttribute("stack_columns", &ncols); - pelem->QueryIntAttribute("stack_slices", &nslices); - N_ROWS = nrows; - N_COLS = ncols; - N_SLICES = nslices; - - pelem = hRoot.FirstChildElement("STACKS").Element()->FirstChildElement(); - BLOCKS = new Block **[N_ROWS]; - for(int i = 0; i < N_ROWS; i++) - { - BLOCKS[i] = new Block *[N_COLS]; - for(int j = 0; j < N_COLS; j++, pelem = pelem->NextSiblingElement()) - { - // 2015-01-17. Alessandro. @ADDED support for all-in-one-folder data (import from xml only). - BLOCKS[i][j] = new Block(this, i, j, pelem, N_SLICES); - - //BLOCKS[i][j] = new Block(this, i, j, pelem->Attribute("DIR_NAME")); - //BLOCKS[i][j]->loadXML(pelem, N_SLICES); - } - } - - // 2014-09-09. Alessandro. @FIXED both 'init()' and 'initFromXML()' methods to deal with empty stacks. Added call of 'normalize_stacks_attributes()' method. - // make stacks have the same attributes - normalize_stacks_attributes(); -} - -void BlockVolume::saveXML(const char *xml_filename, const char *xml_filepath) throw (iom::exception) -{ - #if VM_VERBOSE > 3 - printf("\t\t\t\tin BlockVolume::saveXML(char *xml_filename = %s)\n", xml_filename); - #endif - - //LOCAL VARIABLES - char xml_abs_path[S_STATIC_STRINGS_SIZE]; - TiXmlDocument xml; - TiXmlElement * root; - TiXmlElement * pelem; - int i,j; - - //obtaining XML absolute path - if(xml_filename) - sprintf(xml_abs_path, "%s/%s.xml", stacks_dir, xml_filename); - else if(xml_filepath) - strcpy(xml_abs_path, xml_filepath); - else - throw iom::exception("in BlockVolume::saveXML(...): no xml path provided"); - - //initializing XML file with DTD declaration - fstream XML_FILE(xml_abs_path, ios::out); - XML_FILE<<""<"< and children nodes - root = new TiXmlElement("TeraStitcher"); - xml.LinkEndChild( root ); - - // 2014-09-10. Alessandro. @ADDED 'volume_format' attribute to XML node - root->SetAttribute("volume_format", id.c_str()); - - pelem = new TiXmlElement("stacks_dir"); - pelem->SetAttribute("value", stacks_dir); - root->LinkEndChild(pelem); - // 2014-11-06. Giulio. @ADDED saved reference system into XML file - pelem = new TiXmlElement("ref_sys"); - pelem->SetAttribute("ref1", reference_system.first); - pelem->SetAttribute("ref2", reference_system.second); - pelem->SetAttribute("ref3", reference_system.third); - root->LinkEndChild(pelem); - pelem = new TiXmlElement("voxel_dims"); - pelem->SetDoubleAttribute("V", VXL_V); - pelem->SetDoubleAttribute("H", VXL_H); - pelem->SetDoubleAttribute("D", VXL_D); - root->LinkEndChild(pelem); - pelem = new TiXmlElement("origin"); - pelem->SetDoubleAttribute("V", ORG_V); - pelem->SetDoubleAttribute("H", ORG_H); - pelem->SetDoubleAttribute("D", ORG_D); - root->LinkEndChild(pelem); - pelem = new TiXmlElement("mechanical_displacements"); - pelem->SetDoubleAttribute("V", MEC_V); - pelem->SetDoubleAttribute("H", MEC_H); - root->LinkEndChild(pelem); - pelem = new TiXmlElement("dimensions"); - pelem->SetAttribute("stack_rows", N_ROWS); - pelem->SetAttribute("stack_columns", N_COLS); - pelem->SetAttribute("stack_slices", N_SLICES); - root->LinkEndChild(pelem); - - //inserting stack nodes - pelem = new TiXmlElement("STACKS"); - for(i=0; iLinkEndChild(BLOCKS[i][j]->getXML()); - root->LinkEndChild(pelem); - //saving the file - xml.SaveFile(); -} - -//counts the total number of displacements and the number of displacements per stack -void BlockVolume::countDisplacements(int& total, float& per_stack_pair) -{ - /* PRECONDITIONS: none */ - total = 0; - per_stack_pair = 0.0f; - for(int i=0; i(BLOCKS[i][j]->getEAST().size()); - total+= static_cast(BLOCKS[i][j]->getSOUTH().size()); - per_stack_pair += static_cast(BLOCKS[i][j]->getEAST().size()); - per_stack_pair += static_cast(BLOCKS[i][j]->getSOUTH().size()); - } - per_stack_pair /= 2*(N_ROWS*N_COLS) - N_ROWS - N_COLS; -} - -//counts the number of single-direction displacements having a reliability measure above the given threshold -void BlockVolume::countReliableSingleDirectionDisplacements(float threshold, int& total, int& reliable) -{ - /* PRECONDITIONS: - * - for each pair of adjacent stacks one and only one displacement exists (CHECKED) */ - - total = reliable = 0; - for(int i=0; igetEAST().size()==1) - { - total+=3; - reliable += BLOCKS[i][j]->getEAST()[0]->getReliability(dir_vertical) >= threshold; - reliable += BLOCKS[i][j]->getEAST()[0]->getReliability(dir_horizontal) >= threshold; - reliable += BLOCKS[i][j]->getEAST()[0]->getReliability(dir_depth) >= threshold; - } - if(i != (N_ROWS-1) && BLOCKS[i][j]->getSOUTH().size()==1) - { - total+=3; - reliable += BLOCKS[i][j]->getSOUTH()[0]->getReliability(dir_vertical) >= threshold; - reliable += BLOCKS[i][j]->getSOUTH()[0]->getReliability(dir_horizontal) >= threshold; - reliable += BLOCKS[i][j]->getSOUTH()[0]->getReliability(dir_depth) >= threshold; - } - } -} - -//counts the number of stitchable stacks given the reliability threshold -int BlockVolume::countStitchableStacks(float threshold) -{ - /* PRECONDITIONS: - * - for each pair of adjacent stacks one and only one displacement exists (CHECKED) */ - - //stitchable stacks are stacks that have at least one reliable single-direction displacement - int stitchables = 0; - bool stitchable; - for(int i=0; igetNORTH().size()==1) - for(int k=0; k<3; k++) - stitchable = stitchable || (stk->getNORTH()[0]->getReliability(direction(k)) >= threshold); - if(j!= (N_COLS -1) && BLOCKS[i][j]->getEAST().size()==1) - for(int k=0; k<3; k++) - stitchable = stitchable || (stk->getEAST()[0]->getReliability(direction(k)) >= threshold); - if(i!= (N_ROWS -1) && BLOCKS[i][j]->getSOUTH().size()==1) - for(int k=0; k<3; k++) - stitchable = stitchable || (stk->getSOUTH()[0]->getReliability(direction(k)) >= threshold); - if(j!= 0 && BLOCKS[i][j]->getWEST().size()==1) - for(int k=0; k<3; k++) - stitchable = stitchable || (stk->getWEST()[0]->getReliability(direction(k)) >= threshold); - stitchables += stitchable; - } - return stitchables; -} - -// 2014-09-05. Alessandro. @ADDED 'normalize_stacks_attributes()' method to normalize stacks attributes (width, height, etc.) -void BlockVolume::normalize_stacks_attributes() throw (iom::exception) -{ - std::set heights, widths, nbytes, nchans; - for(int i=0; iisEmpty()) - continue; - - heights.insert(BLOCKS[i][j]->HEIGHT); - widths.insert(BLOCKS[i][j]->WIDTH); - nbytes.insert(BLOCKS[i][j]->N_BYTESxCHAN); - nchans.insert(BLOCKS[i][j]->N_CHANS); - - } - - // make the checks - if(heights.size() != 1) - throw iom::exception("in BlockVolume::check_stacks_same_dims(...): Stacks have unequal 'HEIGHT' attribute. This feature is not supported yet."); - if(widths.size() != 1) - throw iom::exception("in BlockVolume::check_stacks_same_dims(...): Stacks have unequal 'WIDTH' attribute. This feature is not supported yet."); - if(nbytes.size() != 1) - throw iom::exception("in BlockVolume::check_stacks_same_dims(...): Stacks have unequal 'N_BYTESxCHAN' attribute. This feature is not supported yet."); - if(nchans.size() != 1) - throw iom::exception("in BlockVolume::check_stacks_same_dims(...): Stacks have unequal 'N_CHANS' attribute. This feature is not supported yet."); - - // make empty stacks having the same attributes of other stacks - for(int i=0; iisEmpty()) - { - BLOCKS[i][j]->HEIGHT = *(heights.begin()); - BLOCKS[i][j]->WIDTH = *(widths.begin()); - BLOCKS[i][j]->N_CHANS = *(nchans.begin()); - BLOCKS[i][j]->N_BYTESxCHAN = *(nbytes.begin()); - } -} diff --git a/v3d_main/terafly/src/core/volumemanager/vmBlockVolume.h b/v3d_main/terafly/src/core/volumemanager/vmBlockVolume.h deleted file mode 100644 index 7057118082..0000000000 --- a/v3d_main/terafly/src/core/volumemanager/vmBlockVolume.h +++ /dev/null @@ -1,127 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -* 2015-06-12. Giulio @ADDED 'check' method to check completeness and coherence of a volume -* 2015-02-26. Giulio. @ADDED initChannels private method to initialize fields DIM_C and BYTESxCHAN -* 2015-01-17. Alessandro. @FIXED missing throw(iom::exception) declaration in loadXML and initFromXML methods. -* 2014-09-20. Alessandro. @ADDED overwrite_mdata flag to the XML-based constructor. -* 2014-09-10. Alessandro. @ADDED plugin creation/registration functions to make 'StackedVolume' a volume format plugin. -* 2014-09-05. Alessandro. @ADDED 'normalize_stacks_attributes()' method to normalize stacks attributes (width, height, etc.) -*/ - -#ifndef _VM_BLOCK_VOLUME_H -#define _VM_BLOCK_VOLUME_H - -#include -#include -#include "volumemanager.config.h" -#include "iomanager.config.h" -#include "vmVirtualVolume.h" -#include "vmBlock.h" - - -class vm::BlockVolume : public vm::VirtualVolume -{ - private: - - // 2014-09-10. Alessandro. @ADDED plugin creation/registration functions to make 'StackedVolume' a volume format plugin. - static const std::string creator_id1, creator_id2; - static vm::VirtualVolume* createFromXML(const char* xml_path, bool ow_mdata) { return new BlockVolume(xml_path, ow_mdata); } - static vm::VirtualVolume* createFromData(const char* data_path, vm::ref_sys ref, float vxl1, float vxl2, float vxl3, bool ow_mdata) { - return new BlockVolume(data_path, ref, vxl1, vxl2, vxl3, ow_mdata); - } - - vm::Block ***BLOCKS; //2-D array of - - //Given the reference system, initializes all object's members using stack's directories hierarchy - void init() throw (iom::exception); - void initChannels() throw (iom::exception); - - void applyReferenceSystem(vm::ref_sys reference_system, float VXL_1, float VXL_2, float VXL_3) throw (iom::exception); - - //binary metadata load/save methods - void saveBinaryMetadata(char *metadata_filepath) throw (iom::exception); - void loadBinaryMetadata(char *metadata_filepath) throw (iom::exception); - - //rotate stacks matrix around D vm::axis (accepted values are theta=0,90,180,270) - void rotate(int theta); - - //mirror stacks matrix along mrr_axis (accepted values are mrr_axis=1,2,3) - void mirror(vm::axis mrr_axis); - - // iannello returns the number of channels of images composing the volume - //void initChannels ( ) throw (iom::iom::exception); - - // 2014-09-05. Alessandro. @ADDED 'normalize_stacks_attributes()' method to normalize stacks attributes (width, height, etc.) - void normalize_stacks_attributes() throw (iom::exception); - - public: - - // 2014-09-10. Alessandro. @ADDED plugin creation/registration functions to make 'StackedVolume' a volume format plugin. - static const std::string id; - - //CONSTRUCTORS-DECONSTRUCTOR - BlockVolume() : vm::VirtualVolume(){} - BlockVolume(const char* _stacks_dir, vm::ref_sys reference_system, float VXL_1=0, float VXL_2=0, float VXL_3=0, bool overwrite_mdata=false) throw (iom::exception); - BlockVolume(const char *xml_filepath, bool overwrite_mdata=false) throw (iom::exception); - ~BlockVolume(); - - // ******GET METHODS****** - int getStacksHeight() {return BLOCKS[0][0]->getHEIGHT();} - int getStacksWidth() {return BLOCKS[0][0]->getWIDTH();} - vm::VirtualStack*** getSTACKS() {return (vm::VirtualStack***)this->BLOCKS;} - - //loads/saves metadata from/in the given xml filename - void loadXML(const char *xml_filename) throw (iom::exception); - void initFromXML(const char *xml_filename) throw (iom::exception); - void saveXML(const char *xml_filename=0, const char *xml_filepath=0) throw (iom::exception); - - - /********************************************************************************** - * UTILITY methods - ***********************************************************************************/ - - //check if volume is complete and coherent; return true if the volume is ok, false otherwise - //if a file name is passed and the volume is not ok an error log file is generated - bool check(const char *errlogFileName = 0) throw (iom::exception); - - //counts the total number of displacements and the number of displacements per pair of adjacent stacks - void countDisplacements(int& total, float& per_stack_pair); - - //counts the number of single-direction displacements having a reliability measure above the given threshold - void countReliableSingleDirectionDisplacements(float threshold, int& total, int& reliable); - - //counts the number of stitchable stacks given the reliability threshold - int countStitchableStacks(float threshold); -}; - -namespace{ - const vm::BlockVolume* objectBlockVolume = new vm::BlockVolume(); -} - - -#endif /* BLOCK_VOLUME_H */ diff --git a/v3d_main/terafly/src/core/volumemanager/vmStack.cpp b/v3d_main/terafly/src/core/volumemanager/vmStack.cpp deleted file mode 100644 index f25b840fda..0000000000 --- a/v3d_main/terafly/src/core/volumemanager/vmStack.cpp +++ /dev/null @@ -1,761 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* -* Bria, A., Iannello, G., "TeraStitcher - A Tool for Fast 3D Automatic Stitching of Teravoxel-sized Microscopy Images", (2012) BMC Bioinformatics, 13 (1), art. no. 316. -* -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -* 2015-08-24. Giulio. @FIXED memory leak in loadImageStack -* 2015-02-28. Giulio. @ADDED saving of fields N_CHANS and N_BYTESxCHAN in the xml files -* 2015-02-26. Giulio. @ADDED initialization of fields N_CHANS and N_BYTESxCHAN in constructor; this information is NOT saved in mdata.bin and xml files -* 2015-01-17. Alessandro. @ADDED constructor for initialization from XML. -* 2015-01-17. Alessandro. @ADDED support for all-in-one-folder data (import from xml only). -* 2014-09-12. Alessandro. @FIXED 'init()' method to deal with non-empty tiles. -* 2014-09-05. Alessandro. @ADDED 'z_end' parameter in 'loadXML()' method to support sparse data feature. -* 2014-09-03. Alessandro. @ADDED 'Z_RANGES' attribute in the xml node. -* 2014-09-01. Alessandro. @FIXED 'binarizeInto()' and 'unbinarizeFrom()' to support sparse tiles. -* 2014-08-30. Alessandro. @ADDED 'hasValidImageData()' method. -* 2014-08-25. Alessandro. @REMOVED unused 'entry_k' variable declared in 'init()'. -*/ - -#ifdef _WIN32 - #include "dirent_win.h" -#else - #include -#endif -#include -#include -#include -#include -#include -#include "vmStackedVolume.h" -#include "vmStack.h" -#include "StackStitcher.h" -#include "Displacement.h" -#include "IOPluginAPI.h" - -using namespace std; -using namespace vm; -using namespace iom; - -//CONSTRUCTOR WITH ARGUMENTS -Stack::Stack(StackedVolume* _CONTAINER, int _ROW_INDEX, int _COL_INDEX, const char* _DIR_NAME) throw (iom::exception) - : VirtualStack() -{ - #if VM_VERBOSE > 3 - printf("\t\t\t\tin Stack::Stack(StackedVolume* _CONTAINER, int _ROW_INDEX=%d, int _COL_INDEX=%d, char* _DIR_NAME=%s)\n", - _ROW_INDEX, _COL_INDEX, _DIR_NAME); - #endif - - CONTAINER = _CONTAINER; - DIR_NAME = new char[strlen(_DIR_NAME)+1]; - strcpy(DIR_NAME, _DIR_NAME); - ROW_INDEX = _ROW_INDEX; - COL_INDEX = _COL_INDEX; - - init(); -} - -// 2015-01-17. Alessandro. @ADDED constructor for initialization from XML. -Stack::Stack(StackedVolume* _CONTAINER, int _ROW_INDEX, int _COL_INDEX, TiXmlElement* stack_node, int z_end) throw (iom::exception) - : VirtualStack() -{ - #if VM_VERBOSE > 3 - printf("\t\t\t\tin Stack::Stack(StackedVolume* _CONTAINER, int _ROW_INDEX=%d, int _COL_INDEX=%d, TiXmlElement*, int z_end=%d)\n", - _ROW_INDEX, _COL_INDEX, z_end); - #endif - - // check for valid stack node - if(!stack_node) - throw iom::exception("not an xml node", __iom__current__function__); - if( strcmp(stack_node->ToElement()->Value(), "Stack") != 0) - throw iom::exception(iom::strprintf("invalid xml node name: expected \"Stack\", found \"%s\"", stack_node->ToElement()->Value()), __iom__current__function__); - - CONTAINER = _CONTAINER; - DIR_NAME = new char[strlen(stack_node->Attribute("DIR_NAME"))+1]; - strcpy(DIR_NAME, stack_node->Attribute("DIR_NAME")); - ROW_INDEX = _ROW_INDEX; - COL_INDEX = _COL_INDEX; - - // first read image regex field (if any) from xml node - readImgRegex(stack_node); - - // then scan folder for images - init(); - - // finally load other xml attributes - loadXML(stack_node, z_end); -} - -Stack::Stack(StackedVolume* _CONTAINER, int _ROW_INDEX, int _COL_INDEX, FILE* bin_file) throw (iom::exception) - : VirtualStack() -{ - #if VM_VERBOSE > 3 - printf("\t\t\t\tin Stack::Stack(StackedVolume* _CONTAINER, int _ROW_INDEX=%d, int _COL_INDEX=%d, FILE* bin_file)\n", - _ROW_INDEX, _COL_INDEX); - #endif - - CONTAINER = _CONTAINER; - ROW_INDEX = _ROW_INDEX; - COL_INDEX = _COL_INDEX; - - unBinarizeFrom(bin_file); -} - -Stack::~Stack() -{ - #if VM_VERBOSE > 3 - printf("\t\t\t\tin Stack[%d,%d]::~Stack()\n",ROW_INDEX, COL_INDEX); - #endif - - NORTH.clear(); - EAST.clear(); - SOUTH.clear(); - WEST.clear(); - - if(FILENAMES) - { - for(int z=0; z 3 - printf("\t\t\t\tin Stack[%d,%d]::init()\n",ROW_INDEX, COL_INDEX); - #endif - - //LOCAL variables - string tmp; - DIR *cur_dir_lev3; - dirent *entry_lev3; - list entries_lev3; - string entry; - - //opening stack directory - char abs_path[S_STATIC_STRINGS_SIZE]; - sprintf(abs_path,"%s/%s", CONTAINER->getSTACKS_DIR(), DIR_NAME); - cur_dir_lev3 = opendir(abs_path); - if (!cur_dir_lev3) - { - char errMsg[S_STATIC_STRINGS_SIZE]; - sprintf(errMsg, "in Stack::init(): can't open directory \"%s\"", abs_path); - throw iom::exception(errMsg); - } - - //scanning third level of hierarchy which entries need to be ordered alphabetically. This is done using STL. - while ((entry_lev3=readdir(cur_dir_lev3))) - { - tmp = entry_lev3->d_name; - - // 2015-01-17. Alessandro. @ADDED support for all-in-one-folder data (import from xml only). - if(img_regex.empty()) - { - if(tmp.compare(".") != 0 && tmp.compare("..") != 0 && tmp.find(".") != string::npos) - entries_lev3.push_back(tmp); - } - else - { - boost::xpressive::sregex rex = boost::xpressive::sregex::compile(img_regex.c_str()); - boost::xpressive::smatch what; - if(boost::xpressive::regex_match(tmp, what, rex)) - entries_lev3.push_back(tmp); - } - } - entries_lev3.sort(); - DEPTH = (int)entries_lev3.size(); - - // close dir - closedir(cur_dir_lev3); - - // 2014-08-30. Alessandro. @FIXED to deal with sparse data. - // if stack is empty... - if(DEPTH == 0) - { - // ...and SPARSE_DATA option is active, then exit - if(vm::SPARSE_DATA) - return; - // ...otherwise throw an exception - else - { - if(img_regex.empty()) - throw iom::exception(vm::strprintf("in Stack[%s]::init(): stack is empty. If that was your intent, please use the 'sparse data' option", DIR_NAME).c_str()); - else - throw iom::exception(vm::strprintf("in Stack[%s]::init(): no files found that match regular expression \"%s\"", DIR_NAME, img_regex.c_str()).c_str()); - } - } - - // convert filenames_list (STL list of objects) into FILENAMES (1-D array of C-strings) - FILENAMES = new char*[DEPTH]; - for(int z=0; zreadMetadata(vm::strprintf("%s/%s/%s", CONTAINER->getSTACKS_DIR(), DIR_NAME, FILENAMES[0]), WIDTH, HEIGHT, N_BYTESxCHAN, N_CHANS); - - // 2014-09-12. Alessandro. @FIXED 'init()' method to deal with non-empty tiles. - // add to 'z_ranges' the full range - z_ranges.clear(); - z_ranges.push_back(vm::interval(0, DEPTH)); -} - -//binarizing-unbinarizing methods -void Stack::binarizeInto(FILE* file) throw (iom::exception) -{ - #if VM_VERBOSE > 3 - printf("\t\t\t\tin Stack[%d,%d]::binarizeInto(...)\n",ROW_INDEX, COL_INDEX); - #endif - - //LOCAL VARIABLES - uint16 str_size=0; - int i=0; - - fwrite(&HEIGHT, sizeof(int), 1, file); - fwrite(&WIDTH, sizeof(int), 1, file); - fwrite(&DEPTH, sizeof(int), 1, file); - fwrite(&ABS_V, sizeof(int), 1, file); - fwrite(&ABS_H, sizeof(int), 1, file); - fwrite(&ABS_D, sizeof(int), 1, file); - str_size = (uint16)strlen(DIR_NAME) + 1; - fwrite(&str_size, sizeof(uint16), 1, file); - fwrite(DIR_NAME, str_size, 1, file); - for(i = 0; i < DEPTH; i++) - { - // 2014-09-01. Alessandro. @FIXED: added support for sparse tiles - str_size = static_cast( FILENAMES[i] ? strlen(FILENAMES[i]) + 1 : 0); - fwrite(&str_size, sizeof(uint16), 1, file); - if(FILENAMES[i]) - fwrite(FILENAMES[i], str_size, 1, file); - } -} - -void Stack::unBinarizeFrom(FILE* file) throw (iom::exception) -{ - #if VM_VERBOSE > 3 - printf("\t\t\t\tin Stack[%d,%d]::unBinarizeFrom(...)\n",ROW_INDEX, COL_INDEX); - #endif - - //LOCAL VARIABLES - uint16 str_size; - int i; - size_t fread_return_val; - - fread_return_val = fread(&HEIGHT, sizeof(int), 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in Stack::unBinarizeFrom(...): error while reading binary metadata file"); - } - fread_return_val = fread(&WIDTH, sizeof(int), 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in Stack::unBinarizeFrom(...): error while reading binary metadata file"); - } - fread_return_val = fread(&DEPTH, sizeof(int), 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in Stack::unBinarizeFrom(...): error while reading binary metadata file"); - } - fread_return_val = fread(&ABS_V, sizeof(int), 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in Stack::unBinarizeFrom(...): error while reading binary metadata file"); - } - fread_return_val = fread(&ABS_H, sizeof(int), 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in Stack::unBinarizeFrom(...): error while reading binary metadata file"); - } - fread_return_val = fread(&ABS_D, sizeof(int), 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in Stack::unBinarizeFrom(...): error while reading binary metadata file"); - } - fread_return_val = fread(&str_size, sizeof(uint16), 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in Stack::unBinarizeFrom(...): error while reading binary metadata file"); - } - DIR_NAME = new char[str_size]; - fread_return_val = fread(DIR_NAME, str_size, 1, file); - FILENAMES = new char*[DEPTH]; - for(i = 0; i < DEPTH; i++) - { - fread_return_val = fread(&str_size, sizeof(uint16), 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in Stack::unBinarizeFrom(...): error while reading binary metadata file"); - } - - // 2014-09-01. Alessandro. @FIXED: added support for sparse tiles. - FILENAMES[i] = str_size ? new char[str_size] : 0; - if(str_size) - { - fread_return_val = fread(FILENAMES[i], str_size, 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in Stack::unBinarizeFrom(...): error while reading binary metadata file"); - } - } - } - - // 2014-09-01. Alessandro. @ADDED support for sparse data. - compute_z_ranges(); -} - -//XML methods -TiXmlElement* Stack::getXML() -{ - #if VM_VERBOSE > 3 - printf("......in Stack[%d,%d]::getXML()\n",ROW_INDEX, COL_INDEX); - #endif - - TiXmlElement *xml_representation = new TiXmlElement("Stack"); - xml_representation->SetAttribute("N_CHANS",N_CHANS); - xml_representation->SetAttribute("N_BYTESxCHAN",N_BYTESxCHAN); - xml_representation->SetAttribute("ROW",ROW_INDEX); - xml_representation->SetAttribute("COL",COL_INDEX); - xml_representation->SetAttribute("ABS_V",ABS_V); - xml_representation->SetAttribute("ABS_H",ABS_H); - xml_representation->SetAttribute("ABS_D",ABS_D); - xml_representation->SetAttribute("STITCHABLE",stitchable ? "yes" : "no"); - xml_representation->SetAttribute("DIR_NAME",DIR_NAME); - - // 2014-09-03. Alessandro. @ADDED 'Z_RANGES' attribute in the xml node - std::string z_ranges_string; - for(int k=0; kSetAttribute("Z_RANGES",z_ranges_string.c_str()); - writeImgRegex(xml_representation); - - vector::iterator i; - TiXmlElement *NORTH_displacements = new TiXmlElement("NORTH_displacements"); - for(i = NORTH.begin(); i != NORTH.end(); i++) - NORTH_displacements->LinkEndChild((*i)->getXML()); - TiXmlElement *EAST_displacements = new TiXmlElement("EAST_displacements"); - for(i = EAST.begin(); i != EAST.end(); i++) - EAST_displacements->LinkEndChild((*i)->getXML()); - TiXmlElement *SOUTH_displacements = new TiXmlElement("SOUTH_displacements"); - for(i = SOUTH.begin(); i != SOUTH.end(); i++) - SOUTH_displacements->LinkEndChild((*i)->getXML()); - TiXmlElement *WEST_displacements = new TiXmlElement("WEST_displacements"); - for(i = WEST.begin(); i != WEST.end(); i++) - WEST_displacements->LinkEndChild((*i)->getXML()); - xml_representation->LinkEndChild(NORTH_displacements); - xml_representation->LinkEndChild(EAST_displacements); - xml_representation->LinkEndChild(SOUTH_displacements); - xml_representation->LinkEndChild(WEST_displacements); - - return xml_representation; -} - -void Stack::loadXML( - TiXmlElement *stack_node, - int z_end) // 2014-09-05. Alessandro. @ADDED 'z_end' parameter to support sparse data feature - // Here 'z_end' identifies the range [0, z_end) that slices can span -throw (iom::exception) -{ - #if VM_VERBOSE > 3 - printf("\t\t\t\tin Stack[%d,%d]::loadXML(TiXmlElement *stack_node)\n",ROW_INDEX, COL_INDEX); - #endif - - stack_node->QueryIntAttribute("N_CHANS",&N_CHANS); - stack_node->QueryIntAttribute("N_BYTESxCHAN",&N_BYTESxCHAN); - if ( N_CHANS == -1 ||N_BYTESxCHAN == -1 ) { - iom::warning(iom::strprintf("old xml file: missing N_CHANS and N_BYTESxCHAN tags; class data members set to 1.").c_str(), __iom__current__function__); - // data members set to 1 assuming that there is only one 8bits channel - N_CHANS = 1; - N_BYTESxCHAN = 1; - } - - stack_node->QueryIntAttribute("ABS_V", &ABS_V); - stack_node->QueryIntAttribute("ABS_H", &ABS_H); - stack_node->QueryIntAttribute("ABS_D", &ABS_D); - stitchable = strcmp(stack_node->Attribute("STITCHABLE"),"yes")==0 ? true : false; - if(strcmp(stack_node->Attribute("DIR_NAME"), DIR_NAME) != 0) - { - char errMsg[2000]; - sprintf(errMsg, "in Stack[%s]::loadXML(...): Mismatch between xml file and %s in field.", DIR_NAME, vm::BINARY_METADATA_FILENAME.c_str()); - throw iom::exception(errMsg); - } - - // 2015-01-17. Alessandro. @ADDED support for all-in-one-folder data (import from xml only). - readImgRegex(stack_node); - - // 2014-09-03. Alessandro. @ADDED 'Z_RANGES' attribute in the xml node - const char* z_ranges_c = stack_node->Attribute("Z_RANGES"); - if( z_ranges_c ) // field is present: we can run 'sparse data' code - { - // nonempty tile - if ( strlen(z_ranges_c) != 0 ) - { - // parse 'Z_RANGES' field - z_ranges.clear(); - std::string z_ranges_c_str = z_ranges_c; - std::string z_ranges_string = vm::cls(z_ranges_c_str); - std::vector tokens; - vm::split(z_ranges_string, ";", tokens); - for(int i=0; i extremes; - vm::split(tokens[i].substr(1, tokens[i].size()-2), ",", extremes); - - // check correct parsing - if(extremes.size() != 2) - throw iom::exception(vm::strprintf("in Stack(%s)::loadXML(): cannot parse 'Z_RANGES' subentry \"%s\"", DIR_NAME, tokens[i].c_str()).c_str()); - - // get integral range - int start = vm::str2num(extremes[0]); - int end = vm::str2num(extremes[1]); - - // check valid range - if(start < 0 || start >= end || end > z_end) - throw iom::exception(vm::strprintf("in Stack(%s)::loadXML(): 'Z_RANGES' subentry \"%s\" is out of range [%d,%d) ", DIR_NAME, tokens[i].c_str(), 0, z_end).c_str()); - - // push range - z_ranges.push_back(vm::interval(start, end)); - } - - // check precondition: z_ranges should contain consecutive but not contiguous intervals [a_1,b_1), [a_2,b_2), ... such that a_n > b_(n-1) - for(int i=1; i b_(n-1). " - "Found a_%d(%d) <= b_%d(%d)", DIR_NAME, i, z_ranges[i].start, i-1, z_ranges[i-1].end).c_str()); - - // if 'FILENAMES' is not a sparse list... - if(DEPTH != z_end) - { - // make 'FILENAMES' a sparse list - char **FILENAMES_sparse = new char*[z_end]; - for(int z=0; z= DEPTH) - throw iom::exception(vm::strprintf("in Stack(%s)::loadXML(): no more slices available to cover z-range [%d,%d)", - DIR_NAME, z_ranges[k].start, z_ranges[k].end).c_str()); - - FILENAMES_sparse[z] = FILENAMES[i++]; - } - - // substitute list of filenames with its sparse version - if(FILENAMES) - delete[] FILENAMES; - FILENAMES = FILENAMES_sparse; - DEPTH = z_end; - } - // ...otherwise check if the sparse list matches with z_ranges - else - { - for(int i=0; i(0, DEPTH)); - } - - - TiXmlElement *NORTH_displacements = stack_node->FirstChildElement("NORTH_displacements"); - for(TiXmlElement *displ_node = NORTH_displacements->FirstChildElement("Displacement"); displ_node; displ_node = displ_node->NextSiblingElement()) - NORTH.push_back(Displacement::getDisplacementFromXML(displ_node)); - TiXmlElement *EAST_displacements = stack_node->FirstChildElement("EAST_displacements"); - for(TiXmlElement *displ_node = EAST_displacements->FirstChildElement("Displacement"); displ_node; displ_node = displ_node->NextSiblingElement()) - EAST.push_back(Displacement::getDisplacementFromXML(displ_node)); - TiXmlElement *SOUTH_displacements = stack_node->FirstChildElement("SOUTH_displacements"); - for(TiXmlElement *displ_node = SOUTH_displacements->FirstChildElement("Displacement"); displ_node; displ_node = displ_node->NextSiblingElement()) - SOUTH.push_back(Displacement::getDisplacementFromXML(displ_node)); - TiXmlElement *WEST_displacements = stack_node->FirstChildElement("WEST_displacements"); - for(TiXmlElement *displ_node = WEST_displacements->FirstChildElement("Displacement"); displ_node; displ_node = displ_node->NextSiblingElement()) - WEST.push_back(Displacement::getDisplacementFromXML(displ_node)); - -} - - -//loads image stack from to extremes included, if not specified loads entire Stack -iom::real_t* Stack::loadImageStack(int first_file, int last_file) throw (iom::exception) -{ - #if VM_VERBOSE > 3 - printf("\t\t\t\tin Stack[%d,%d](%s, empty = %s)::loadImageStack(first_file = %d, last_file = %d)\n",ROW_INDEX, COL_INDEX, DIR_NAME, isEmpty() ? "true": "false", first_file, last_file); - #endif - - //// if stack is empty in the given range, just return a black image - //if(isEmpty(first_file, last_file)) - //{ - // // check and adjust file selection - // first_file = (first_file == -1 ? 0 : first_file); - // last_file = (last_file == -1 ? DEPTH - 1 : last_file ); - // first_file = min(first_file, DEPTH-1); - // last_file = min(last_file, DEPTH-1); - - // // allocate and initialize a black stack - // uint64 image_size = static_cast(WIDTH) * static_cast(HEIGHT) * static_cast(last_file-first_file+1); - // STACKED_IMAGE = new iom::real_t[image_size]; - // for(uint64 k=0; kreadData(FILENAMES, DEPTH, - // (std::string(CONTAINER->getSTACKS_DIR()) + "/" + DIR_NAME).c_str(), first_file, last_file, isSparse()); - //} - - uint64 image_stack_width=0, image_stack_height=0, z=0; - iom::real_t *raw_data; - - unsigned char *data; - int img_width; - int img_height; - int img_bytes_x_chan; - int img_chans; - - // check and adjust file selection - first_file = (first_file == -1 ? 0 : first_file); - last_file = (last_file == -1 ? DEPTH - 1 : last_file ); - first_file = min(first_file, DEPTH-1); - last_file = min(last_file, DEPTH-1); - - if(isEmpty(first_file, last_file)) - { - // allocate and initialize a black stack - uint64 image_size = static_cast(WIDTH) * static_cast(HEIGHT) * static_cast(last_file-first_file+1); - STACKED_IMAGE = new iom::real_t[image_size]; - for(uint64 k=0; k last_file ) - throw iom::exception("unexpected exception: substack is entirely empty", __iom__current__function__); - - std::string image_path = std::string(CONTAINER->getSTACKS_DIR()) + "/" + DIR_NAME + "/" + FILENAMES[i]; - - iom::IOPluginFactory::getPlugin2D(iom::IMIN_PLUGIN)->readMetadata(image_path,img_width,img_height,img_bytes_x_chan,img_chans); - - // allocate buffer - data = new unsigned char[img_width * img_height * img_bytes_x_chan * img_chans]; - - // loop over files - for(int file_i = first_file; file_i <= last_file; file_i++, z++) { - - // skip missing slices if stack is sparse - if(isSparse() && !FILENAMES[file_i]) - continue; - - // if stack is not sparse, a missing slice must throw an iom::exception - if(!FILENAMES[file_i]) - throw iom::exception("invalid slice filename in non-sparse tile", __iom__current__function__); - - // build absolute image path - image_path = std::string(CONTAINER->getSTACKS_DIR()) + "/" + DIR_NAME + "/" + FILENAMES[file_i]; - - iom::IOPluginFactory::getPlugin2D(iom::IMIN_PLUGIN)->readData(image_path,img_width,img_height,img_bytes_x_chan,img_chans,data); - - // initialize output data and image dimensions - if(!STACKED_IMAGE) - { - image_stack_height = (uint64) img_height; - image_stack_width = (uint64) img_width; - uint64 image_stack_size = image_stack_width * image_stack_height * (last_file - first_file + 1); - STACKED_IMAGE = new iom::real_t[image_stack_size]; - for(uint64 j=0; j < image_stack_size; j++) - STACKED_IMAGE[j] = 0; // default is 0 (black) - } - else if(image_stack_width != (uint64)img_width || image_stack_height != (uint64)img_height) - throw iom::exception("images in stack have not the same dimensions", __iom__current__function__); - - int offset; - - // convert image to [0.0,1.0]-valued array - if ( img_chans == 1 ) { - raw_data = &STACKED_IMAGE[z*img_height*img_width]; - if ( img_bytes_x_chan == 1 ) { - for(int i = 0; i < (img_height * img_width); i++) - raw_data[i] = (iom::real_t) data[i]/255.0f; - } - else { // img_bytes_x_chan == 2 - for(int i = 0; i < (img_height * img_width); i++) - raw_data[i] = (iom::real_t) ((uint16 *)data)[i]/65535.0f; // data must be interpreted as a uint16 array - } - } - else { // conversion to an intensity image - // test how channel are stored in the returned buffer 'data' - if ( iom::IOPluginFactory::getPlugin2D(iom::IMIN_PLUGIN)->isChansInterleaved() ) { - if ( CHANS == iom::ALL ) { - throw iom::exception("conversion from multi-channel to intensity images not supported.", __iom__current__function__); - } - else if ( CHANS == iom::R ) { - offset = 0; - } - else if ( CHANS == iom::G ) { - offset = 1; - } - else if ( CHANS == iom::B ) { - offset = 2; - } - else { - throw iom::exception("wrong value for parameter iom::CHANNEL_SELECTION.", __iom__current__function__); - } - raw_data = &STACKED_IMAGE[z*img_height*img_width]; - if ( img_bytes_x_chan == 1 ) - for(int i = 0; i < (img_height * img_width); i++) - raw_data[i] = (iom::real_t) data[3*i + offset]/255.0f; - else // img_bytes_x_chan == 2 - for(int i = 0; i < (img_height * img_width); i++) - raw_data[i] = (iom::real_t) ((uint16 *)data)[3*i + offset]/65535.0f; // data must be interpreted as a uint16 array - } - else { - throw iom::exception("channels are not interleaved in the returned buffer 'data', conversion to intensity images not supported yet."); - } - } - } - - // 2015-08-24. Giulio. data must be released - delete [] data; - - return STACKED_IMAGE; -} - - -//deallocates memory used by STACKED_IMAGE -void Stack::releaseImageStack() -{ - if(STACKED_IMAGE) - delete[] STACKED_IMAGE; - STACKED_IMAGE=0; -} - -// compute 'z_ranges' -void - Stack::compute_z_ranges( - std::set const * z_coords /*= 0*/) // set of z-coordinates where at least one slice (of a certain stack) is available - throw (iom::exception) // if null, 'z_ranges' will be compute based on 'FILENAMES' vector -{ - // if 'z_coords' has been provided, we use it to associate each file in 'FILENAMES' to the correspondent z-coordinate - if(z_coords) - { - // check for nonempty 'z_coords' - if(z_coords->empty()) - throw iom::exception("in Stack::compute_z_ranges(): z_coords is empty"); - - // associate each file to the correspondent z-coordinate - char **FILENAMES_sparse = new char*[z_coords->size()]; - int DEPTH_sparse = 0; - int k=0; - for(std::set::const_iterator it = z_coords->begin(); it != z_coords->end(); it++) - { - if(kcompare(VirtualVolume::name2coordZ(FILENAMES[k])) == 0) - FILENAMES_sparse[DEPTH_sparse++] = FILENAMES[k++]; - else - FILENAMES_sparse[DEPTH_sparse++] = 0; - } - - - // substitute list of filenames with its sparse version - if(FILENAMES) - delete[] FILENAMES; - FILENAMES = FILENAMES_sparse; - DEPTH = DEPTH_sparse; - } - - // compute 'z_range' from 'FILENAMES' - bool interval_start = true; - bool interval_stop = false; - z_ranges.clear(); - for(int k=0; k(k, -1)); - } - if(FILENAMES[k] == 0 && interval_stop) - { - interval_start = true; - interval_stop = false; - z_ranges.back().end = k; - } - } - if(!z_ranges.empty() && z_ranges.back().end == -1) - z_ranges.back().end = DEPTH; -} diff --git a/v3d_main/terafly/src/core/volumemanager/vmStack.h b/v3d_main/terafly/src/core/volumemanager/vmStack.h deleted file mode 100644 index 4952616543..0000000000 --- a/v3d_main/terafly/src/core/volumemanager/vmStack.h +++ /dev/null @@ -1,101 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* -* Bria, A., Iannello, G., "TeraStitcher - A Tool for Fast 3D Automatic Stitching of Teravoxel-sized Microscopy Images", (2012) BMC Bioinformatics, 13 (1), art. no. 316. -* -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -* 2015-02-26. Giulio. @ADDED fields N_CHANS and N_BYTESxCHAN -* 2015-01-17. Alessandro. @ADDED constructor for initialization from XML. -* 2014-09-05. Alessandro. @ADDED 'z_end' parameter in 'loadXML()' method to support sparse data feature. -* 2014-09-01. Alessandro. @ADDED 'compute_z_ranges()' method to compute z-ranges on sparse data given the complete set of z-coordinates. -*/ - -#ifndef _VM_STACK_H_ -#define _VM_STACK_H_ - -#include "volumemanager.config.h" -#include "iomanager.config.h" -#include "tinyxml.h" -#include "vmVirtualStack.h" - - -class Displacement; -class vm::Stack : public vm::VirtualStack -{ - private: - - //*********** OBJECT ATTRIBUTES *********** - vm::StackedVolume* CONTAINER; //pointer to object that contains the current object - - //******** OBJECT PRIVATE METHODS ********* - Stack(void){} - - //Initializes all object's members - void init() throw (iom::exception); - - //binarizing-unbinarizing methods - void binarizeInto(FILE* file) throw (iom::exception); - void unBinarizeFrom(FILE* file) throw (iom::exception); - - // compute 'z_ranges' - void - compute_z_ranges( - std::set const * z_coords = 0) // set of z-coordinates where at least one slice (of a certain stack) is available - throw (iom::exception); // if null, 'z_ranges' will be compute based on 'FILENAMES' vector - - //******** FRIEND CLASS DECLARATION ********* - //StackedVolume can access Stack private members and methods - friend class vm::StackedVolume; - - public: - - //CONSTRUCTORS - Stack(vm::StackedVolume* _CONTAINER, int _ROW_INDEX, int _COL_INDEX, const char* _DIR_NAME) throw (iom::exception); // build from scratch - Stack(vm::StackedVolume* _CONTAINER, int _ROW_INDEX, int _COL_INDEX, FILE* bin_file) throw (iom::exception); // build from mdata.bin - Stack(vm::StackedVolume* _CONTAINER, int _ROW_INDEX, int _COL_INDEX, TiXmlElement* stack_node, int z_end) throw (iom::exception); // build from XML - ~Stack(void); - - //GET methods - void *getCONTAINER() {return CONTAINER;} - int getN_CHANS() {return N_CHANS;} - int getN_BYTESxCHAN() {return N_BYTESxCHAN;} - - //LOAD and RELEASE methods - iom::real_t* loadImageStack(int first_file=-1, int last_file=-1) throw (iom::exception); - void releaseImageStack(); - - //XML methods - TiXmlElement* getXML(); - void loadXML( - TiXmlElement *stack_node, - int z_end) // 2014-09-05. Alessandro. @ADDED 'z_end' parameter to support sparse data feature - // Here 'z_end' identifies the range [0, z_end) that slices can span - throw (iom::exception); -}; - -#endif /* STACK_H_ */ - diff --git a/v3d_main/terafly/src/core/volumemanager/vmStackedVolume.cpp b/v3d_main/terafly/src/core/volumemanager/vmStackedVolume.cpp deleted file mode 100644 index 553170ce1e..0000000000 --- a/v3d_main/terafly/src/core/volumemanager/vmStackedVolume.cpp +++ /dev/null @@ -1,1600 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* -* Bria, A., Iannello, G., "TeraStitcher - A Tool for Fast 3D Automatic Stitching of Teravoxel-sized Microscopy Images", (2012) BMC Bioinformatics, 13 (1), art. no. 316. -* -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -* 2015-06-12. Giulio @ADDED 'check' method to check completeness and coherence of a volume -* 2015-02-26. Giulio. @ADDED implementation of initChannels private method to initialize fields DIM_C and BYTESxCHAN -* 2015-01-17. Alessandro. @ADDED support for all-in-one-folder data (import from xml only). -* 2014-11-06. Giulio. @ADDED saved reference system into XML file -* 2014-09-20. Alessandro. @ADDED overwrite_mdata flag to the XML-based constructor. -* 2014-09-10. Alessandro. @ADDED 'volume_format' attribute to XML node. -* 2014-09-10. Alessandro. @ADDED plugin creation/registration functions to make 'StackedVolume' a volume format plugin. -* 2014-09-09. Alessandro. @FIXED. Added default reference system if volume is imported from xml. -* 2014-09-05. Alessandro. @ADDED 'normalize_stacks_attributes()' method to normalize stacks attributes (width, height, etc.) -* 2014-09-05. Alessandro. @FIXED 'StackedVolume(...)' constructors to support sparse data. -* 2014-09-04. Alessandro. @FIXED 'loadBinaryMetadata()' and 'saveBinaryMetadata()'. Added new fields in mdata.bin to avoid misinterpretation of the bytes: -* - : to avoid confusion between different modules producing the mdata.bin file (e.g. volumemanager, imagemanager) -* - : to avoid misinterpretation of the bytes when the structure of the file is modified. -* - : to avoid confusione between different classes producing the mdata.bin file (e.g. StackedVolume, BlockVolume) -* 2014-09-03. Alessandro. @FIXED 'init()' method: check that all the stacks have the same WIDTH and HEIGHT and also correct empty stacks. -* 2014-09-02. Alessandro. @FIXED both 'loadBinaryMetadata()' and 'saveBinaryMetadata()' as 'N_SLICES' changed from 'uint16' to 'int' type. See vmVirtualVolume.h. -* 2014-09-01. Alessandro. @FIXED 'applyReferenceSystem()' method to deal with sparse tiles. -* 2014-09-01. Alessandro. @ADDED sparse data support in the 'init()' method. -*/ - - -#ifdef _WIN32 -#include "dirent_win.h" -#else -#include -#endif -#include -#include -#include -#include -#include -#include -#include -#include "vmStackedVolume.h" -#include "S_config.h" -#include "tinyxml.h" -#include "vmStack.h" -#include "Displacement.h" - -#ifdef min -#undef min -#endif - -#ifdef max -#undef max -#endif - -using namespace std; -using namespace iom; -using namespace vm; - -// 2014-09-10. Alessandro. @ADDED plugin creation/registration functions to make 'StackedVolume' a volume format plugin. -const std::string StackedVolume::id = "TiledXY|2Dseries"; -const std::string StackedVolume::creator_id1 = volumemanager::VirtualVolumeFactory::registerPluginCreatorXML(&createFromXML, StackedVolume::id); -const std::string StackedVolume::creator_id2 = volumemanager::VirtualVolumeFactory::registerPluginCreatorData(&createFromData, StackedVolume::id); - -StackedVolume::StackedVolume(const char* _stacks_dir, vm::ref_sys _reference_system, float VXL_1, float VXL_2, float VXL_3, bool overwrite_mdata) throw (iom::exception) - : VirtualVolume(_stacks_dir, _reference_system, VXL_1, VXL_2, VXL_3) -{ - #if VM_VERBOSE > 3 - printf("\t\t\t\tin StackedVolume::StackedVolume(_stacks_dir=%s, reference_system = {%d,%d,%d}, VXL_1 = %.2f, VXL_2 = %.2f, VXL_3 = %.2f)\n", - _stacks_dir,reference_system.first, reference_system.second, reference_system.third, VXL_1, VXL_2, VXL_3); - #endif - - //trying to unserialize an already existing metadata file, if it doesn't exist the full initialization procedure is performed and metadata is saved - char mdata_filepath[VM_STATIC_STRINGS_SIZE]; - sprintf(mdata_filepath, "%s/%s", stacks_dir, vm::BINARY_METADATA_FILENAME.c_str()); - if(fileExists(mdata_filepath) && !overwrite_mdata) - loadBinaryMetadata(mdata_filepath); - else - { - if(_reference_system.first == axis_invalid || _reference_system.second == axis_invalid || - _reference_system.third == axis_invalid || VXL_1 == 0 || VXL_2 == 0 || VXL_3 == 0) - throw iom::exception("in StackedVolume::StackedVolume(...): invalid importing parameters"); - reference_system = _reference_system; // GI_140501: stores the reference system to generate the mdata.bin file for the output volumes - init(); - applyReferenceSystem(reference_system, VXL_1, VXL_2, VXL_3); - saveBinaryMetadata(mdata_filepath); - } - - initChannels(); - - // check all stacks have the same number of slices (@ADDED by Alessandro on 2014-03-06) - // 2014-09-05. Alessandro. @FIXED to support sparse data. - if(!vm::SPARSE_DATA) - { - for(int i=0; igetDEPTH() != N_SLICES) - { - throw iom::exception(iom::strprintf("in StackedVolume::StackedVolume(): unequal number of slices detected. Stack \"%s\" has %d, stack \"%s\" has %d. " - "Please activate the sparse data option if stacks are not complete", - STACKS[0][0]->getDIR_NAME(), STACKS[0][0]->getDEPTH(), STACKS[i][j]->getDIR_NAME(), STACKS[i][j]->getDEPTH()).c_str()); - } - } - } -} - -StackedVolume::StackedVolume(const char *xml_filepath, bool overwrite_mdata) throw (iom::exception) - : VirtualVolume(xml_filepath) -{ - #if VM_VERBOSE > 3 - printf("\t\t\t\tin StackedVolume::StackedVolume(xml_filepath=%s, overwrite_mdata = %s)\n", xml_filepath, overwrite_mdata ? "true" : "false"); - #endif - - //extracting field from XML - TiXmlDocument xml; - if(!xml.LoadFile(xml_filepath)) - { - char errMsg[2000]; - sprintf(errMsg,"in StackedVolume::StackedVolume(xml_filepath = \"%s\") : unable to load xml", xml_filepath); - throw iom::exception(errMsg); - } - TiXmlHandle hRoot(xml.FirstChildElement("TeraStitcher")); - TiXmlElement * pelem = hRoot.FirstChildElement("stacks_dir").Element(); - this->stacks_dir = new char[strlen(pelem->Attribute("value"))+1]; - strcpy(this->stacks_dir, pelem->Attribute("value")); - xml.Clear(); - - //trying to unserialize an already existing metadata file, if it doesn't exist the full initialization procedure is performed and metadata is saved - char mdata_filepath[2000]; - sprintf(mdata_filepath, "%s/%s", stacks_dir, vm::BINARY_METADATA_FILENAME.c_str()); - - // 2014-09-20. Alessandro. @ADDED overwrite_mdata flag - if(fileExists(mdata_filepath) && !overwrite_mdata) - { - // load mdata.bin content and xml content, also perform consistency check between mdata.bin and xml content - loadBinaryMetadata(mdata_filepath); - loadXML(xml_filepath); - } - else - { - // load xml content and generate mdata.bin - initFromXML(xml_filepath); - saveBinaryMetadata(mdata_filepath); - } - - initChannels(); - - // check all stacks have the same number of slices (@ADDED by Alessandro on 2014-03-06) - // 2014-09-05. Alessandro. @FIXED to support sparse data. - if(!vm::SPARSE_DATA) - { - for(int i=0; igetDEPTH() != N_SLICES) - { - throw iom::exception(iom::strprintf("in StackedVolume::StackedVolume(): unequal number of slices detected. N_SLICES = %d, but stack \"%s\" has %d" - "Please activate the sparse data option if stacks are not complete", - N_SLICES, STACKS[i][j]->getDIR_NAME(), STACKS[i][j]->getDEPTH()).c_str()); - } - } - } -} - -StackedVolume::~StackedVolume() -{ - #if VM_VERBOSE > 3 - printf("\t\t\t\tin StackedVolume::~StackedVolume(void)\n"); - #endif - - if(stacks_dir) - delete[] stacks_dir; - - if(STACKS) - { - for(int row=0; rowgetVXL_V();} //Alessandro - 23/03/2013: removed conversion from int to float -//float StackedVolume::getABS_H(int ABS_PIXEL_H) {return ORG_H * 1000 + ABS_PIXEL_H*this->getVXL_H();} //Alessandro - 23/03/2013: removed conversion from int to float -//float StackedVolume::getABS_D(int ABS_PIXEL_D) {return ORG_D * 1000 + ABS_PIXEL_D*this->getVXL_D();} //Alessandro - 23/03/2013: removed conversion from int to float -//float StackedVolume::getVXL_V() {return VXL_V;} -//float StackedVolume::getVXL_H() {return VXL_H;} -//float StackedVolume::getVXL_D() {return VXL_D;} -//float StackedVolume::getMEC_V() {return MEC_V;} -//float StackedVolume::getMEC_H() {return MEC_H;} -int StackedVolume::getStacksHeight() {return STACKS[0][0]->getHEIGHT();} -int StackedVolume::getStacksWidth() {return STACKS[0][0]->getWIDTH();} -//int StackedVolume::getN_ROWS() {return this->N_ROWS;} -//int StackedVolume::getN_COLS() {return this->N_COLS;} -//int StackedVolume::getN_SLICES() {return this->N_SLICES;} -VirtualStack*** StackedVolume::getSTACKS() {return (VirtualStack***)this->STACKS;} -//char* StackedVolume::getSTACKS_DIR() {return this->stacks_dir;} -//int StackedVolume::getOVERLAP_V() {return (int)(getStacksHeight() - MEC_V/VXL_V);} -//int StackedVolume::getOVERLAP_H() {return (int)(getStacksWidth() - MEC_H/VXL_H);} -//int StackedVolume::getDEFAULT_DISPLACEMENT_V() {return (int)(fabs(MEC_V/VXL_V));} -//int StackedVolume::getDEFAULT_DISPLACEMENT_H() {return (int)(fabs(MEC_H/VXL_H));} -//int StackedVolume::getDEFAULT_DISPLACEMENT_D() {return 0;} - -void StackedVolume::init() throw (iom::exception) -{ - #if VM_VERBOSE > 3 - printf("\t\t\t\tin StackedVolume::init()\n"); - #endif - - //LOCAL VARIABLES - string tmp_path; //string that contains temp paths during computation - string tmp; //string that contains temp data during computation - DIR *cur_dir_lev1; //pointer to DIR, the data structure that represents a DIRECTORY (level 1 of hierarchical structure) - DIR *cur_dir_lev2; //pointer to DIR, the data structure that represents a DIRECTORY (level 2 of hierarchical structure) - dirent *entry_lev1; //pointer to DIRENT, the data structure that represents a DIRECTORY ENTRY inside a directory (level 1) - dirent *entry_lev2; //pointer to DIRENT, the data structure that represents a DIRECTORY ENTRY inside a directory (level 2) - int i=0,j=0; //for counting of N_ROWS, N_COLS - list stacks_list; //each stack found in the hierarchy is pushed into this list - list entries_lev1; //list of entries of first level of hierarchy - list::iterator entry_i; //iterator for list 'entries_lev1' - list entries_lev2; //list of entries of second level of hierarchy - list::iterator entry_j; //iterator for list 'entries_lev2' - char stack_i_j_path[S_STATIC_STRINGS_SIZE]; - - //obtaining DIR pointer to stacks_dir (=NULL if directory doesn't exist) - if (!(cur_dir_lev1=opendir(stacks_dir))) - { - char msg[S_STATIC_STRINGS_SIZE]; - sprintf(msg,"in StackedVolume::init(...): Unable to open directory \"%s\"", stacks_dir); - throw iom::exception(msg); - } - - //scanning first level of hierarchy which entries need to be ordered alphabetically. This is done using STL. - while ((entry_lev1=readdir(cur_dir_lev1))) - { - tmp=entry_lev1->d_name; - if(tmp.find(".") == string::npos && tmp.find(" ") == string::npos) - entries_lev1.push_front(entry_lev1->d_name); - } - closedir(cur_dir_lev1); - entries_lev1.sort(); - N_ROWS = (uint16) entries_lev1.size(); - N_COLS = 0; - if(N_ROWS == 0) - throw iom::exception("in StackedVolume::init(...): Unable to find stacks in the given directory"); - - - //for each entry of first level, scanning second level - for(entry_i = entries_lev1.begin(), i=0; entry_i!= entries_lev1.end(); entry_i++, i++) - { - //building absolute path of first level entry to be used for "opendir(...)" - tmp_path=stacks_dir; - tmp_path.append("/"); - tmp_path.append(*entry_i); - cur_dir_lev2 = opendir(tmp_path.c_str()); - if (!cur_dir_lev2) - throw iom::exception("in StackedVolume::init(...): A problem occurred during scanning of subdirectories"); - - //scanning second level of hierarchy which entries need to be ordered alphabetically. This is done using STL. - while ((entry_lev2=readdir(cur_dir_lev2))) - { - tmp=entry_lev2->d_name; - if(tmp.find(".") == string::npos && tmp.find(" ") == string::npos) - entries_lev2.push_back(entry_lev2->d_name); - } - closedir(cur_dir_lev2); - entries_lev2.sort(); - - //for each entry of the second level, allocating a new Stack - for(entry_j = entries_lev2.begin(), j=0; entry_j!= entries_lev2.end(); entry_j++, j++) - { - //allocating new stack - sprintf(stack_i_j_path,"%s/%s",(*entry_i).c_str(), (*entry_j).c_str()); - Stack *new_stk = new Stack(this,i,j,stack_i_j_path); - stacks_list.push_back(new_stk); - } - entries_lev2.clear(); - if(N_COLS == 0) - N_COLS = j; - else if(j != N_COLS) - throw iom::exception("in StackedVolume::init(...): Number of second-level directories is not the same for all first-level directories!"); - } - entries_lev1.clear(); - - // intermediate check - if(N_ROWS == 0 || N_COLS == 0) - throw iom::exception("in StackedVolume::init(...): Unable to find stacks in the given directory"); - - // 2014-09-01. Alessandro. @ADDED sparse data support - // precondition: files must be named according to one of the two formats supported (see 'name2coordZ()') - if(SPARSE_DATA) - { - // compute N_SLICES as the cardinality of the set of all Z-coordinates extracted from the filenames of the entire volume - std::set z_coords; - for(list::iterator i = stacks_list.begin(); i != stacks_list.end(); i++) - for(int k=0; k< (*i)->DEPTH; k++) - z_coords.insert(name2coordZ((*i)->FILENAMES[k])); - N_SLICES = (int)(z_coords.size()); - - // check non-zero N_SLICES - if(N_SLICES == 0) - throw iom::exception("in StackedVolume::init(...): Unable to find image files in the given directory"); - - // for each tile, compute the range of available slices - for(list::iterator i = stacks_list.begin(); i != stacks_list.end(); i++) - (*i)->compute_z_ranges(&z_coords); - } - - //converting stacks_list (STL list of Stack*) into STACKS (2-D array of Stack*) - STACKS = new Stack**[N_ROWS]; - for(int row=0; row < N_ROWS; row++) - STACKS[row] = new Stack*[N_COLS]; - for(list::iterator i = stacks_list.begin(); i != stacks_list.end(); i++) - STACKS[(*i)->getROW_INDEX()][(*i)->getCOL_INDEX()] = (*i); - - // check stacks have the same width and height - normalize_stacks_attributes(); -} - -void StackedVolume::initChannels() throw (iom::exception) -{ - DIM_C = STACKS[0][0]->getN_CHANS(); - BYTESxCHAN = STACKS[0][0]->getN_BYTESxCHAN(); -} - -void StackedVolume::applyReferenceSystem(vm::ref_sys reference_system, float VXL_1, float VXL_2, float VXL_3) throw (iom::exception) -{ - #if VM_VERBOSE > 3 - printf("\t\t\t\tin StackedVolume::applyReferenceSystem(reference_system = {%d,%d,%d}, VXL_1 = %.2f, VXL_2 = %.2f, VXL_3 = %.2f)\n", - reference_system.first, reference_system.second, reference_system.third, VXL_1, VXL_2, VXL_3); - #endif - - /******************* 2) SETTING THE REFERENCE SYSTEM ******************** - The entire application uses a vertical-horizontal reference system, so - it is necessary to fit the original reference system into the new one. - *************************************************************************/ - - //adjusting possible sign mismatch between reference system and VXL - //in these cases VXL is adjusted to match with reference system - if(SIGN(reference_system.first) != SIGN(VXL_1)) - VXL_1*=-1.0f; - if(SIGN(reference_system.second) != SIGN(VXL_2)) - VXL_2*=-1.0f; - if(SIGN(reference_system.third) != SIGN(VXL_3)) - VXL_3*=-1.0f; - - //HVD --> VHD - if (abs(reference_system.first)==2 && abs(reference_system.second)==1 && reference_system.third==3) - { - this->rotate(90); - this->mirror(vm::axis(2)); - - if(reference_system.first == -2) - this->mirror(vm::axis(2)); - if(reference_system.second == -1) - this->mirror(vm::axis(1)); - - int computed_ORG_1, computed_ORG_2, computed_ORG_3; - - // 2014-09-01. Alessandro. @FIXED: check that this tile has a slice at z=0. Otherwise it's not possible to compute the origin. - if(STACKS[0][0]->isComplete(0,0) == false) - throw iom::exception(vm::strprintf("in StackedVolume::applyReferenceSystem(): cannot compute origin. Tile (0,0) [%s] has no slice at z=0", STACKS[0][0]->getDIR_NAME()).c_str()); - - extractCoordinates(STACKS[0][0], 0, &computed_ORG_1, &computed_ORG_2, &computed_ORG_3); - ORG_V = computed_ORG_2/10000.0F; - ORG_H = computed_ORG_1/10000.0F; - ORG_D = computed_ORG_3/10000.0F; - VXL_V = VXL_2 ; - VXL_H = VXL_1 ; - VXL_D = VXL_3 ; - int tmp_coord_1, tmp_coord_2, tmp_coord_4, tmp_coord_5; - extractCoordinates(STACKS[0][0], 0, &tmp_coord_1, &tmp_coord_2); - if(N_ROWS > 1) - { - extractCoordinates(STACKS[1][0], 0, &tmp_coord_4, &tmp_coord_5); - this->MEC_V = (tmp_coord_5 - tmp_coord_2)/10.0F; - } - else - this->MEC_V = getStacksHeight()*VXL_V; - if(N_COLS > 1) - { - extractCoordinates(STACKS[0][1], 0, &tmp_coord_4, &tmp_coord_5); - this->MEC_H = (tmp_coord_4 - tmp_coord_1)/10.0F; - } - else - this->MEC_H = getStacksWidth()*VXL_H; - this->N_SLICES = STACKS[0][0]->getDEPTH(); - } - //VHD --> VHD - else if (abs(reference_system.first)==1 && abs(reference_system.second)==2 && reference_system.third==3) - { - if(reference_system.first == -1) - this->mirror(vm::axis(1)); - if(reference_system.second == -2) - this->mirror(vm::axis(2)); - - int computed_ORG_1, computed_ORG_2, computed_ORG_3; - - // 2014-09-01. Alessandro. @FIXED: check that this tile has a slice at z=0. Otherwise it's not possible to compute the origin. - if(STACKS[0][0]->isComplete(0,0) == false) - throw iom::exception(vm::strprintf("in StackedVolume::applyReferenceSystem(): cannot compute origin. Tile (0,0) [%s] has no slice at z=0", STACKS[0][0]->getDIR_NAME()).c_str()); - - extractCoordinates(STACKS[0][0], 0, &computed_ORG_1, &computed_ORG_2, &computed_ORG_3); - ORG_V = computed_ORG_1/10000.0F; - ORG_H = computed_ORG_2/10000.0F; - ORG_D = computed_ORG_3/10000.0F; - VXL_V = VXL_1; - VXL_H = VXL_2; - VXL_D = VXL_3; - int tmp_coord_1, tmp_coord_2, tmp_coord_4, tmp_coord_5; - extractCoordinates(STACKS[0][0], 0, &tmp_coord_1, &tmp_coord_2); - - if(N_ROWS > 1) - { - extractCoordinates(STACKS[1][0], 0, &tmp_coord_4, &tmp_coord_5); - this->MEC_V = (tmp_coord_4 - tmp_coord_1)/10.0F; - } - else - this->MEC_V = getStacksHeight()*VXL_V; - if(N_COLS > 1) - { - extractCoordinates(STACKS[0][1], 0, &tmp_coord_4, &tmp_coord_5); - this->MEC_H = (tmp_coord_5 - tmp_coord_2)/10.0F; - } - else - this->MEC_H = getStacksWidth()*VXL_H; - this->N_SLICES = STACKS[0][0]->getDEPTH(); - } - else //unsupported reference system - { - char msg[500]; - sprintf(msg, "in StackedVolume::init(...): the reference system {%d,%d,%d} is not supported.", - reference_system.first, reference_system.second, reference_system.third); - throw iom::exception(msg); - } - - //some little adjustments of the origin - if(VXL_V < 0) - ORG_V -= (STACKS[0][0]->getHEIGHT()-1)* VXL_V/1000.0F; - - if(VXL_H < 0) - ORG_H -= (STACKS[0][0]->getWIDTH() -1)* VXL_H/1000.0F; - - //inserting motorized stages coordinates - for(int i=0; isetABS_V(STACKS[i-1][j]->getABS_V() + getDEFAULT_DISPLACEMENT_V()); - else - STACKS[i][j]->setABS_V(0); - if(j!=0) - STACKS[i][j]->setABS_H(STACKS[i][j-1]->getABS_H() + getDEFAULT_DISPLACEMENT_H()); - else - STACKS[i][j]->setABS_H(0); - STACKS[i][j]->setABS_D(getDEFAULT_DISPLACEMENT_D()); - } -} - -void StackedVolume::loadXML(const char *xml_filepath) throw (iom::exception) -{ - #if VM_VERBOSE > 3 - printf("\t\t\t\tin StackedVolume::loadXML(char *xml_filepath = %s)\n", xml_filepath); - #endif - - TiXmlDocument xml; - if(!xml.LoadFile(xml_filepath)) - { - char errMsg[2000]; - sprintf(errMsg,"in StackedVolume::loadXML(xml_filepath = \"%s\") : unable to load xml", xml_filepath); - throw iom::exception(errMsg); - } - - //setting ROOT element (that is the first child, i.e. node) - TiXmlHandle hRoot(xml.FirstChildElement("TeraStitcher")); - - // 2014-09-10. Alessandro. @ADDED 'volume_format' attribute to XML node - const char *volformat = hRoot.ToElement()->Attribute("volume_format"); - if(volformat && strcmp(volformat, id.c_str()) != 0) - throw iom::exception(vm::strprintf("in StackedVolume::initFromXML(): unsupported volume_format = \"%s\" (current format is \"%s\")", volformat, id.c_str()).c_str()); - - //reading fields and checking coherence with metadata previously read from VM_BIN_METADATA_FILE_NAME - TiXmlElement * pelem = hRoot.FirstChildElement("stacks_dir").Element(); - if(strcmp(pelem->Attribute("value"), stacks_dir) != 0) - throw iom::exception(iom::strprintf("in StackedVolume::loadXML(...): Mismatch in field between xml file (=\"%s\") and %s (=\"%s\").", pelem->Attribute("value"), vm::BINARY_METADATA_FILENAME.c_str(), stacks_dir).c_str()); - // 2014-11-06. Giulio. @ADDED saved reference system into XML file - vm::ref_sys reference_system_read; - if ( (pelem = hRoot.FirstChildElement("ref_sys").Element()) != 0 ) { // skip if not present (for compatibility with previous versions) - pelem = hRoot.FirstChildElement("ref_sys").Element(); - pelem->QueryIntAttribute("ref1", (int *) &reference_system_read.first); - pelem->QueryIntAttribute("ref2", (int *) &reference_system_read.second); - pelem->QueryIntAttribute("ref3", (int *) &reference_system_read.third); - if (reference_system_read.first != reference_system.first || reference_system_read.second != reference_system.second || reference_system_read.third != reference_system.third ) - { - char errMsg[2000]; - sprintf(errMsg, "in BlockVolume::loadXML(...): Mismatch in field between xml file (= (%d,%d,%d) ) and %s (= (%d,%d,%d) ).", - reference_system_read.first, reference_system_read.second, reference_system_read.third, vm::BINARY_METADATA_FILENAME.c_str(), reference_system.first, reference_system.second, reference_system.third); - throw iom::exception(errMsg); - } - } - pelem = hRoot.FirstChildElement("voxel_dims").Element(); - float VXL_V_read=0.0f, VXL_H_read=0.0f, VXL_D_read=0.0f; - pelem->QueryFloatAttribute("V", &VXL_V_read); - pelem->QueryFloatAttribute("H", &VXL_H_read); - pelem->QueryFloatAttribute("D", &VXL_D_read); - if(VXL_V_read != VXL_V || VXL_H_read != VXL_H || VXL_D_read != VXL_D) - { - char errMsg[2000]; - sprintf(errMsg, "in StackedVolume::loadXML(...): Mismatch in field between xml file (= %.2f x %.2f x %.2f ) and %s (= %.2f x %.2f x %.2f ).", VXL_V_read, VXL_H_read, VXL_D_read, vm::BINARY_METADATA_FILENAME.c_str(), VXL_V, VXL_H, VXL_D); - throw iom::exception(errMsg); - } - pelem = hRoot.FirstChildElement("origin").Element(); - float ORG_V_read=0.0f, ORG_H_read=0.0f, ORG_D_read=0.0f; - pelem->QueryFloatAttribute("V", &ORG_V_read); - pelem->QueryFloatAttribute("H", &ORG_H_read); - pelem->QueryFloatAttribute("D", &ORG_D_read); - /*if(ORG_V_read != ORG_V || ORG_H_read != ORG_H || ORG_D_read != ORG_D) - { - char errMsg[2000]; - sprintf(errMsg, "in StackedVolume::loadXML(...): Mismatch in field between xml file (= {%.7f, %.7f, %.7f} ) and %s (= {%.7f, %.7f, %.7f} ).", ORG_V_read, ORG_H_read, ORG_D_read, VM_BIN_METADATA_FILE_NAME, ORG_V, ORG_H, ORG_D); - throw iom::iom::exception(errMsg); - } @TODO: bug with float precision causes often mismatch */ - pelem = hRoot.FirstChildElement("mechanical_displacements").Element(); - float MEC_V_read=0.0f, MEC_H_read=0.0f; - pelem->QueryFloatAttribute("V", &MEC_V_read); - pelem->QueryFloatAttribute("H", &MEC_H_read); - if(MEC_V_read != MEC_V || MEC_H_read != MEC_H) - { - char errMsg[2000]; - sprintf(errMsg, "in StackedVolume::loadXML(...): Mismatch in field between xml file (= %.1f x %.1f ) and %s (= %.1f x %.1f ).", MEC_V_read, MEC_H_read, vm::BINARY_METADATA_FILENAME.c_str(), MEC_V, MEC_H); - throw iom::exception(errMsg); - } - pelem = hRoot.FirstChildElement("dimensions").Element(); - int N_ROWS_read, N_COLS_read, N_SLICES_read; - pelem->QueryIntAttribute("stack_rows", &N_ROWS_read); - pelem->QueryIntAttribute("stack_columns", &N_COLS_read); - pelem->QueryIntAttribute("stack_slices", &N_SLICES_read); - if(N_ROWS_read != N_ROWS || N_COLS_read != N_COLS || N_SLICES_read != N_SLICES) - { - char errMsg[2000]; - sprintf(errMsg, "in StackedVolume::loadXML(...): Mismatch between in field xml file (= %d x %d x %d), %s (= %d x %d x %d).", N_ROWS_read, N_COLS_read, N_SLICES_read, vm::BINARY_METADATA_FILENAME.c_str(), N_ROWS, N_COLS, N_SLICES); - throw iom::exception(errMsg); - } - - pelem = hRoot.FirstChildElement("STACKS").Element()->FirstChildElement(); - int i,j; - for(i=0; iNextSiblingElement()) - STACKS[i][j]->loadXML(pelem, N_SLICES); -} - -void StackedVolume::initFromXML(const char *xml_filepath) throw (iom::exception) -{ - #if VM_VERBOSE > 3 - printf("\t\t\t\tin StackedVolume::initFromXML(char *xml_filename = %s)\n", xml_filepath); - #endif - - TiXmlDocument xml; - if(!xml.LoadFile(xml_filepath)) - { - char errMsg[2000]; - sprintf(errMsg,"in StackedVolume::initFromXML(xml_filepath = \"%s\") : unable to load xml", xml_filepath); - throw iom::exception(errMsg); - } - - //setting ROOT element (that is the first child, i.e. node) - TiXmlHandle hRoot(xml.FirstChildElement("TeraStitcher")); - - // 2014-09-10. Alessandro. @ADDED 'volume_format' attribute to XML node - const char *volformat = hRoot.ToElement()->Attribute("volume_format"); - if(volformat && strcmp(volformat, id.c_str()) != 0) - throw iom::exception(vm::strprintf("in StackedVolume::initFromXML(): unsupported volume_format = \"%s\" (current format is \"%s\")", volformat, id.c_str()).c_str()); - - //reading fields - TiXmlElement * pelem = hRoot.FirstChildElement("stacks_dir").Element(); - // 2014-11-06. Giulio. @ADDED saved reference system into XML file - if ( (pelem = hRoot.FirstChildElement("ref_sys").Element()) != 0 ) { // skip if not present (for compatibility with previous versions) - pelem->QueryIntAttribute("ref1", (int *) &reference_system.first); - pelem->QueryIntAttribute("ref2", (int *) &reference_system.second); - pelem->QueryIntAttribute("ref3", (int *) &reference_system.third); - } - else { - // 2014-11-06. Giulio. @MOVED in case XML is old - // 2014-09-09. Alessandro. @FIXED. Added default reference system if volume is imported from xml. - reference_system = vm::ref_sys(vm::vertical,vm::horizontal,vm::depth); - } - pelem = hRoot.FirstChildElement("voxel_dims").Element(); - pelem->QueryFloatAttribute("V", &VXL_V); - pelem->QueryFloatAttribute("H", &VXL_H); - pelem->QueryFloatAttribute("D", &VXL_D); - pelem = hRoot.FirstChildElement("origin").Element(); - pelem->QueryFloatAttribute("V", &ORG_V); - pelem->QueryFloatAttribute("H", &ORG_H); - pelem->QueryFloatAttribute("D", &ORG_D); - pelem = hRoot.FirstChildElement("mechanical_displacements").Element(); - pelem->QueryFloatAttribute("V", &MEC_V); - pelem->QueryFloatAttribute("H", &MEC_H); - pelem = hRoot.FirstChildElement("dimensions").Element(); - int nrows, ncols, nslices; - pelem->QueryIntAttribute("stack_rows", &nrows); - pelem->QueryIntAttribute("stack_columns", &ncols); - pelem->QueryIntAttribute("stack_slices", &nslices); - N_ROWS = nrows; - N_COLS = ncols; - N_SLICES = nslices; - - pelem = hRoot.FirstChildElement("STACKS").Element()->FirstChildElement(); - STACKS = new Stack **[N_ROWS]; - for(int i = 0; i < N_ROWS; i++) - { - STACKS[i] = new Stack *[N_COLS]; - for(int j = 0; j < N_COLS; j++, pelem = pelem->NextSiblingElement()) - { - // 2015-01-17. Alessandro. @ADDED support for all-in-one-folder data (import from xml only). - STACKS[i][j] = new Stack(this, i, j, pelem, N_SLICES); - - //STACKS[i][j] = new Stack(this, i, j, pelem->Attribute("DIR_NAME")); - //STACKS[i][j]->loadXML(pelem, N_SLICES); - } - } - - // check stacks have the same width and height - normalize_stacks_attributes(); -} - -void StackedVolume::saveXML(const char *xml_filename, const char *xml_filepath) throw (iom::exception) -{ - #if VM_VERBOSE > 3 - printf("\t\t\t\tin StackedVolume::saveXML(char *xml_filename = %s)\n", xml_filename); - #endif - - //LOCAL VARIABLES - char xml_abs_path[S_STATIC_STRINGS_SIZE]; - TiXmlDocument xml; - TiXmlElement * root; - TiXmlElement * pelem; - int i,j; - - //obtaining XML absolute path - if(xml_filename) - sprintf(xml_abs_path, "%s/%s.xml", stacks_dir, xml_filename); - else if(xml_filepath) - strcpy(xml_abs_path, xml_filepath); - else - throw iom::exception("in StackedVolume::saveXML(...): no xml path provided"); - - //initializing XML file with DTD declaration - fstream XML_FILE(xml_abs_path, ios::out); - XML_FILE<<""<"< and children nodes - root = new TiXmlElement("TeraStitcher"); - - // 2014-09-10. Alessandro. @ADDED 'volume_format' attribute to XML node - root->SetAttribute("volume_format", id.c_str()); - - xml.LinkEndChild( root ); - pelem = new TiXmlElement("stacks_dir"); - pelem->SetAttribute("value", stacks_dir); - root->LinkEndChild(pelem); - // 2014-11-06. Giulio. @ADDED saved reference system into XML file - pelem = new TiXmlElement("ref_sys"); - pelem->SetAttribute("ref1", reference_system.first); - pelem->SetAttribute("ref2", reference_system.second); - pelem->SetAttribute("ref3", reference_system.third); - pelem = new TiXmlElement("voxel_dims"); - pelem->SetDoubleAttribute("V", VXL_V); - pelem->SetDoubleAttribute("H", VXL_H); - pelem->SetDoubleAttribute("D", VXL_D); - root->LinkEndChild(pelem); - pelem = new TiXmlElement("origin"); - pelem->SetDoubleAttribute("V", ORG_V); - pelem->SetDoubleAttribute("H", ORG_H); - pelem->SetDoubleAttribute("D", ORG_D); - root->LinkEndChild(pelem); - pelem = new TiXmlElement("mechanical_displacements"); - pelem->SetDoubleAttribute("V", MEC_V); - pelem->SetDoubleAttribute("H", MEC_H); - root->LinkEndChild(pelem); - pelem = new TiXmlElement("dimensions"); - pelem->SetAttribute("stack_rows", N_ROWS); - pelem->SetAttribute("stack_columns", N_COLS); - pelem->SetAttribute("stack_slices", N_SLICES); - root->LinkEndChild(pelem); - - //inserting stack nodes - pelem = new TiXmlElement("STACKS"); - for(i=0; iLinkEndChild(STACKS[i][j]->getXML()); - root->LinkEndChild(pelem); - //saving the file - xml.SaveFile(); -} - -void StackedVolume::saveBinaryMetadata(char *metadata_filepath) throw (iom::exception) -{ - #if VM_VERBOSE > 3 - printf("\t\t\t\tin StackedVolume::saveBinaryMetadata(char *metadata_filepath = %s)\n", metadata_filepath); - #endif - - //LOCAL VARIABLES - uint16 str_size; - FILE *file; - int i,j; - - if(!(file = fopen(metadata_filepath, "wb"))) - throw iom::exception("in StackedVolume::saveBinaryMetadata(...): unable to save binary metadata file"); - - - // 2014-09-03. Alessandro. @FIXED: added unified header to retrieve module's signature, metadata file version, and class name - // ----- module's signature: to avoid confusion between different modules (e.g. volumemanager and imagemanager) - str_size = (uint16) strlen(vm::MODULE_ID.c_str()) + 1; - fwrite(&str_size, sizeof(uint16), 1, file); - fwrite(vm::MODULE_ID.c_str(), str_size, 1, file); - // ----- metadata file version: to avoid misinterpretation of mdata.bin bytes when its structure is changed - fwrite(&vm::BINARY_METADATA_VERSION, sizeof(float), 1, file); - // ----- class signature: to avoid confusion between different mdata.bin files produced by different classes (e.g. StackedVolume and BlockVolume) - const char* class_signature = typeid(StackedVolume).name(); - str_size = (uint16) strlen(class_signature) + 1; - fwrite(&str_size, sizeof(uint16), 1, file); - fwrite(class_signature, str_size, 1, file); - // ------------------------------------------------------------- - - str_size = (uint16) strlen(stacks_dir) + 1; - fwrite(&str_size, sizeof(uint16), 1, file); - fwrite(stacks_dir, str_size, 1, file); - fwrite(&reference_system.first, sizeof(vm::axis), 1, file); // GI_140501 - fwrite(&reference_system.second, sizeof(vm::axis), 1, file); // GI_140501 - fwrite(&reference_system.third, sizeof(vm::axis), 1, file); // GI_140501 - fwrite(&VXL_V, sizeof(float), 1, file); - fwrite(&VXL_H, sizeof(float), 1, file); - fwrite(&VXL_D, sizeof(float), 1, file); - fwrite(&ORG_V, sizeof(float), 1, file); - fwrite(&ORG_H, sizeof(float), 1, file); - fwrite(&ORG_D, sizeof(float), 1, file); - fwrite(&MEC_V, sizeof(float), 1, file); - fwrite(&MEC_H, sizeof(float), 1, file); - fwrite(&N_ROWS, sizeof(uint16), 1, file); - fwrite(&N_COLS, sizeof(uint16), 1, file); - - // 2014-09-02. Alessandro. @FIXED as 'N_SLICES' changed from 'uint16' to 'int' type. See vmVirtualVolume.h. - fwrite(&N_SLICES, sizeof(int), 1, file); - - for(i = 0; i < N_ROWS; i++) - for(j = 0; j < N_COLS; j++) - STACKS[i][j]->binarizeInto(file); - - fclose(file); -} - -void StackedVolume::loadBinaryMetadata(char *metadata_filepath) throw (iom::exception) -{ - #if VM_VERBOSE > 3 - printf("\t\t\t\tin StackedVolume::loadBinaryMetadata(char *metadata_filepath = %s)\n", metadata_filepath); - #endif - - //LOCAL VARIABLES - uint16 str_size; - char *temp; // GI_140425 - bool regen = false; - FILE *file; - int i,j; - size_t fread_return_val; - char buffer[VM_STATIC_STRINGS_SIZE]; - float tmp=0; - - // open file - if(!(file = fopen(metadata_filepath, "rb"))) - throw iom::exception("in StackedVolume::loadBinaryMetadata(...): unable to load binary metadata file"); - - - // 2014-09-03. Alessandro. @FIXED: added unified header to retrieve module's signature, metadata file version, and class name - // ----- module's signature: to avoid confusion between different modules (e.g. volumemanager and imagemanager) - if( fread(&str_size, sizeof(uint16), 1, file) != 1) - { - fclose(file); - throw iom::exception("in StackedVolume::loadBinaryMetadata(...) error while reading binary metadata file"); - } - if( fread(buffer, str_size, 1, file) != 1) - { - fclose(file); - throw iom::exception("in StackedVolume::loadBinaryMetadata(...) error while reading binary metadata file"); - } - if(vm::MODULE_ID.compare(buffer) != 0) - { - fclose(file); - throw iom::exception(vm::strprintf("in StackedVolume::loadBinaryMetadata(). Wrong module's signature: expected \"%s\", found \"%s\"." - "Possible obsolete mdata.bin file. Please delete it and try again.", vm::MODULE_ID.c_str(), buffer).c_str()); - } - // ----- metadata file version: to avoid misinterpretation of mdata.bin bytes when its structure is changed - if( fread(&tmp, sizeof(float), 1, file) != 1) - { - fclose(file); - throw iom::exception("in StackedVolume::loadBinaryMetadata(...) error while reading binary metadata file"); - } - if(vm::BINARY_METADATA_VERSION != tmp) - { - fclose(file); - throw iom::exception(vm::strprintf("in StackedVolume::loadBinaryMetadata(). Binary metadata file version (%.1f) is out-of-date (required: %.1f): please delete the mdata.bin file and try again", tmp, vm::BINARY_METADATA_VERSION).c_str()); - } - // ----- class signature: to avoid confusion between different mdata.bin files produced by different classes (e.g. StackedVolume and BlockVolume) - if( fread(&str_size, sizeof(uint16), 1, file) != 1) - { - fclose(file); - throw iom::exception("in StackedVolume::loadBinaryMetadata(...) error while reading binary metadata file"); - } - if( fread(buffer, str_size, 1, file) != 1) - { - fclose(file); - throw iom::exception("in StackedVolume::loadBinaryMetadata(...) error while reading binary metadata file"); - } - if(strcmp(buffer, typeid(StackedVolume).name()) != 0) - { - fclose(file); - throw iom::exception(vm::strprintf("in StackedVolume::loadBinaryMetadata(). Wrong class signature: expected \"%s\", found \"%s\".", typeid(StackedVolume).name(), buffer).c_str()); - } - // ------------------------------------------------------------- - - - fread_return_val = fread(&str_size, sizeof(uint16), 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in StackedVolume::loadBinaryMetadata(...) error while reading binary metadata file"); - } - // GI_140425 a check has been introduced to avoid that an out-of-date mdata.bin contains a wrong rood directory - temp = new char[str_size]; - fread_return_val = fread(temp, str_size, 1, file); - if(fread_return_val != 1) { - delete []temp; - fclose(file); - throw iom::exception("in StackedVolume::loadBinaryMetadata(...) error while reading binary metadata file"); - } - if ( !strcmp(temp,stacks_dir) ) // the two strings are equal - delete []temp; - else { // GI_140626: allow moving mdata.bin to other machine - delete []temp; - regen = true; - //fclose(file); - //throw iom::iom::exception("in StackedVolume::loadBinaryMetadata(...): binary metadata file is out-of-date"); - #if VM_VERBOSE > 3 - printf("\t\t\t\tin StackedVolume::loadBinaryMetadata(...): binary metadata file is out-of-date and it has been regenerated\n"); - #endif - } - - // GI_140501 - fread_return_val = fread(&reference_system.first, sizeof(vm::axis), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw iom::exception("in StackedVolume::unBinarizeFrom(...): error while reading binary metadata file"); - } - - // GI_140501 - fread_return_val = fread(&reference_system.second, sizeof(vm::axis), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw iom::exception("in StackedVolume::unBinarizeFrom(...): error while reading binary metadata file"); - } - - // GI_140501 - fread_return_val = fread(&reference_system.third, sizeof(vm::axis), 1, file); - if(fread_return_val != 1) - { - fclose(file); - throw iom::exception("in StackedVolume::unBinarizeFrom(...): error while reading binary metadata file"); - } - - fread_return_val = fread(&VXL_V, sizeof(float), 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in StackedVolume::loadBinaryMetadata(...) error while reading binary metadata file"); - } - fread_return_val = fread(&VXL_H, sizeof(float), 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in StackedVolume::loadBinaryMetadata(...) error while reading binary metadata file"); - } - fread_return_val = fread(&VXL_D, sizeof(float), 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in StackedVolume::loadBinaryMetadata(...) error while reading binary metadata file"); - } - fread_return_val = fread(&ORG_V, sizeof(float), 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in StackedVolume::loadBinaryMetadata(...) error while reading binary metadata file"); - } - fread_return_val = fread(&ORG_H, sizeof(float), 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in StackedVolume::loadBinaryMetadata(...) error while reading binary metadata file"); - } - fread_return_val = fread(&ORG_D, sizeof(float), 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in StackedVolume::loadBinaryMetadata(...) error while reading binary metadata file"); - } - fread_return_val = fread(&MEC_V, sizeof(float), 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in StackedVolume::loadBinaryMetadata(...) error while reading binary metadata file"); - } - fread_return_val = fread(&MEC_H, sizeof(float), 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in StackedVolume::loadBinaryMetadata(...) error while reading binary metadata file"); - } - fread_return_val = fread(&N_ROWS, sizeof(uint16), 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in StackedVolume::loadBinaryMetadata(...) error while reading binary metadata file"); - } - fread_return_val = fread(&N_COLS, sizeof(uint16), 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in StackedVolume::loadBinaryMetadata(...) error while reading binary metadata file"); - } - - // 2014-09-02. Alessandro. @FIXED as 'N_SLICES' changed from 'uint16' to 'int' type. See vmVirtualVolume.h. - fread_return_val = fread(&N_SLICES, sizeof(int), 1, file); - if(fread_return_val != 1) { - fclose(file); - throw iom::exception("in StackedVolume::loadBinaryMetadata(...) error while reading binary metadata file"); - } - - STACKS = new Stack **[N_ROWS]; - for(i = 0; i < N_ROWS; i++) - { - STACKS[i] = new Stack *[N_COLS]; - for(j = 0; j < N_COLS; j++) - STACKS[i][j] = new Stack(this, i, j, file); - } - - fclose(file); - - if ( regen ) { // GI_140626: directory name is changed, mdata.bin must be regenerated - saveBinaryMetadata(metadata_filepath); - } -} - -//rotate stacks matrix around D vm::axis (accepted values are theta=0,90,180,270) -void StackedVolume::rotate(int theta) -{ - #if VM_VERBOSE > 3 - printf("\t\t\t\tin StackedVolume::rotate(theta = %d)\n", theta); - #endif - - Stack*** new_STACK_2D_ARRAY = NULL; - int new_N_ROWS=0, new_N_COLS=0; - - switch(theta) - { - case(0): break; - - case(90): - { - new_N_COLS = N_ROWS; - new_N_ROWS = N_COLS; - - //allocating new_STACK_2D_ARRAY - new_STACK_2D_ARRAY = new Stack**[new_N_ROWS]; - for(int i=0; isetROW_INDEX(i); - new_STACK_2D_ARRAY[i][j]->setCOL_INDEX(j); - } - break; - } - case(180): - { - new_N_COLS=N_COLS; - new_N_ROWS=N_ROWS; - - //allocating new_STACK_2D_ARRAY - new_STACK_2D_ARRAY = new Stack**[new_N_ROWS]; - for(int i=0; isetROW_INDEX(i); - new_STACK_2D_ARRAY[i][j]->setCOL_INDEX(j); - } - break; - } - case(270): - { - new_N_COLS=N_ROWS; - new_N_ROWS=N_COLS; - - //allocating new_STACK_2D_ARRAY - new_STACK_2D_ARRAY = new Stack**[new_N_ROWS]; - for(int i=0; isetROW_INDEX(i); - new_STACK_2D_ARRAY[i][j]->setCOL_INDEX(j); - } - break; - } - } - - //deallocating current STACK_2DARRAY object - for(int row=0; row 3 - printf("\t\t\t\tin StackedVolume::mirror(mrr_axis = %d)\n", mrr_axis); - #endif - - if(mrr_axis!= 1 && mrr_axis != 2) - { - char msg[1000]; - sprintf(msg,"in StackedVolume::mirror(vm::axis mrr_axis=%d): unsupported vm::axis mirroring", mrr_axis); - throw iom::exception(msg); - } - - Stack*** new_STACK_2D_ARRAY; - - switch(mrr_axis) - { - case(1): - { - //allocating new_STACK_2D_ARRAY - new_STACK_2D_ARRAY = new Stack**[N_ROWS]; - for(int i=0; isetROW_INDEX(i); - new_STACK_2D_ARRAY[i][j]->setCOL_INDEX(j); - } - break; - } - case(2): - { - //allocating new_STACK_2D_ARRAY - new_STACK_2D_ARRAY = new Stack**[N_ROWS]; - for(int i=0; isetROW_INDEX(i); - new_STACK_2D_ARRAY[i][j]->setCOL_INDEX(j); - } - break; - } - default: break; - } - - //deallocating current STACK_2DARRAY object - for(int row=0; rowgetDEPTH(); - - for ( int i=0; igetDEPTH() ) { - if ( ok ) { // first anomaly: open and initialize the errlog file - if ( errlogFileName ) { - if ( (errlogf = fopen(errlogFileName,"w")) == 0 ) { - char errMsg[2000]; - sprintf(errMsg,"in StackedVolume::check(errlogFileName = \"%s\") : unable to open log file", errlogFileName); - throw iom::exception(errMsg); - } - - fprintf(errlogf,"errlog file of volume (BlockVolume): \"%s\"\n",stacks_dir); - fprintf(errlogf,"\tdepth: %d\n",depth); - } - - ok = false; - } - if ( errlogFileName ) - fprintf(errlogf,"\trow=%d, col=%d, depth=%d\n",i,j,STACKS[i][j]->getDEPTH()); - } - } - } - - if ( errlogFileName && !ok ) // there are anomalies: close the errlog file - fclose(errlogf); - - return ok; -} - - -//counts the total number of displacements and the number of displacements per stack -void StackedVolume::countDisplacements(int& total, float& per_stack_pair) -{ - /* PRECONDITIONS: none */ - total = 0; - per_stack_pair = 0.0f; - for(int i=0; i(STACKS[i][j]->getEAST().size()); - total+= static_cast(STACKS[i][j]->getSOUTH().size()); - per_stack_pair += static_cast(STACKS[i][j]->getEAST().size()); - per_stack_pair += static_cast(STACKS[i][j]->getSOUTH().size()); - } - per_stack_pair /= 2*(N_ROWS*N_COLS) - N_ROWS - N_COLS; -} - -//counts the number of single-direction displacements having a reliability measure above the given threshold -void StackedVolume::countReliableSingleDirectionDisplacements(float threshold, int& total, int& reliable) -{ - /* PRECONDITIONS: - * - for each pair of adjacent stacks one and only one displacement exists (CHECKED) */ - - total = reliable = 0; - for(int i=0; igetEAST().size()==1) - { - total+=3; - reliable += STACKS[i][j]->getEAST()[0]->getReliability(dir_vertical) >= threshold; - reliable += STACKS[i][j]->getEAST()[0]->getReliability(dir_horizontal) >= threshold; - reliable += STACKS[i][j]->getEAST()[0]->getReliability(dir_depth) >= threshold; - } - if(i != (N_ROWS-1) && STACKS[i][j]->getSOUTH().size()==1) - { - total+=3; - reliable += STACKS[i][j]->getSOUTH()[0]->getReliability(dir_vertical) >= threshold; - reliable += STACKS[i][j]->getSOUTH()[0]->getReliability(dir_horizontal) >= threshold; - reliable += STACKS[i][j]->getSOUTH()[0]->getReliability(dir_depth) >= threshold; - } - } -} - -//counts the number of stitchable stacks given the reliability threshold -int StackedVolume::countStitchableStacks(float threshold) -{ - /* PRECONDITIONS: - * - for each pair of adjacent stacks one and only one displacement exists (CHECKED) */ - - //stitchable stacks are stacks that have at least one reliable single-direction displacement - int stitchables = 0; - bool stitchable; - for(int i=0; igetNORTH().size()==1) - for(int k=0; k<3; k++) - stitchable = stitchable || (stk->getNORTH()[0]->getReliability(direction(k)) >= threshold); - if(j!= (N_COLS -1) && STACKS[i][j]->getEAST().size()==1) - for(int k=0; k<3; k++) - stitchable = stitchable || (stk->getEAST()[0]->getReliability(direction(k)) >= threshold); - if(i!= (N_ROWS -1) && STACKS[i][j]->getSOUTH().size()==1) - for(int k=0; k<3; k++) - stitchable = stitchable || (stk->getSOUTH()[0]->getReliability(direction(k)) >= threshold); - if(j!= 0 && STACKS[i][j]->getWEST().size()==1) - for(int k=0; k<3; k++) - stitchable = stitchable || (stk->getWEST()[0]->getReliability(direction(k)) >= threshold); - stitchables += stitchable; - } - return stitchables; -} - -// print mdata.bin content to stdout -void StackedVolume::dumpMData(const char* volumePath) throw (iom::exception) -{ - char mdata_filepath[VM_STATIC_STRINGS_SIZE]; - sprintf(mdata_filepath, "%s/%s", volumePath, vm::BINARY_METADATA_FILENAME.c_str()); - uint16 str_size = 0; - char buffer[VM_STATIC_STRINGS_SIZE]; - float tmp = 0; - - // file open - FILE* f = fopen(mdata_filepath, "rb"); - if(!f) - throw iom::exception(iom::strprintf("in StackedVolume::dumpMData(): cannot open metadata binary file at \"%s\"", mdata_filepath).c_str()); - - // field - if( fread(&str_size, sizeof(uint16), 1, f) != 1) - { - fclose(f); - throw iom::exception("in StackedVolume::dumpMData(...): cannot read field "); - } - printf(" = %d\n", str_size); - - - - // field - if( fread(buffer, str_size, 1, f) != 1) - { - fclose(f); - throw iom::exception("in StackedVolume::dumpMData(...): cannot read field "); - } - if(vm::MODULE_ID.compare(buffer) != 0) - { - fclose(f); - throw iom::exception(vm::strprintf("in StackedVolume::dumpMData(). Wrong module's signature: expected \"%s\", found \"%s\"." - "Possible obsolete mdata.bin file. Please delete it and try again.", vm::MODULE_ID.c_str(), buffer).c_str()); - } - printf(" = %s\n", buffer); - - // field - if( fread(&tmp, sizeof(float), 1, f) != 1) - { - fclose(f); - throw iom::exception("in StackedVolume::dumpMData(...): cannot read field "); - } - if(vm::BINARY_METADATA_VERSION != tmp) - { - fclose(f); - throw iom::exception(vm::strprintf("in StackedVolume::dumpMData(). Binary metadata file version (%.1f) is out-of-date (required: %.1f): please delete the mdata.bin file and try again", tmp, vm::BINARY_METADATA_VERSION).c_str()); - } - printf(" = %.1f\n", tmp); - - // field - if( fread(&str_size, sizeof(uint16), 1, f) != 1) - { - fclose(f); - throw iom::exception("in StackedVolume::dumpMData(...): cannot read field "); - } - printf(" = %d\n", str_size); - - // field - if( fread(buffer, str_size, 1, f) != 1) - { - fclose(f); - throw iom::exception("in StackedVolume::dumpMData(...): cannot read field "); - } - if(strcmp(buffer, typeid(StackedVolume).name()) != 0) - { - fclose(f); - throw iom::exception(vm::strprintf("in StackedVolume::dumpMData(). Wrong class signature: expected \"%s\", found \"%s\".", typeid(StackedVolume).name(), buffer).c_str()); - } - printf(" = %s\n", buffer); - // ------------------------------------------------------------- - - // field - if(fread(&str_size, sizeof(uint16), 1, f) != 1) - { - fclose(f); - throw iom::exception("in StackedVolume::dumpMData(...): cannot read field "); - } - printf(" = %d\n", str_size); - - // - if(fread(buffer, str_size, 1, f) != 1) - { - fclose(f); - throw iom::exception("in StackedVolume::dumpMData(...): cannot read field "); - } - printf(" = %s\n", buffer); - - - // - vm::ref_sys reference_system; - if( fread(&reference_system.first, sizeof(vm::axis), 1, f) != 1) - { - fclose(f); - throw iom::exception("in StackedVolume::dumpMData(...): cannot read field "); - } - printf(" = %d\n", reference_system.first); - - // - if( fread(&reference_system.second, sizeof(vm::axis), 1, f) != 1) - { - fclose(f); - throw iom::exception("in StackedVolume::dumpMData(...): cannot read field "); - } - printf(" = %d\n", reference_system.second); - - // - if( fread(&reference_system.third, sizeof(vm::axis), 1, f) != 1) - { - fclose(f); - throw iom::exception("in StackedVolume::dumpMData(...): cannot read field "); - } - printf(" = %d\n", reference_system.third); - - - // - float fn = 0.0f; - if(fread(&fn, sizeof(float), 1, f) != 1) - { - fclose(f); - throw iom::exception("in StackedVolume::dumpMData(...): cannot read field "); - } - printf(" = %.4f\n", fn); - - - // - if(fread(&fn, sizeof(float), 1, f) != 1) - { - fclose(f); - throw iom::exception("in StackedVolume::dumpMData(...): cannot read field "); - } - printf(" = %.4f\n", fn); - - - // - if(fread(&fn, sizeof(float), 1, f) != 1) - { - fclose(f); - throw iom::exception("in StackedVolume::dumpMData(...): cannot read field "); - } - printf(" = %.4f\n", fn); - - - // - if(fread(&fn, sizeof(float), 1, f) != 1) - { - fclose(f); - throw iom::exception("in StackedVolume::dumpMData(...): cannot read field "); - } - printf(" = %.6f\n", fn); - - - // - if(fread(&fn, sizeof(float), 1, f) != 1) - { - fclose(f); - throw iom::exception("in StackedVolume::dumpMData(...): cannot read field "); - } - printf(" = %.6f\n", fn); - - - // - if(fread(&fn, sizeof(float), 1, f) != 1) - { - fclose(f); - throw iom::exception("in StackedVolume::dumpMData(...): cannot read field "); - } - printf(" = %.6f\n", fn); - - - // - if(fread(&fn, sizeof(float), 1, f) != 1) - { - fclose(f); - throw iom::exception("in StackedVolume::dumpMData(...): cannot read field "); - } - printf(" = %.6f\n", fn); - - - // - if(fread(&fn, sizeof(float), 1, f) != 1) - { - fclose(f); - throw iom::exception("in StackedVolume::dumpMData(...): cannot read field "); - } - printf(" = %.6f\n", fn); - - - // - uint16 nrows = 0; - if(fread(&nrows, sizeof(uint16), 1, f) != 1) - { - fclose(f); - throw iom::exception("in StackedVolume::dumpMData(...): cannot read field "); - } - printf(" = %d\n", nrows); - - - // - uint16 ncols = 0; - if(fread(&ncols, sizeof(uint16), 1, f) != 1) - { - fclose(f); - throw iom::exception("in StackedVolume::dumpMData(...): cannot read field "); - } - printf(" = %d\n", ncols); - - - // - int nslices = 0; - if(fread(&nslices, sizeof(int), 1, f) != 1) - { - fclose(f); - throw iom::exception("in StackedVolume::dumpMData(...): cannot read field "); - } - printf(" = %d\n", nslices); - - - // read stack fields - printf("\n"); - for(int i = 0; i < nrows; i++) - { - for(int j = 0; j < ncols; j++) - { - printf("\t----begin Stack (%d,%d)\n", i, j); - - // - int intn = 0; - if(fread(&intn, sizeof(int), 1, f) != 1) - { - fclose(f); - throw iom::exception("in StackedVolume::dumpMData(...): cannot read field "); - } - printf("\t = %d\n", intn); - - // - if(fread(&intn, sizeof(int), 1, f) != 1) - { - fclose(f); - throw iom::exception("in StackedVolume::dumpMData(...): cannot read field "); - } - printf("\t = %d\n", intn); - - // - int depth = 0; - if(fread(&depth, sizeof(int), 1, f) != 1) - { - fclose(f); - throw iom::exception("in StackedVolume::dumpMData(...): cannot read field "); - } - printf("\t = %d\n", depth); - - // - if(fread(&intn, sizeof(int), 1, f) != 1) - { - fclose(f); - throw iom::exception("in StackedVolume::dumpMData(...): cannot read field "); - } - printf("\t = %d\n", intn); - - // - if(fread(&intn, sizeof(int), 1, f) != 1) - { - fclose(f); - throw iom::exception("in StackedVolume::dumpMData(...): cannot read field "); - } - printf("\t = %d\n", intn); - - // - if(fread(&intn, sizeof(int), 1, f) != 1) - { - fclose(f); - throw iom::exception("in StackedVolume::dumpMData(...): cannot read field "); - } - printf("\t = %d\n", intn); - - - // field - if(fread(&str_size, sizeof(uint16), 1, f) != 1) - { - fclose(f); - throw iom::exception("in StackedVolume::dumpMData(...): cannot read field "); - } - printf("\t = %d\n", str_size); - - // - if(fread(buffer, str_size, 1, f) != 1) - { - fclose(f); - throw iom::exception("in StackedVolume::dumpMData(...): cannot read field "); - } - printf("\t = %s\n\n", buffer); - - - for(int k = 0; k < depth; k++) - { - printf("\t\tSlice %d/%d\n", k+1, depth); - - // field - if(fread(&str_size, sizeof(uint16), 1, f) != 1) - { - fclose(f); - throw iom::exception("in StackedVolume::dumpMData(...): cannot read field "); - } - printf("\t\t = %d\n", str_size); - - // - if(str_size > 0) - { - if(fread(buffer, str_size, 1, f) != 1) - { - fclose(f); - throw iom::exception("in StackedVolume::dumpMData(...): cannot read field "); - } - printf("\t\t = %s\n", buffer); - } - else - printf("\t\t = \n"); - - printf("\n"); - } - - - printf("\t----end Stack (%d,%d)\n\n", i, j); - } - } - - fclose(f); - -} - -// 2014-09-05. Alessandro. @ADDED 'check_stacks_same_dims()' method to check that stacks have same width and height -void StackedVolume::normalize_stacks_attributes() throw (iom::exception) -{ - std::set heights, widths; - for(int i=0; iisEmpty()) - continue; - - heights.insert(STACKS[i][j]->HEIGHT); - widths.insert(STACKS[i][j]->WIDTH); - } - - // make the check - if(heights.size() != 1 || widths.size() != 1) - throw iom::exception("in StackedVolume::normalize_stacks_attributes(...): Stacks have unequal X,Y dimensions. This feature is not supported yet."); - - // make empty stacks having the same width and height of other stacks - for(int i=0; iisEmpty()) - { - STACKS[i][j]->HEIGHT = *(heights.begin()); - STACKS[i][j]->WIDTH = *(widths.begin()); - } -} diff --git a/v3d_main/terafly/src/core/volumemanager/vmStackedVolume.h b/v3d_main/terafly/src/core/volumemanager/vmStackedVolume.h deleted file mode 100644 index 9ad94d7b13..0000000000 --- a/v3d_main/terafly/src/core/volumemanager/vmStackedVolume.h +++ /dev/null @@ -1,135 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* -* Bria, A., Iannello, G., "TeraStitcher - A Tool for Fast 3D Automatic Stitching of Teravoxel-sized Microscopy Images", (2012) BMC Bioinformatics, 13 (1), art. no. 316. -* -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -* 2015-06-12. Giulio @ADDED 'check' method to check completeness and coherence of a volume -* 2015-02-26. Giulio. @ADDED initChannels private method to initialize fields DIM_C and BYTESxCHAN -* 2014-09-20. Alessandro. @ADDED overwrite_mdata flag to the XML-based constructor. -* 2014-09-10. Alessandro. @ADDED plugin creation/registration functions to make 'StackedVolume' a volume format plugin. -* 2014-09-05. Alessandro. @ADDED 'normalize_stacks_attributes()' method to normalize stacks attributes (width, height, etc.) -*/ - -#ifndef _VM_STACKED_VOLUME_H -#define _VM_STACKED_VOLUME_H - -#include -#include "volumemanager.config.h" -#include -#include "iomanager.config.h" -#include "vmVirtualVolume.h" -#include -#include -#include -#include -#include - - -class vm::StackedVolume : public vm::VirtualVolume -{ - private: - - // 2014-09-10. Alessandro. @ADDED plugin creation/registration functions to make 'StackedVolume' a volume format plugin. - static const std::string creator_id1, creator_id2; - static vm::VirtualVolume* createFromXML(const char* xml_path, bool ow_mdata) { return new StackedVolume(xml_path, ow_mdata); } - static vm::VirtualVolume* createFromData(const char* data_path, vm::ref_sys ref, float vxl1, float vxl2, float vxl3, bool ow_mdata) { - return new StackedVolume(data_path, ref, vxl1, vxl2, vxl3, ow_mdata); - } - - - //******OBJECT ATTRIBUTES****** - vm::Stack ***STACKS; //2-D array of - - //initialization methods - void init() throw (iom::exception); - void initChannels() throw (iom::exception); - void applyReferenceSystem(vm::ref_sys reference_system, float VXL_1, float VXL_2, float VXL_3) throw (iom::exception); - - //binary metadata load/save methods - void saveBinaryMetadata(char *metadata_filepath) throw (iom::exception); - void loadBinaryMetadata(char *metadata_filepath) throw (iom::exception); - - //rotates stacks matrix around D vm::axis (accepted values are theta=0,90,180,270) - void rotate(int theta); - - //mirrors stacks matrix along mrr_axis (accepted values are mrr_axis=1,2,3) - void mirror(vm::axis mrr_axis) throw (iom::exception); - - // 2014-09-05. Alessandro. @ADDED 'normalize_stacks_attributes()' method to normalize stacks attributes (width, height, etc.) - void normalize_stacks_attributes() throw (iom::exception); - - public: - - // 2014-09-10. Alessandro. @ADDED plugin creation/registration functions to make 'StackedVolume' a volume format plugin. - static const std::string id; - - //CONSTRUCTORS-DECONSTRUCTOR - StackedVolume() : vm::VirtualVolume(){} - StackedVolume(const char* _stacks_dir, vm::ref_sys reference_system, float VXL_1=0, float VXL_2=0, float VXL_3=0, bool overwrite_mdata=false) throw (iom::exception); - StackedVolume(const char *xml_filepath, bool overwrite_mdata=false) throw (iom::exception); - ~StackedVolume(); - - // ******GET METHODS****** - int getStacksHeight(); - int getStacksWidth(); - vm::VirtualStack*** getSTACKS(); - - //loads/saves metadata from/in the given xml filename - void loadXML(const char *xml_filename) throw (iom::exception); - void initFromXML(const char *xml_filename) throw (iom::exception); - void saveXML(const char *xml_filename=0, const char *xml_filepath=0) throw (iom::exception); - - - /********************************************************************************** - * UTILITY methods - ***********************************************************************************/ - - //check if volume is complete and coherent; return true if the volume is ok, false otherwise - //if a file name is passed and thevolume is not ok an error log file is generated - bool check(const char *errlogFileName = 0) throw (iom::exception); - - //counts the total number of displacements and the number of displacements per pair of adjacent stacks - void countDisplacements(int& total, float& per_stack_pair); - - //counts the number of single-direction displacements having a reliability measure above the given threshold - void countReliableSingleDirectionDisplacements(float threshold, int& total, int& reliable); - - //counts the number of stitchable stacks given the reliability threshold - int countStitchableStacks(float threshold); - - // print mdata.bin content to stdout - static void dumpMData(const char* volumePath) throw (iom::exception); -}; - -namespace{ - const vm::StackedVolume* objectStackedVolume = new vm::StackedVolume(); -} - - -#endif /* STACKED_VOLUME_H */ - diff --git a/v3d_main/terafly/src/core/volumemanager/vmVirtualStack.cpp b/v3d_main/terafly/src/core/volumemanager/vmVirtualStack.cpp deleted file mode 100644 index 3732a5d2d6..0000000000 --- a/v3d_main/terafly/src/core/volumemanager/vmVirtualStack.cpp +++ /dev/null @@ -1,119 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* -* Bria, A., Iannello, G., "TeraStitcher - A Tool for Fast 3D Automatic Stitching of Teravoxel-sized Microscopy Images", (2012) BMC Bioinformatics, 13 (1), art. no. 316. -* -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -* 2015-09-18. Alessandro. @FIXED bug which caused image regex to be ignored when scanning the folder tree. -* 2015-02-28. Giulio. @ADDED initialization of fields N_CHANS and N_BYTESxCHAN -* 2015-01-17. Alessandro. @ADDED support for all-in-one-folder data (import from xml only). -* 2014-09-10. Alessandro. @ADDED 'isEmpty(z0,z1)' method. -* 2014-08-30. Alessandro. @REMOVED 'show()' method (obsolete). -* 2014-08-30. Alessandro. @ADDED 'VirtualStack()' default constructor definition with member initialization. -* 2014-08-29. Alessandro. @ADDED 'isComplete()' implementation. -* 2014-08-25. Alessandro. @ADDED SPARSE_DATA parameter definition. Default is false. -*/ - -#include "vmVirtualStack.h" - -using namespace vm; - -VirtualStack::VirtualStack() -{ - FILENAMES = 0; - HEIGHT = WIDTH = DEPTH = -1; - ROW_INDEX = COL_INDEX = -1; - N_CHANS = 0; - N_BYTESxCHAN = 0; - DIR_NAME = 0; - stitchable = false; - ABS_V = ABS_H = ABS_D = -1; - STACKED_IMAGE = 0; - - // @FIXED by Alessandro on 2015-09-18. By default, assign to img_regex the value of the global variable vm::IMG_FILTER_REGEX. - img_regex = vm::IMG_FILTER_REGEX; -} - -// return true if the given range [z0,z1] does not contain missing slices/blocks -bool VirtualStack::isComplete(int z0, int z1) -{ - // precondition 1 (unchecked) - // z_ranges should contain consecutive but not contiguous intervals [a_1,b_1), [a_2,b_2), ... such that a_n > b_(n-1) - - // precondition 2 and 3: nonempty tile, and valid range. - if(isEmpty() || z0 > z1) - return false; - - // search for one z-range that contains [z0,z1] - bool is_contained = false; - for(int k=0; k= z_ranges[k].start && z1 < z_ranges[k].end; - - return is_contained; -} - -// return true if the given range [z0,z1] does not contain any slice/block -bool VirtualStack::isEmpty(int z0, int z1) -{ - // precondition 1 (unchecked) - // z_ranges should contain consecutive but not contiguous intervals [a_1,b_1), [a_2,b_2), ... such that a_n > b_(n-1) - - // precondition 2 and 3: nonempty tile, and valid range. - if(isEmpty() || z0 > z1) - return true; - - // search for one z-range that intersects with [z0,z1] - bool intersects = false; - for(int k=0; k= z_ranges[k].start && z_ranges[k].end > z0; - - return !intersects; -} - -// read img_regex from xml stack node -std::string VirtualStack::readImgRegex(TiXmlElement *stack_node) throw (iom::exception) -{ - // check for valid stack node - if(!stack_node) - throw iom::exception("not an xml node", __iom__current__function__); - if( strcmp(stack_node->ToElement()->Value(), "Stack") != 0) - throw iom::exception(iom::strprintf("invalid xml node name: expected \"Stack\", found \"%s\"", stack_node->ToElement()->Value()), __iom__current__function__); - - const char* img_regex_read = stack_node->Attribute("IMG_REGEX"); - if( img_regex_read ) // field is present - img_regex = img_regex_read; // store the regex read from XML - else - img_regex = vm::IMG_FILTER_REGEX; // store the global regex read from command line - - return img_regex; -} - -// write img_regex to the xml stack node -void VirtualStack::writeImgRegex(TiXmlElement *stack_node) throw (iom::exception) -{ - stack_node->SetAttribute("IMG_REGEX",img_regex.c_str()); -} diff --git a/v3d_main/terafly/src/core/volumemanager/vmVirtualStack.h b/v3d_main/terafly/src/core/volumemanager/vmVirtualStack.h deleted file mode 100644 index e80fd2c761..0000000000 --- a/v3d_main/terafly/src/core/volumemanager/vmVirtualStack.h +++ /dev/null @@ -1,197 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* -* Bria, A., Iannello, G., "TeraStitcher - A Tool for Fast 3D Automatic Stitching of Teravoxel-sized Microscopy Images", (2012) BMC Bioinformatics, 13 (1), art. no. 316. -* -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -* 2015-02-28. Giulio. @ADDED fields N_CHANS and BYTESxCHAN -* 2015-01-17. Alessandro. @ADDED support for all-in-one-folder data (import from xml only). -* 2014-09-10. Alessandro. @ADDED 'isEmpty(z0,z1)' method. -* 2014-09-05. Alessandro. @ADDED 'z_end' parameter in 'loadXML()' method to support sparse data feature. -* 2014-09-03. Alessandro. @ADDED 'isEmpty()' and 'isSparse()' get methods. -* 2014-09-01. Alessandro. @ADDED 'z_ranges' attribute to manage sparse data along Z. -* 2014-08-30. Alessandro. @REMOVED 'show()' method (obsolete). -* 2014-08-30. Alessandro. @MOVED 'VirtualStack()' default constructor to .cpp source file. -* 2014-08-29. Alessandro. @ADDED 'isComplete()' concrete virtual method. -* 2014-08-25. Alessandro. @ADDED missing 'throw (iom::iom::exception)' statement in the 'loadImageStack()' method's signature. -*/ - -#ifndef _VM_VIRTUAL_STACK_H -#define _VM_VIRTUAL_STACK_H - -#include -#include "iomanager.config.h" -#include "tinyxml.h" -#include "volumemanager.config.h" -#include "../stitcher/Displacement.h" - -//class Displacement; - -class vm::VirtualStack -{ - protected: - - char* DIR_NAME; //string containing current stack directory - char** FILENAMES; //1D dynamic array of pointers to images filenames - int HEIGHT, WIDTH, DEPTH; //VHD (Vertical, Horizontal, Depth) dimensions of current stack - int ROW_INDEX, COL_INDEX; //row and col index relative to stack matrix - int N_CHANS; //number of channels - int N_BYTESxCHAN; //number of bytes per channel - bool stitchable; //true if current Stack is stitchable with adjacent ones - int ABS_V, ABS_H, ABS_D; //absolute VHD voxel coordinates of current stack - iom::real_t* STACKED_IMAGE; //pointer to 1-D array of REAL_T that stores Stack image data - std::vector NORTH; //vector of displacements along D direction between this and northern Stack - std::vector EAST; //vector of displacements along D direction between this and eastern Stack - std::vector SOUTH; //vector of displacements along D direction between this and southern Stack - std::vector WEST; //vector of displacements along D direction between this and western Stack - - // 2014-09-01. Alessandro. @ADDED support for sparse data. - std::vector< vm::interval > z_ranges; //vector of Z-ranges containing valid data (each range is of type [start, end) ) - //*** WARNING ***: if vector is empty, the stack is assumed as empty - - // 2015-01-17. Alessandro. @ADDED support for all-in-one-folder data (import from xml only). - // Each stack can be associated with a regular expression to filter image filenames. - std::string img_regex; - virtual std::string readImgRegex(TiXmlElement *stack_node) throw (iom::exception); - virtual void writeImgRegex(TiXmlElement *stack_node) throw (iom::exception); - - public: - - VirtualStack(); - ~VirtualStack(void){} - - - //GET methods - char* getDIR_NAME() {return DIR_NAME;} - char** getFILENAMES() {return FILENAMES;} - int getROW_INDEX() {return ROW_INDEX;} - int getCOL_INDEX() {return COL_INDEX;} - int getHEIGHT() {return HEIGHT;}//Onofri: type changed - int getWIDTH() {return WIDTH;} //Onofri: type changed - int getDEPTH() {return DEPTH;} //Onofri: type changed - int getN_CHANS() {return N_CHANS;} - int getN_BYTESxCHAN() {return N_BYTESxCHAN;} - int getABS_V() {return ABS_V;} - int getABS_H() {return ABS_H;} - int getABS_D() {return ABS_D;} - int getABS(int direction) throw (iom::exception) - { - #if VM_VERBOSE > 4 - printf("........in Stack[%d,%d]::getABS(direction = %d)\n",ROW_INDEX, COL_INDEX, direction); - #endif - - if (direction == dir_vertical) - return getABS_V(); - else if(direction == dir_horizontal) - return getABS_H(); - else if(direction == dir_depth) - return getABS_D(); - else - throw iom::exception("in Stack::setABS(int _ABS, int direction): wrong direction inserted"); - } - - iom::real_t* getSTACKED_IMAGE() {return STACKED_IMAGE;} - virtual void *getCONTAINER() =0; - - std::vector& getNORTH(){return NORTH;} - std::vector& getEAST(){return EAST;} - std::vector& getSOUTH(){return SOUTH;} - std::vector& getWEST(){return WEST;} - - bool isStitchable(){return this->stitchable;} - - // 2014-09-03. Alessandro. @ADDED 'isEmpty()' and 'isSparse()' get methods - bool isEmpty(){return z_ranges.empty();} - bool isSparse(){return !isEmpty() && !isComplete(0, DEPTH-1);} - - Displacement* getDisplacement(VirtualStack* neighbour) throw (iom::exception) - { - #if VM_VERBOSE > 4 - printf("........in Stack[%d,%d]::getDisplacement(Stack* neighbour[%d,%d])\n",ROW_INDEX, COL_INDEX, neighbour->ROW_INDEX, neighbour->COL_INDEX); - #endif - - if(neighbour == NULL) - throw iom::exception("...in Stack::getDisplacement(Stack* neighbour = NULL): invalid neighbour stack"); - else if(neighbour->getROW_INDEX() == (ROW_INDEX -1) && neighbour->getCOL_INDEX() == COL_INDEX) - if(NORTH.size() == 1) return NORTH[0]; - else throw iom::exception("...in Stack::getDisplacement(Stack* neighbour): stack MUST contain one displacement only at NORTH"); - else if(neighbour->getROW_INDEX() == ROW_INDEX && neighbour->getCOL_INDEX() == COL_INDEX -1) - if(WEST.size() == 1) return WEST[0]; - else throw iom::exception("...in Stack::getDisplacement(Stack* neighbour): stack MUST contain one displacement only at WEST"); - else if(neighbour->getROW_INDEX() == ROW_INDEX +1 && neighbour->getCOL_INDEX() == COL_INDEX) - if(SOUTH.size() == 1) return SOUTH[0]; - else throw iom::exception("...in Stack::getDisplacement(Stack* neighbour): stack MUST contain one displacement only at SOUTH"); - else if(neighbour->getROW_INDEX() == ROW_INDEX && neighbour->getCOL_INDEX() == COL_INDEX +1) - if(EAST.size() == 1) return EAST[0]; - else throw iom::exception("...in Stack::getDisplacement(Stack* neighbour): stack MUST contain one displacement only at EAST"); - else - throw iom::exception("...in Stack::getDisplacement(Stack* neighbour): neighbour is not a neighbour!!!"); - } - - //SET methods - void setROW_INDEX(int _ROW_INDEX){ROW_INDEX = _ROW_INDEX;} - void setCOL_INDEX(int _COL_INDEX){COL_INDEX = _COL_INDEX;} - void setABS_V (int _ABS_V) {ABS_V = _ABS_V; } - void setABS_H (int _ABS_H) {ABS_H = _ABS_H; } - void setABS_D (int _ABS_D) {ABS_D = _ABS_D; } - void setABS (int _ABS, int direction) throw (iom::exception) - { - #if VM_VERBOSE > 4 - printf("........in Stack[%d,%d]::setABS(_ABS = %d, direction = %d)\n",ROW_INDEX, COL_INDEX, _ABS, direction); - #endif - - if (direction == dir_vertical) - setABS_V(_ABS); - else if(direction == dir_horizontal) - setABS_H(_ABS); - else if(direction == dir_depth) - setABS_D(_ABS); - else - throw iom::exception("in Stack::setABS(int _ABS, int direction): wrong direction inserted"); - } - void setStitchable(bool _stitchable){this->stitchable = _stitchable;} - - //LOAD and RELEASE methods - virtual iom::real_t* loadImageStack(int first_file=-1, int last_file=-1) throw (iom::exception) = 0; - virtual void releaseImageStack()= 0; - - // return true if the given range [z0,z1] does not contain missing slices/blocks - virtual bool isComplete(int z0, int z1); - - // return true if the given range [z0,z1] does not contain any slice/block - virtual bool isEmpty(int z0, int z1); - - //XML methods - virtual TiXmlElement* getXML()= 0; - virtual void loadXML( - TiXmlElement *stack_node, - int z_end) // 2014-09-05. Alessandro. @ADDED 'z_end' parameter to support sparse data feature - // Here 'z_end' identifies the range [0, z_end) that slices can span - throw (iom::exception)= 0; -}; - -#endif diff --git a/v3d_main/terafly/src/core/volumemanager/vmVirtualVolume.cpp b/v3d_main/terafly/src/core/volumemanager/vmVirtualVolume.cpp deleted file mode 100644 index 53031ac0bf..0000000000 --- a/v3d_main/terafly/src/core/volumemanager/vmVirtualVolume.cpp +++ /dev/null @@ -1,272 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -* 2015-02-26. Giulio. @ADDED dummy initialization of fields DIM_C and BYTESxCHAN in constructor -* 2014-09-10. Alessandro. @ADDED 'getVolumeFormat' method to be applied on xml file. -* 2014-09-01. Alessandro. @FIXED 'extractCoordinates()' method to deal with sparse tiles w/o causing crashes. -* 2014-09-01. Alessandro. @ADDED 'name2coordZ()' utility method to extract the z-coordinate substring from a given filename. -* 2014-08-30. Alessandro. @REMOVED 'extractPathFromFilePath()' method (obsolete). -* 2014-08-30. Alessandro. @REMOVED 'print()' method from abstract class and all concrete classes (obsolete). -*/ - -#include -#include "vmVirtualVolume.h" -#include "vmVirtualStack.h" -#ifdef _WIN32 -#include "dirent_win.h" -#else -#include -#endif -#include //fabs - - -using namespace std; -using namespace vm; - -float VirtualVolume::getORG_V() {return ORG_V;} -float VirtualVolume::getORG_H() {return ORG_H;} -float VirtualVolume::getORG_D() {return ORG_D;} -float VirtualVolume::getABS_V(int ABS_PIXEL_V) {return ORG_V * 1000 + ABS_PIXEL_V*this->getVXL_V();} //Alessandro - 23/03/2013: removed conversion from int to float -float VirtualVolume::getABS_H(int ABS_PIXEL_H) {return ORG_H * 1000 + ABS_PIXEL_H*this->getVXL_H();} //Alessandro - 23/03/2013: removed conversion from int to float -float VirtualVolume::getABS_D(int ABS_PIXEL_D) {return ORG_D * 1000 + ABS_PIXEL_D*this->getVXL_D();} //Alessandro - 23/03/2013: removed conversion from int to float -float VirtualVolume::getVXL_V() {return VXL_V;} -float VirtualVolume::getVXL_H() {return VXL_H;} -float VirtualVolume::getVXL_D() {return VXL_D;} -float VirtualVolume::getMEC_V() {return MEC_V;} -float VirtualVolume::getMEC_H() {return MEC_H;} -int VirtualVolume::getN_ROWS() {return this->N_ROWS;} -int VirtualVolume::getN_COLS() {return this->N_COLS;} -int VirtualVolume::getN_SLICES() {return this->N_SLICES;} -int VirtualVolume::getDIM_C() {return this->DIM_C;} -int VirtualVolume::getBYTESxCHAN() {return this->BYTESxCHAN;} -//char* VirtualVolume::getSTACKS_DIR() {return this->stacks_dir;} -int VirtualVolume::getOVERLAP_V() {return (int)(getStacksHeight() - MEC_V/VXL_V);} -int VirtualVolume::getOVERLAP_H() {return (int)(getStacksWidth() - MEC_H/VXL_H);} -int VirtualVolume::getDEFAULT_DISPLACEMENT_V() {return (int)(fabs(MEC_V/VXL_V));} -int VirtualVolume::getDEFAULT_DISPLACEMENT_H() {return (int)(fabs(MEC_H/VXL_H));} -int VirtualVolume::getDEFAULT_DISPLACEMENT_D() {return 0;} - -void VirtualVolume::init() throw (iom::exception) -{ - stacks_dir = 0; - - reference_system.first = reference_system.second = reference_system.third = axis_invalid; - - VXL_V = 0; - VXL_H = 0; - VXL_D = 0; - - ORG_V = ORG_H = ORG_D = (float) 0.0; - MEC_V = MEC_H = 0; - - N_ROWS = N_COLS = 0; - N_SLICES = 0; - - DIM_C = 0; - BYTESxCHAN = 0; -} - -//returns true if file exists at the given filepath -bool VirtualVolume::fileExists(const char *filepath) throw (iom::exception) -{ - //LOCAL VARIABLES - string file_path_string =filepath; - string file_name; - string dir_path; - bool file_exists = false; - DIR* directory; - dirent* dir_entry; - - //extracting dir_path and file_name from file_path - char * tmp; - tmp = strtok (&file_path_string[0],"/\\"); - while (tmp != NULL) - { - file_name = tmp; - tmp = strtok (NULL, "/\\"); - } - file_path_string =filepath; - dir_path=file_path_string.substr(0,file_path_string.find(file_name)); - - //obtaining DIR pointer to directory (=NULL if directory doesn't exist) - if (!(directory=opendir(&(dir_path[0])))) - { - char msg[1000]; - sprintf(msg,"in fileExists(filepath=%s): Unable to open directory \"%s\"", filepath, &dir_path[0]); - throw iom::exception(msg); - } - - //scanning for given file - while (!file_exists && (dir_entry=readdir(directory))) - { - //storing in tmp i-th entry and checking that it not contains '.', so that I can exclude '..', '.' and files entries - if(!strcmp(&(file_name[0]), dir_entry->d_name)) - file_exists = true; - } - closedir(directory); - - return file_exists; -} - -// returns the Z-coordinate string extracted from the given filename. Supported filenames formats are -// [0-9]+_[0-9]+_[0-9]+.* and -// [0-9]+.* -std::string VirtualVolume::name2coordZ(const std::string & filename) throw (iom::exception) -{ - // split string using "_" token (also works if "_" is not present) - std::vector tokens; - vm::split(filename, "_", tokens); - - // check - if(tokens.empty()) - throw iom::exception(vm::strprintf("in VirtualVolume::name2coordZ(): error when parsing filename %s", filename.c_str()).c_str()); - - // remove file extension and return - return tokens[tokens.size()-1].substr(0, tokens[tokens.size()-1].find_last_of(".")); -} - -//extract spatial coordinates (in millimeters) of given Stack object -void VirtualVolume::extractCoordinates(VirtualStack* stk, int z, int* crd_1, int* crd_2, int* crd_3) -{ - #if VM_VERBOSE > 3 - printf("\t\t\t\tin VirtualVolume::extractCoordinates(stk=\"%s\", z = %d)\n", stk->getDIR_NAME(), z); - #endif - - bool found_ABS_X=false; - bool found_ABS_Y=false; - - //loading estimations for absolute X and Y stack positions - char * pch; - char buffer[100]; - strcpy(buffer,&(stk->getDIR_NAME()[0])); - pch = strtok (buffer,"/_"); - pch = strtok (NULL, "/_"); - - while (pch != NULL) - { - if(!found_ABS_X) - { - if(sscanf(pch, "%d", crd_1) == 1) - found_ABS_X=true; - } - else if(!found_ABS_Y) - { - if(sscanf(pch, "%d", crd_2) == 1) - found_ABS_Y=true; - } - else - break; - - pch = strtok (NULL, "/_"); - } - - if(!found_ABS_X || !found_ABS_Y) - throw iom::exception(vm::strprintf("in VirtualVolume::extractCoordinates(directory_name=\"%s\"): format 000000_000000 or X_000000_X_000000 not found", stk->getDIR_NAME()).c_str()); - - //loading estimation for absolute Z stack position - if(crd_3!= NULL) - { - // check for existing slice at z - // 2014-09-01. Alessandro. @FIXED 'extractCoordinates()' method to deal with sparse tiles w/o causing crashes. - if(!stk->isComplete(z,z)) - throw iom::exception(vm::strprintf("in VirtualVolume::extractCoordinates(directory_name=\"%s\"): no slice found at z=%d", stk->getDIR_NAME(), z).c_str()); - - char* first_file_name = stk->getFILENAMES()[z]; - - char * pch; - char lastTokenized[100]; - char buffer[500]; - strcpy(buffer,&(first_file_name[0])); - - pch = strtok (buffer,"_"); - while (pch != NULL) - { - strcpy(lastTokenized,pch); - pch = strtok (NULL, "_"); - } - - pch = strtok (lastTokenized,"."); - strcpy(lastTokenized,pch); - - if(sscanf(lastTokenized, "%d", crd_3) != 1) - throw iom::exception(vm::strprintf("in VirtualVolume::extractCoordinates(...): unable to extract Z position from filename %s", first_file_name).c_str()); - } -} - -//inserts the given displacements in the given stacks -void VirtualVolume::insertDisplacement(VirtualStack *stk_A, VirtualStack *stk_B, Displacement *displacement) throw (iom::exception) -{ - int stk_A_row = stk_A->getROW_INDEX(); - int stk_A_col = stk_A->getCOL_INDEX(); - int stk_B_row = stk_B->getROW_INDEX(); - int stk_B_col = stk_B->getCOL_INDEX(); - displacement->evalReliability(dir_vertical); - displacement->evalReliability(dir_horizontal); - displacement->evalReliability(dir_depth); - if(stk_B_row == stk_A_row && stk_B_col == stk_A_col+1) - { - displacement->setDefaultV(0); //we assume that adjacent tiles are aligned with respect to motorized stages coordinates - displacement->setDefaultH(getDEFAULT_DISPLACEMENT_H()); - displacement->setDefaultD(getDEFAULT_DISPLACEMENT_D()); - stk_A->getEAST().push_back(displacement); - stk_B->getWEST().push_back(displacement->getMirrored(dir_horizontal)); - } - else if(stk_B_row == stk_A_row +1 && stk_B_col == stk_A_col) - { - displacement->setDefaultV(getDEFAULT_DISPLACEMENT_V()); - displacement->setDefaultH(0); //we assume that adjacent tiles are aligned with respect to motorized stages coordinates - displacement->setDefaultD(getDEFAULT_DISPLACEMENT_D()); - stk_A->getSOUTH().push_back(displacement); - stk_B->getNORTH().push_back(displacement->getMirrored(dir_vertical)); - } - else - { - char errMsg[1000]; - sprintf(errMsg, "in VirtualVolume::insertDisplacement(stk_A[%d,%d], stk_B[%d,%d], displacement): stacks are not adjacent", - stk_A->getROW_INDEX(), stk_A->getCOL_INDEX(), stk_B->getROW_INDEX(), stk_B->getCOL_INDEX()); - throw iom::exception(errMsg); - } -} - -// return 'volume_format' attribute of node from the given xml. -std::string VirtualVolume::getVolumeFormat(const std::string& xml_path) throw (iom::exception) -{ - // open xml - TiXmlDocument xml; - if(!xml.LoadFile(xml_path.c_str())) - throw iom::exception(vm::strprintf("in VirtualVolume::getVolumeFormat(): cannot open xml file at \"%s\"", xml_path.c_str())); - - // get root node - TiXmlHandle hRoot(xml.FirstChildElement("TeraStitcher")); - - // get 'volume_format' attribute - const char *volformat = hRoot.ToElement()->Attribute("volume_format"); - if(!volformat) - throw iom::exception(vm::strprintf("in VirtualVolume::getVolumeFormat(): cannot find 'volume_format' attribute in xml file at \"%s\". Too old xml, please regenerate it.", xml_path.c_str()).c_str()); - - return volformat; -} diff --git a/v3d_main/terafly/src/core/volumemanager/vmVirtualVolume.h b/v3d_main/terafly/src/core/volumemanager/vmVirtualVolume.h deleted file mode 100644 index 2181736d35..0000000000 --- a/v3d_main/terafly/src/core/volumemanager/vmVirtualVolume.h +++ /dev/null @@ -1,247 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -* 2015-06-12. Giulio @ADDED 'check' method to check completeness and coherence of a volume -* 2015-02-26. Giulio. @ADDED fields DIM_C and BYTESxCHAN -* 2014-09-10. Alessandro. @ADDED 'getVolumeFormat' method to be applied on xml file. -* 2014-09-02. Alessandro. @FIXED possible bottleneck: N_SLICES was of 'uint16' type, now changed to 'int'. 'int' has been chosen in place of 'uint64' -* to avoid possible bugs as most of the code that uses 'N_SLICES' is 'int'-based. -* 2014-09-01. Alessandro. @ADDED 'name2coordZ()' utility method to extract the z-coordinate substring from a given filename. -* 2014-08-30. Alessandro. @REMOVED 'extractPathFromFilePath()' method (obsolete). -* 2014-08-30. Alessandro. @REMOVED 'print()' method from abstract class and all concrete classes (obsolete). -*/ - -#ifndef _VM_VIRTUAL_VOLUME_H -#define _VM_VIRTUAL_VOLUME_H - - -#include -#include -#include "volumemanager.config.h" -#include "iomanager.config.h" - - -//FORWARD-DECLARATIONS -class Displacement; - -class volumemanager::VirtualVolume -{ - protected: - - //******OBJECT ATTRIBUTES****** - char* stacks_dir; //C-string that contains the directory path of stacks matrix - float VXL_V, VXL_H, VXL_D; //[microns]: voxel dimensions (in microns) along V(Vertical), H(horizontal) and D(Depth) axes - float ORG_V, ORG_H, ORG_D; //[millimeters]: origin spatial coordinates (in millimeters) along VHD axes - float MEC_V, MEC_H; //[microns]: mechanical displacements of the microscope between two adjacent stacks - iom::uint16 N_ROWS, N_COLS; //dimensions (in stacks) of stacks matrix along VH axes - int N_SLICES; //dimension along D(Z). - vm::ref_sys reference_system; - int DIM_C; // number of channels (@ADDED by Iannello on ..........) - int BYTESxCHAN; // number of bytes per channel - - //initialization methods - virtual void init() throw (iom::exception); - virtual void applyReferenceSystem(vm::ref_sys reference_system, float VXL_1, float VXL_2, float VXL_3) throw (iom::exception)=0; - - //binary metadata load/save methods - virtual void saveBinaryMetadata(char *metadata_filepath) throw (iom::exception)=0; - virtual void loadBinaryMetadata(char *metadata_filepath) throw (iom::exception)=0; - - //rotates stacks matrix around D vm::axis (accepted values are theta=0,90,180,270) - virtual void rotate(int theta)=0; - - //mirrors stacks matrix along mrr_axis (accepted values are mrr_axis=1,2,3) - virtual void mirror(vm::axis mrr_axis)=0; - - //extract spatial coordinates (in millimeters) of given Stack object reading directory and filenames as spatial coordinates - void extractCoordinates(VirtualStack* stk, int z, int* crd_1, int* crd_2, int* crd_3=0); - - public: - - //CONSTRUCTORS-DECONSTRUCTOR - VirtualVolume(){ - init(); - } - VirtualVolume(const char* _stacks_dir, vm::ref_sys _reference_system, float VXL_1=0, float VXL_2=0, float VXL_3=0) throw (iom::exception) - { - init(); - - stacks_dir = new char[strlen(_stacks_dir)+1]; - strcpy(stacks_dir, _stacks_dir); - - reference_system = _reference_system; - - VXL_V = VXL_1; - VXL_H = VXL_2; - VXL_D = VXL_3; - } - VirtualVolume(const char* xml_path) throw (iom::exception){ - init(); - } - - virtual ~VirtualVolume(){} - - - // ******GET METHODS****** - float getORG_V(); - float getORG_H(); - float getORG_D(); - float getABS_V(int ABS_PIXEL_V); - float getABS_H(int ABS_PIXEL_H); - float getABS_D(int ABS_PIXEL_D); - float getVXL_V(); - float getVXL_H(); - float getVXL_D(); - float getMEC_V(); - float getMEC_H(); - virtual int getStacksHeight() = 0; - virtual int getStacksWidth() = 0; - int getN_ROWS(); - int getN_COLS(); - int getN_SLICES(); - int getDIM_C(); - int getBYTESxCHAN(); - virtual VirtualStack*** getSTACKS() = 0; - char* getSTACKS_DIR(){return this->stacks_dir;} - int getOVERLAP_V(); - int getOVERLAP_H(); - int getDEFAULT_DISPLACEMENT_V(); - int getDEFAULT_DISPLACEMENT_H(); - virtual int getDEFAULT_DISPLACEMENT_D(); - vm::ref_sys getREF_SYS(){return reference_system;} - - //loads/saves metadata from/in the given xml filename - virtual void loadXML(const char *xml_filename) = 0; - virtual void initFromXML(const char *xml_filename) = 0; - virtual void saveXML(const char *xml_filename=0, const char *xml_filepath=0) throw (iom::exception) = 0; - - // 2014-09-10. Alessandro. @ADDED 'getVolumeFormat' method to be applied on xml file. - // return 'volume_format' attribute of node from the given xml. - static std::string getVolumeFormat(const std::string& xml_path) throw (iom::exception); - - //inserts the given displacement in the given stacks - void insertDisplacement(VirtualStack *stk_A, VirtualStack *stk_B, Displacement *displacement) throw (iom::exception); - - /********************************************************************************** - * UTILITY methods - ***********************************************************************************/ - //check if volume is complete and coherent; return true if the volume is ok, false otherwise - //if a file name is passed and thevolume is not ok an error log file is generated - virtual bool check(const char *errlogFileName = 0) throw (iom::exception)=0; - - //counts the total number of displacements and the number of displacements per pair of adjacent stacks - virtual void countDisplacements(int& total, float& per_stack_pair) = 0; - - //counts the number of single-direction displacements having a reliability measure above the given threshold - virtual void countReliableSingleDirectionDisplacements(float threshold, int& total, int& reliable) = 0; - - //counts the number of stitchable stacks given the reliability threshold - virtual int countStitchableStacks(float threshold) = 0; - - //returns true if file exists at the given filepath - static bool fileExists(const char *filepath) throw (iom::exception); - - // returns the Z-coordinate string extracted from the given filename. Supported filenames formats are - // [0-9]+_[0-9]+_[0-9]+.* and - // [0-9]+.* - static std::string name2coordZ(const std::string & filename) throw (iom::exception); -}; - - -// define new type: VirtualVolume plugin creator functions -typedef volumemanager::VirtualVolume* (*VolumeCreatorXML)(const char*, bool); -typedef volumemanager::VirtualVolume* (*VolumeCreatorData)(const char*, vm::ref_sys, float, float, float, bool); - -// Factory for plugins' registration and instantiation -class volumemanager::VirtualVolumeFactory -{ - private: - - // map of registered virtual volume plugins - std::map creators_xml; - std::map creators_data; - - public: - - // singleton - static VirtualVolumeFactory* instance() - { - static VirtualVolumeFactory* uniqueInstance = new VirtualVolumeFactory(); - return uniqueInstance; - } - - // plugin registration - static std::string registerPluginCreatorXML(VolumeCreatorXML creator, std::string id) - { - instance()->creators_xml[id] = creator; - return id; - } - static std::string registerPluginCreatorData(VolumeCreatorData creator, std::string id) - { - instance()->creators_data[id] = creator; - return id; - } - - // plugin instantiation - static VirtualVolume* createFromXML(const char* xml_path, bool ow_mdata) throw (iom::exception) - { - std::string id = VirtualVolume::getVolumeFormat(xml_path); - if(instance()->creators_xml.find(id) == instance()->creators_xml.end()) - throw iom::exception(iom::strprintf("Cannot find VirtualVolume(xml) plugin \"%s\": no such plugin", id.c_str()).c_str()); - return (instance()->creators_xml[id])(xml_path, ow_mdata); - } - static VirtualVolume* createFromXML(std::string id, const char* xml_path, bool ow_mdata) throw (iom::exception) - { - if(instance()->creators_xml.find(id) == instance()->creators_xml.end()) - throw iom::exception(iom::strprintf("Cannot find VirtualVolume(xml) plugin \"%s\": no such plugin", id.c_str()).c_str()); - return (instance()->creators_xml[id])(xml_path, ow_mdata); - } - - static VirtualVolume* createFromData(std::string id, const char* data_path, vm::ref_sys ref, float vxl1, float vxl2, float vxl3, bool ow_mdata) throw (iom::exception) - { - if(instance()->creators_data.find(id) == instance()->creators_data.end()) - throw iom::exception(iom::strprintf("Cannot find VirtualVolume(data) plugin \"%s\": no such plugin", id.c_str()).c_str()); - return (instance()->creators_data[id])(data_path, ref, vxl1, vxl2, vxl3, ow_mdata); - } - - // get list of registered plugins - static std::string registeredPlugins(){ - std::string plugins; - for(std::map::iterator it = instance()->creators_xml.begin(); it != instance()->creators_xml.end(); it++) - plugins += "\"" + it->first + "\", "; - plugins = plugins.substr(0, plugins.find_last_of(",")); - return plugins; - } - static std::vector registeredPluginsList(){ - std::vector plugins; - for(std::map::iterator it = instance()->creators_xml.begin(); it != instance()->creators_xml.end(); it++) - plugins.push_back(it->first); - return plugins; - } -}; - -#endif diff --git a/v3d_main/terafly/src/core/volumemanager/volumemanager.config.cpp b/v3d_main/terafly/src/core/volumemanager/volumemanager.config.cpp deleted file mode 100644 index 12c9cf0f71..0000000000 --- a/v3d_main/terafly/src/core/volumemanager/volumemanager.config.cpp +++ /dev/null @@ -1,51 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* -* Bria, A., et al., (2012) "Stitching Terabyte-sized 3D Images Acquired in Confocal Ultramicroscopy", Proceedings of the 9th IEEE International Symposium on Biomedical Imaging. -* Bria, A., Iannello, G., "TeraStitcher - A Tool for Fast 3D Automatic Stitching of Teravoxel-sized Microscopy Images", submitted for publication, 2012. -* -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -* 2014-08-25. Alessandro. @ADDED SPARSE_DATA parameter to turn on/off sparse data support. -*/ - -#include "volumemanager.config.h" -#include "vmStackedVolume.h" -#include "vmBlockVolume.h" - -// assign default values to namespace parameters -namespace volumemanager -{ - /******************* - * PARAMETERS * - ******************** - ---------------------------------------------------------------------------------------------------------------------------*/ - std::string VOLUME_INPUT_FORMAT_PLUGIN = "TiledXY|2Dseries"; // plugin to manage the input volume format - std::string VOLUME_OUTPUT_FORMAT_PLUGIN = "TiledXY|2Dseries"; // plugin to manage the output volume format - std::string IMG_FILTER_REGEX = ""; // regular expression used to filter image filenames when the volume is imported - bool SPARSE_DATA = false; // flag to turn on/off sparse data support - /*-------------------------------------------------------------------------------------------------------------------------*/ -} diff --git a/v3d_main/terafly/src/core/volumemanager/volumemanager.config.h b/v3d_main/terafly/src/core/volumemanager/volumemanager.config.h deleted file mode 100644 index ca179b4f0e..0000000000 --- a/v3d_main/terafly/src/core/volumemanager/volumemanager.config.h +++ /dev/null @@ -1,350 +0,0 @@ -//------------------------------------------------------------------------------------------------ -// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). -// All rights reserved. -//------------------------------------------------------------------------------------------------ - -/******************************************************************************************************************************************************************************************* -* LICENSE NOTICE -******************************************************************************************************************************************************************************************** -* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change -* this code. -******************************************************************************************************************************************************************************************** -* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at -* g.iannello@unicampus.it for further details. -* 2. You agree to appropriately cite this work in your related studies and publications. -* -* Bria, A., et al., (2012) "Stitching Terabyte-sized 3D Images Acquired in Confocal Ultramicroscopy", Proceedings of the 9th IEEE International Symposium on Biomedical Imaging. -* Bria, A., Iannello, G., "TeraStitcher - A Tool for Fast 3D Automatic Stitching of Teravoxel-sized Microscopy Images", submitted for publication, 2012. -* -* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- -* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the -* copyright owners, University Campus Bio-Medico, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not -* limited to, procurement of substitute goods or services; loss of use, data, or profits;reasonable royalties; or business interruption) however caused and on any theory of liabil- -* ity, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of -* such damage. -* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without -* specific prior written permission. -********************************************************************************************************************************************************************************************/ - -/****************** -* CHANGELOG * -******************* -* 2015-08-26. Giulio. @ADDED a function to remove an empty directory -* 2014-09-01. Alessandro. @ADDED template class 'interval'. -* 2014-08-25. Alessandro. @ADDED SPARSE_DATA parameter to turn on/off sparse data support. -*/ - -#ifndef VM_CONFIG_H -#define VM_CONFIG_H - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#ifdef _WIN32 -#include -#include -#else -#include -#include -#include -#include -#include -#endif - -namespace volumemanager -{ - - /******************* - * INTERFACES * - ******************** - ---------------------------------------------------------------------------------------------------------------------------*/ - class VirtualVolume; - class VirtualVolumeFactory; - class VirtualStack; - class StackedVolume; - class BlockVolume; - class Stack; - class Block; - /*-------------------------------------------------------------------------------------------------------------------------*/ - - - /******************* - * CONSTANTS * - ******************** - ---------------------------------------------------------------------------------------------------------------------------*/ - const std::string MODULE_ID = "terastitcher::volumemanager"; - const double PI = 3.14159265; - const std::string BINARY_METADATA_FILENAME = "mdata.bin"; // binary metadata file name - const float BINARY_METADATA_VERSION = 1.5; // version of binary metadata file (used to check compatibility) - /*-------------------------------------------------------------------------------------------------------------------------*/ - - - /******************* - * MACROS * - ******************** - @warning: macros are not namespaced - ---------------------------------------------------------------------------------------------------------------------------*/ - #define VM_VERBOSE 0 //verbosity level of current module - #define VM_STATIC_STRINGS_SIZE 5000 - #define S_TIME_CALC //if enabled, single-phase processing time will be computed - - - /******************* - * PARAMETERS * - ******************** - ---------------------------------------------------------------------------------------------------------------------------*/ - extern std::string VOLUME_INPUT_FORMAT_PLUGIN; // plugin to manage the input volume format - extern std::string VOLUME_OUTPUT_FORMAT_PLUGIN; // plugin to manage the output volume format - extern std::string IMG_FILTER_REGEX; // regular expression used to filter image filenames when the volume is imported - extern bool SPARSE_DATA; // flag to turn on/off sparse data support - /*-------------------------------------------------------------------------------------------------------------------------*/ - - - /******************* - * BASIC STRUCTURES * - ******************** - ---------------------------------------------------------------------------------------------------------------------------*/ - // 1D templated interval - template struct interval{ - T start, end; - interval() : start(-1), end(-1) {} - interval(T _start, T _end) : start(_start), end(_end) {} - }; - - // axis - enum axis {vertical=1, inv_vertical=-1, horizontal=2, inv_horizontal=-2, depth=3, inv_depth=-3, axis_invalid=0}; - inline const char* axis_to_str(axis ax) - { - if(ax==axis_invalid) return "axis_invalid"; - else if(ax==vertical) return "vertical"; - else if(ax==inv_vertical) return "inv_vertical"; - else if(ax==horizontal) return "horizontal"; - else if(ax==inv_horizontal) return "inv_horizontal"; - else if(ax==depth) return "depth"; - else if(ax==inv_depth) return "inv_depth"; - else return "unknown"; - } - inline axis str2axis(const std::string & str) - { - if(str.compare("vertical") == 0 || str.compare("1") == 0 || str.compare("v") == 0 || str.compare("V") == 0 || str.compare("Y")== 0 || str.compare("y")== 0) - return vertical; - else if(str.compare("inv_vertical") == 0 || str.compare("-1") == 0 || str.compare("-v") == 0 || str.compare("-V") == 0 || str.compare("-Y")== 0 || str.compare("-y")== 0) - return inv_vertical; - else if(str.compare("horizontal") == 0 || str.compare("2") == 0 || str.compare("h") == 0 || str.compare("H") == 0 || str.compare("X")== 0 || str.compare("x")== 0) - return horizontal; - else if(str.compare("inv_horizontal") == 0 || str.compare("-2") == 0 || str.compare("-h") == 0 || str.compare("-H") == 0 || str.compare("-X")== 0 || str.compare("-x")== 0) - return inv_horizontal; - else if(str.compare("depth") == 0 || str.compare("3") == 0 || str.compare("d") == 0 || str.compare("D") == 0 || str.compare("Z")== 0 || str.compare("z")== 0) - return depth; - else if(str.compare("inv_depth") == 0 || str.compare("-3") == 0 || str.compare("-d") == 0 || str.compare("-D") == 0 || str.compare("-Z")== 0 || str.compare("-z")== 0) - return inv_depth; - else - return axis_invalid; - } - - // reference system - struct ref_sys - { - axis first, second, third; - ref_sys(axis _first, axis _second, axis _third) : first(_first), second(_second), third(_third){} - ref_sys(): first(axis_invalid), second(axis_invalid), third(axis_invalid){} - }; - /*-------------------------------------------------------------------------------------------------------------------------*/ - - /******************************************** - * Cross-platform UTILITY inline functions * - ******************************************** - ---------------------------------------------------------------------------------------------------------------------------*/ - // string-based sprintf function - inline std::string strprintf(const std::string fmt, ...){ - int size = 100; - std::string str; - va_list ap; - while (1) { - str.resize(size); - va_start(ap, fmt); - int n = vsnprintf((char *)str.c_str(), size, fmt.c_str(), ap); - va_end(ap); - if (n > -1 && n < size) { - str.resize(n); - return str; - } - if (n > -1) - size = n + 1; - else - size *= 2; - } - return str; - } - - // removes all tab, space and newline characters from the given string - inline std::string cls(std::string& string){ - string.erase(std::remove(string.begin(), string.end(), '\t'), string.end()); - string.erase(std::remove(string.begin(), string.end(), ' '), string.end()); - string.erase(std::remove(string.begin(), string.end(), '\n'), string.end()); - return string; - } - - //returns true if the given path is a directory - inline bool isDirectory(std::string path){ - struct stat s; - if( stat(path.c_str(),&s) == 0 ) - { - if( s.st_mode & S_IFDIR ) - return true; - else if( s.st_mode & S_IFREG ) - return false; - else return false; - } - else return false; - } - - //returns true if the given path is a file - inline bool isFile(std::string path){ - struct stat s; - if( stat(path.c_str(),&s) == 0 ) - { - if( s.st_mode & S_IFDIR ) - return false; - else if( s.st_mode & S_IFREG ) - return true; - else return false; - } - else return false; - } - - // tokenizer - inline void split(const std::string & theString, std::string delim, std::vector& tokens) - { - size_t start = 0, end = 0; - while ( end != std::string::npos) - { - end = theString.find( delim, start); - - // If at end, use length=maxLength. Else use length=end-start. - tokens.push_back( theString.substr( start, - (end == std::string::npos) ? std::string::npos : end - start)); - - // If at end, use start=maxSize. Else use start=end+delimiter. - start = ( ( end > (std::string::npos - delim.size()) ) - ? std::string::npos : end + delim.size()); - } - } - - //number to string conversion function and vice versa - template - std::string num2str ( T Number ){ - std::stringstream ss; - ss << Number; - return ss.str(); - } - template - T str2num ( const std::string &Text ){ - std::stringstream ss(Text); - T result; - return ss >> result ? result : 0; - } - - //make dir - #ifdef _WIN32 - #include - inline bool make_dir(const char* arg){ - bool done = _mkdir(arg) == 0; - bool result = done || errno != ENOENT; - return result; - } - #else - inline bool make_dir(const char* arg){ - bool done = mkdir(arg, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == 0; - bool result = done || errno == EEXIST; - return result; - } - #endif - - //remove dir - #ifdef _WIN32 - #include - inline bool remove_dir(const char* arg){ - bool done = _rmdir(arg) == 0; - bool result = done; - return result; - } - #else - inline bool remove_dir(const char* arg){ - //bool done = rmdir(arg) == 0; - //bool result = done; - //return result; - if(system(strprintf("rmdir \"%s\"", arg).c_str())!=0) { - fprintf(stderr,"Can't remove directory \"%s\"\n", arg); - return 0; - } - else - return 1; - } - #endif - - // check-and-makedir - inline bool check_and_make_dir(const char *dirname){ - if(isDirectory(dirname)) - return true; - else - return make_dir(dirname); - } - - - - //file deleting - #ifdef _WIN32 - inline void delete_file( const char* arg ){ - if(system(strprintf("del /F /Q /S \"%s\"", arg).c_str())!=0) - fprintf(stderr,"Can't delete file \"%s\"\n", arg); - } - #else - inline void delete_file( const char* arg ){ - if(system(strprintf("rm -f \"%s\"", arg).c_str())!=0) - fprintf(stderr,"Can't delete file \"%s\"\n", arg); - } - #endif - - //time computation - #ifdef TIME_CALC - #ifdef _WIN32 - #define TIME( arg ) (((double) clock()) / CLOCKS_PER_SEC) - #else - #define TIME( arg ) (time( arg )) - #endif - #endif - - - //MAX - #define ISR_MAX(a,b) ( (a>b) ? (a) : (b) ) - - //MAX - #define ISR_MIN(a,b) ( (a instead of +inf is returned - #define SAFE_DIVIDE(dividend, divisor, infinite) ( (divisor)==0 ? (infinite) : ((dividend)/(divisor)) ); - /*-------------------------------------------------------------------------------------------------------------------------*/ -} - -namespace vm = volumemanager; - -#endif diff --git a/v3d_main/terafly/src/presentation/PConverter.cpp b/v3d_main/terafly/src/presentation/PConverter.cpp index 61498d10f0..cd9eb07fb0 100644 --- a/v3d_main/terafly/src/presentation/PConverter.cpp +++ b/v3d_main/terafly/src/presentation/PConverter.cpp @@ -32,6 +32,7 @@ #include "PLog.h" #include "../control/CConverter.h" #include "../control/CSettings.h" +#include "QProgressSender.h" using namespace teramanager; @@ -305,7 +306,8 @@ PConverter::PConverter(V3DPluginCallback *callback, QWidget *parent) : QWidget(p //signals and slots connect(startButton, SIGNAL(clicked()), this, SLOT(startButtonClicked())); connect(stopButton, SIGNAL(clicked()), this, SLOT(stopButtonClicked())); - connect(this, SIGNAL(sendProgressBarChanged(int, int, int, const char*)), this, SLOT(progressBarChanged(int, int, int, const char*)), Qt::QueuedConnection); + qRegisterMetaType("std::string"); + connect(ts::QProgressSender::instance(), SIGNAL(sendProgressBarChanged(int, int, int, std::string)), this, SLOT(progressBarChanged(int, int, int, std::string)), Qt::QueuedConnection); connect(inFormatCBox, SIGNAL(currentIndexChanged(int)), this, SLOT(volformatChanged(int))); connect(outFormatCBox, SIGNAL(currentIndexChanged(int)), this, SLOT(volformatChanged(int))); connect(timeSeriesCheckBox, SIGNAL(stateChanged(int)), this, SLOT(volformatChanged(int))); @@ -322,6 +324,9 @@ PConverter::PConverter(V3DPluginCallback *callback, QWidget *parent) : QWidget(p connect(blockHeightField, SIGNAL(valueChanged(int)), this, SLOT(settingsChanged())); connect(blockDepthField, SIGNAL(valueChanged(int)), this, SLOT(settingsChanged())); connect(addResolutionButton, SIGNAL(clicked()), this, SLOT(addResolution())); + + terastitcher::ProgressBar::instance()->setToGUI(true); + resetGUI(); //set always on top @@ -715,17 +720,15 @@ void PConverter::closeEvent(QCloseEvent *evt) /********************************************************************************** * event handler ***********************************************************************************/ -void PConverter::progressBarChanged(int val, int minutes, int seconds, const char* message) +void PConverter::progressBarChanged(int val, int minutes, int seconds, std::string message) { progressBar->setValue(val); QString remaining_time = QString::number(minutes); remaining_time.append(" minutes and "); remaining_time.append(QString::number(seconds)); remaining_time.append(" seconds remaining"); - if(message && strlen(message) != 0) - { - statusBar->showMessage(message + QString(": ") + remaining_time); - } + if(message.size()) + statusBar->showMessage(message.c_str() + QString(": ") + remaining_time); else statusBar->showMessage(remaining_time); } diff --git a/v3d_main/terafly/src/presentation/PConverter.h b/v3d_main/terafly/src/presentation/PConverter.h index 6b9519d967..17166abb20 100644 --- a/v3d_main/terafly/src/presentation/PConverter.h +++ b/v3d_main/terafly/src/presentation/PConverter.h @@ -124,13 +124,6 @@ class teramanager::PConverter : public QWidget //overrides closeEvent method of QWidget void closeEvent(QCloseEvent *evt); - /********************************************************************************** - * Called by algorithms running from different threads. - * Emits signal - ***********************************************************************************/ - void emitProgressBarChanged(int val, int minutes, int seconds, const char* message = 0) - {emit sendProgressBarChanged(val, minutes, seconds, message);} - public slots: void startButtonClicked(); @@ -145,7 +138,7 @@ class teramanager::PConverter : public QWidget /********************************************************************************** * event handler ***********************************************************************************/ - void progressBarChanged(int val, int minutes, int seconds, const char* message); + void progressBarChanged(int val, int minutes, int seconds, std::string message); /********************************************************************************** * Called by when the associated operation has been performed. @@ -168,10 +161,6 @@ class teramanager::PConverter : public QWidget signals: - /********************************************************************************* - * Carries progress bar informations (progress percentage and remaining minutes). - **********************************************************************************/ - void sendProgressBarChanged(int val, int minutes, int seconds, const char* message); }; #endif // PCONVETER_GUI_H diff --git a/v3d_main/terafly/src/presentation/PMain.cpp b/v3d_main/terafly/src/presentation/PMain.cpp index 4e853f5559..9b1e8b670a 100644 --- a/v3d_main/terafly/src/presentation/PMain.cpp +++ b/v3d_main/terafly/src/presentation/PMain.cpp @@ -50,7 +50,7 @@ #include #include #include "VolumeConverter.h" -#include "../core/imagemanager/TiledMCVolume.h" +#include "TiledMCVolume.h" using namespace teramanager; using namespace iim; @@ -2300,166 +2300,15 @@ void PMain::debugAction1Triggered() { /**/itm::debug(itm::NO_DEBUG, 0, __itm__current__function__); -// try -// { -// VolumeConverter *vc = new VolumeConverter(); -// iim::DEBUG = iim::LEV_MAX; -// vc->setSrcVolume("/Volumes/Volumes/test.purkinje.big.tiff.3D.oneblock/RES(2122x1951x608)/000000/000000_000000/000000_000000_000000.tif", iim::TIF3D_FORMAT.c_str()); -// } -// catch(...){QMessageBox::warning(this, "error", "error");} -// QString apo1FilePath = QFileDialog::getOpenFileName(this, tr("Select first APO file (assumed as TRUTH)"), 0,tr("APO files (*.apo)")); -// if(!apo1FilePath.isEmpty()) -// { - -// QList cells = readAPO_file(apo1FilePath); -// for(int k=0; kanoH0, viewer->anoH1, viewer->anoV0, viewer->anoV1, viewer->anoD0, viewer->anoD1).c_str()); -// QPalette Pal(palette()); -// Pal.setColor(QPalette::Background, Qt::red); -// QWidget *emptyPanel = new QWidget(); -// emptyPanel->setAutoFillBackground(true); -// emptyPanel->setPalette(Pal); -// emptyPanel->setFixedWidth(50); -// CViewer::getCurrent()->window3D->centralLayout->insertWidget(0, emptyPanel); - //CViewer::getCurrent()->window3D->centralLayout->takeAt(0); - //QMessageBox::information(this, "position", itm::strprintf("x = %d, y = %d", this->mapToGlobal(pos()).x(), this->mapToGlobal(pos()).y()).c_str()); - -// int n_points = QInputDialog::getInt(this, "", "Number of points:"); -// int n_samples = QInputDialog::getInt(this, "", "Number of samples:"); - -// int dimX = 10000; -// int dimY = 10000; -// int dimZ = 10000; -// CAnnotations::instance(dimY, dimX, dimZ); -// CAnnotations* cano = CAnnotations::getInstance(); -// LandmarkList input_markers; -// for(int k=0; kaddLandmarks(itm::interval_t(0, dimX), itm::interval_t(0, dimY), itm::interval_t(0, dimZ),input_markers); - -// float t_lin_sum = 0, t_lin_sum_sq = 0, t_oct_sum = 0, t_oct_sum_sq = 0; -// for(int n=0; n markers_VOI_lin, markers_VOI; - -// QElapsedTimer timer_ano; -// timer_ano.start(); -// for(int k=0; k= x0 && input_markers[k].x <= x1 && -// input_markers[k].y >= y0 && input_markers[k].y <= y1 && -// input_markers[k].z >= z0 && input_markers[k].z <= z1) -// markers_VOI_lin.push_back(input_markers[k]); -// t_lin_sum += timer_ano.elapsed(); -// t_lin_sum_sq += std::pow(timer_ano.elapsed(), 2.0f); - -// timer_ano.restart(); -// cano->findLandmarks(itm::interval_t(x0, x1), -// itm::interval_t(y0, y1), -// itm::interval_t(z0, z1), markers_VOI); -// t_oct_sum += timer_ano.elapsed(); -// t_oct_sum_sq += std::pow(timer_ano.elapsed(), 2.0f); -// } - -// QMessageBox::information(this, "Results", itm::strprintf("SCAN_LIN -> %.5f stdev %.5f\nSCAN_OCT -> %.5f stdev %.5f", -// t_lin_sum/n_samples, sqrt(t_lin_sum_sq/n_samples - pow(t_lin_sum/n_samples, 2.0f)), -// t_oct_sum/n_samples, sqrt(t_oct_sum_sq/n_samples - pow(t_oct_sum/n_samples, 2.0f))).c_str()); -// CAnnotations::uninstance(); - - - - // printf("PMain is: %s\n", PMain::getInstance() ? "not null" : "NULL"); - -// QMessageBox::information(0, "The number of annotations is...", QString::number(CAnnotations::getInstance()->count())); - -/*QList cellsT0 = readAPO_file(QFileDialog::getOpenFileName(this, tr("Open APO file (proofreading I)"), 0,tr("APO files (*.apo)"))); -QList cellsT1 = readAPO_file(QFileDialog::getOpenFileName(this, tr("Open APO file (proofreading II)"), 0,tr("APO files (*.apo)"))); -QList cells_output; - -// FNb = blue cells in T1 --> display as BLUE -int FNb = 0; -for(int i=0; i display as PURPLE -int FNa = 0; -for(int i=0; i display as RED -int FPb = 0; -for(int i=0; i display as ORANGE -int FPa = 0; -for(int i=0; ishowMessage(QString::number(count++)); + //QApplication::processEvents(); } } -QMessageBox::information(this, "result", itm::strprintf("FPa = %d\nFNa = %d\nFPb = %d\nFNb = %d", FPa, FNa, FPb, FNb).c_str()); - -writeAPO_file(QFileDialog::getSaveFileName(this, "save result to", 0, tr("APO files (*.apo)")), cells_output);*/ - -// CAnnotations::getInstance()->prune(); - -// QMessageBox::information(0, "after pruning, the number of annotations is...", QString::number(CAnnotations::getInstance()->count())); - -} - void PMain::showLogTriggered() { /**/itm::debug(itm::LEV1, 0, __itm__current__function__); diff --git a/v3d_main/terafly/src/terarepo b/v3d_main/terafly/src/terarepo new file mode 160000 index 0000000000..1f46588bba --- /dev/null +++ b/v3d_main/terafly/src/terarepo @@ -0,0 +1 @@ +Subproject commit 1f46588bbae282eaa1028c5f071cf40196c12dbc diff --git a/v3d_main/terafly/teramanager.pro b/v3d_main/terafly/teramanager.pro index 354545d654..b316545204 100644 --- a/v3d_main/terafly/teramanager.pro +++ b/v3d_main/terafly/teramanager.pro @@ -53,128 +53,133 @@ INCLUDEPATH += $$V3DMAINPATH/v3d DEFINES += USE_EXPERIMENTAL_FEATURES #setup iomanager -INCLUDEPATH += ../terafly/src/core/iomanager -HEADERS += ../terafly/src/core/iomanager/iomanager.config.h -HEADERS += ../terafly/src/core/iomanager/ioplugins.h -HEADERS += ../terafly/src/core/iomanager/IOPluginAPI.h -HEADERS += ../terafly/src/core/iomanager/ProgressBar.h -HEADERS += ../terafly/src/core/iomanager/plugins/exampleplugin2D/exampleplugin2D.h -#HEADERS += ../terafly/src/core/iomanager/plugins/opencv2D/opencv2D.h -HEADERS += ../terafly/src/core/iomanager/plugins/tiff2D/tiff2D.h -HEADERS += ../terafly/src/core/iomanager/plugins/tiff3D/tiff3D.h -SOURCES += ../terafly/src/core/iomanager/iomanager.config.cpp -SOURCES += ../terafly/src/core/iomanager/ProgressBar.cpp -SOURCES += ../terafly/src/core/iomanager/plugins/exampleplugin2D/exampleplugin2D.cpp -#SOURCES += ../terafly/src/core/iomanager/plugins/opencv2D/opencv2D.cpp -SOURCES += ../terafly/src/core/iomanager/plugins/tiff2D/tiff2D.cpp -SOURCES += ../terafly/src/core/iomanager/plugins/tiff3D/tiff3D.cpp +INCLUDEPATH += ../terafly/src/terarepo/src/iomanager +HEADERS += ../terafly/src/terarepo/src/iomanager/iomanager.config.h +HEADERS += ../terafly/src/terarepo/src/iomanager/ioplugins.h +HEADERS += ../terafly/src/terarepo/src/iomanager/IOPluginAPI.h +HEADERS += ../terafly/src/terarepo/src/iomanager/plugins/exampleplugin2D/exampleplugin2D.h +#HEADERS += ../terafly/src/terarepo/src/iomanager/plugins/opencv2D/opencv2D.h +HEADERS += ../terafly/src/terarepo/src/iomanager/plugins/tiff2D/tiff2D.h +HEADERS += ../terafly/src/terarepo/src/iomanager/plugins/tiff3D/tiff3D.h +SOURCES += ../terafly/src/terarepo/src/iomanager/iomanager.config.cpp +SOURCES += ../terafly/src/terarepo/src/iomanager/plugins/exampleplugin2D/exampleplugin2D.cpp +#SOURCES += ../terafly/src/terarepo/src/iomanager/plugins/opencv2D/opencv2D.cpp +SOURCES += ../terafly/src/terarepo/src/iomanager/plugins/tiff2D/tiff2D.cpp +SOURCES += ../terafly/src/terarepo/src/iomanager/plugins/tiff3D/tiff3D.cpp #setup imagemanager -INCLUDEPATH += ../terafly/src/core/imagemanager -HEADERS += ../terafly/src/core/imagemanager/BDVVolume.h -HEADERS += ../terafly/src/core/imagemanager/HDF5Mngr.h -HEADERS += ../terafly/src/core/imagemanager/imBlock.h -HEADERS += ../terafly/src/core/imagemanager/dirent_win.h -HEADERS += ../terafly/src/core/imagemanager/IM_config.h -HEADERS += ../terafly/src/core/imagemanager/ProgressBar.h -HEADERS += ../terafly/src/core/imagemanager/RawFmtMngr.h -HEADERS += ../terafly/src/core/imagemanager/RawVolume.h -HEADERS += ../terafly/src/core/imagemanager/SimpleVolume.h -HEADERS += ../terafly/src/core/imagemanager/SimpleVolumeRaw.h -HEADERS += ../terafly/src/core/imagemanager/Stack.h -HEADERS += ../terafly/src/core/imagemanager/StackRaw.h -HEADERS += ../terafly/src/core/imagemanager/StackedVolume.h -HEADERS += ../terafly/src/core/imagemanager/Tiff3DMngr.h -HEADERS += ../terafly/src/core/imagemanager/TiledMCVolume.h -HEADERS += ../terafly/src/core/imagemanager/TiledVolume.h -HEADERS += ../terafly/src/core/imagemanager/TimeSeries.h -HEADERS += ../terafly/src/core/imagemanager/VirtualFmtMngr.h -HEADERS += ../terafly/src/core/imagemanager/VirtualVolume.h -HEADERS += ../terafly/src/core/imagemanager/UnstitchedVolume.h -SOURCES += ../terafly/src/core/imagemanager/BDVVolume.cpp -SOURCES += ../terafly/src/core/imagemanager/HDF5Mngr.cpp -SOURCES += ../terafly/src/core/imagemanager/imBlock.cpp -SOURCES += ../terafly/src/core/imagemanager/IM_config.cpp -SOURCES += ../terafly/src/core/imagemanager/imProgressBar.cpp -SOURCES += ../terafly/src/core/imagemanager/RawFmtMngr.cpp -SOURCES += ../terafly/src/core/imagemanager/RawVolume.cpp -SOURCES += ../terafly/src/core/imagemanager/SimpleVolume.cpp -SOURCES += ../terafly/src/core/imagemanager/SimpleVolumeRaw.cpp -SOURCES += ../terafly/src/core/imagemanager/Stack.cpp -SOURCES += ../terafly/src/core/imagemanager/StackRaw.cpp -SOURCES += ../terafly/src/core/imagemanager/StackedVolume.cpp -SOURCES += ../terafly/src/core/imagemanager/Tiff3DMngr.cpp -SOURCES += ../terafly/src/core/imagemanager/TiledMCVolume.cpp -SOURCES += ../terafly/src/core/imagemanager/TiledVolume.cpp -SOURCES += ../terafly/src/core/imagemanager/TimeSeries.cpp -SOURCES += ../terafly/src/core/imagemanager/VirtualFmtMngr.cpp -SOURCES += ../terafly/src/core/imagemanager/VirtualVolume.cpp -SOURCES += ../terafly/src/core/imagemanager/UnstitchedVolume.cpp +INCLUDEPATH += ../terafly/src/terarepo/src/imagemanager +HEADERS += ../terafly/src/terarepo/src/imagemanager/BDVVolume.h +HEADERS += ../terafly/src/terarepo/src/imagemanager/HDF5Mngr.h +HEADERS += ../terafly/src/terarepo/src/imagemanager/imBlock.h +HEADERS += ../terafly/src/terarepo/src/imagemanager/dirent_win.h +HEADERS += ../terafly/src/terarepo/src/imagemanager/IM_config.h +HEADERS += ../terafly/src/terarepo/src/imagemanager/RawFmtMngr.h +HEADERS += ../terafly/src/terarepo/src/imagemanager/RawVolume.h +HEADERS += ../terafly/src/terarepo/src/imagemanager/SimpleVolume.h +HEADERS += ../terafly/src/terarepo/src/imagemanager/SimpleVolumeRaw.h +HEADERS += ../terafly/src/terarepo/src/imagemanager/Stack.h +HEADERS += ../terafly/src/terarepo/src/imagemanager/StackRaw.h +HEADERS += ../terafly/src/terarepo/src/imagemanager/StackedVolume.h +HEADERS += ../terafly/src/terarepo/src/imagemanager/Tiff3DMngr.h +HEADERS += ../terafly/src/terarepo/src/imagemanager/TiledMCVolume.h +HEADERS += ../terafly/src/terarepo/src/imagemanager/TiledVolume.h +HEADERS += ../terafly/src/terarepo/src/imagemanager/TimeSeries.h +HEADERS += ../terafly/src/terarepo/src/imagemanager/VirtualFmtMngr.h +HEADERS += ../terafly/src/terarepo/src/imagemanager/VirtualVolume.h +HEADERS += ../terafly/src/terarepo/src/imagemanager/UnstitchedVolume.h +SOURCES += ../terafly/src/terarepo/src/imagemanager/BDVVolume.cpp +SOURCES += ../terafly/src/terarepo/src/imagemanager/HDF5Mngr.cpp +SOURCES += ../terafly/src/terarepo/src/imagemanager/imBlock.cpp +SOURCES += ../terafly/src/terarepo/src/imagemanager/IM_config.cpp +SOURCES += ../terafly/src/terarepo/src/imagemanager/RawFmtMngr.cpp +SOURCES += ../terafly/src/terarepo/src/imagemanager/RawVolume.cpp +SOURCES += ../terafly/src/terarepo/src/imagemanager/SimpleVolume.cpp +SOURCES += ../terafly/src/terarepo/src/imagemanager/SimpleVolumeRaw.cpp +SOURCES += ../terafly/src/terarepo/src/imagemanager/Stack.cpp +SOURCES += ../terafly/src/terarepo/src/imagemanager/StackRaw.cpp +SOURCES += ../terafly/src/terarepo/src/imagemanager/StackedVolume.cpp +SOURCES += ../terafly/src/terarepo/src/imagemanager/Tiff3DMngr.cpp +SOURCES += ../terafly/src/terarepo/src/imagemanager/TiledMCVolume.cpp +SOURCES += ../terafly/src/terarepo/src/imagemanager/TiledVolume.cpp +SOURCES += ../terafly/src/terarepo/src/imagemanager/TimeSeries.cpp +SOURCES += ../terafly/src/terarepo/src/imagemanager/VirtualFmtMngr.cpp +SOURCES += ../terafly/src/terarepo/src/imagemanager/VirtualVolume.cpp +SOURCES += ../terafly/src/terarepo/src/imagemanager/UnstitchedVolume.cpp # set up stitcher -INCLUDEPATH += ../terafly/src/core/stitcher -HEADERS += ../terafly/src/core/stitcher/S_config.h -HEADERS += ../terafly/src/core/stitcher/Displacement.h -HEADERS += ../terafly/src/core/stitcher/DisplacementMIPNCC.h -HEADERS += ../terafly/src/core/stitcher/PDAlgo.h -HEADERS += ../terafly/src/core/stitcher/PDAlgoMIPNCC.h -HEADERS += ../terafly/src/core/stitcher/StackRestorer.h -HEADERS += ../terafly/src/core/stitcher/StackStitcher.h -HEADERS += ../terafly/src/core/stitcher/TPAlgo.h -HEADERS += ../terafly/src/core/stitcher/TPAlgoMST.h -HEADERS += ../terafly/src/core/stitcher/resumer.h -SOURCES += ../terafly/src/core/stitcher/Displacement.cpp -SOURCES += ../terafly/src/core/stitcher/DisplacementMIPNCC.cpp -SOURCES += ../terafly/src/core/stitcher/MergeTiles.cpp -SOURCES += ../terafly/src/core/stitcher/PDAlgo.cpp -SOURCES += ../terafly/src/core/stitcher/PDAlgoMIPNCC.cpp -SOURCES += ../terafly/src/core/stitcher/StackRestorer.cpp -SOURCES += ../terafly/src/core/stitcher/StackStitcher.cpp -SOURCES += ../terafly/src/core/stitcher/TPAlgo.cpp -SOURCES += ../terafly/src/core/stitcher/TPAlgoMST.cpp -SOURCES += ../terafly/src/core/stitcher/resumer.cpp +INCLUDEPATH += ../terafly/src/terarepo/src/stitcher +HEADERS += ../terafly/src/terarepo/src/stitcher/S_config.h +HEADERS += ../terafly/src/terarepo/src/stitcher/Displacement.h +HEADERS += ../terafly/src/terarepo/src/stitcher/DisplacementMIPNCC.h +HEADERS += ../terafly/src/terarepo/src/stitcher/PDAlgo.h +HEADERS += ../terafly/src/terarepo/src/stitcher/PDAlgoMIPNCC.h +HEADERS += ../terafly/src/terarepo/src/stitcher/StackRestorer.h +HEADERS += ../terafly/src/terarepo/src/stitcher/StackStitcher.h +HEADERS += ../terafly/src/terarepo/src/stitcher/TPAlgo.h +HEADERS += ../terafly/src/terarepo/src/stitcher/TPAlgoMST.h +HEADERS += ../terafly/src/terarepo/src/stitcher/resumer.h +SOURCES += ../terafly/src/terarepo/src/stitcher/Displacement.cpp +SOURCES += ../terafly/src/terarepo/src/stitcher/DisplacementMIPNCC.cpp +SOURCES += ../terafly/src/terarepo/src/stitcher/MergeTiles.cpp +SOURCES += ../terafly/src/terarepo/src/stitcher/PDAlgo.cpp +SOURCES += ../terafly/src/terarepo/src/stitcher/PDAlgoMIPNCC.cpp +SOURCES += ../terafly/src/terarepo/src/stitcher/StackRestorer.cpp +SOURCES += ../terafly/src/terarepo/src/stitcher/StackStitcher.cpp +SOURCES += ../terafly/src/terarepo/src/stitcher/TPAlgo.cpp +SOURCES += ../terafly/src/terarepo/src/stitcher/TPAlgoMST.cpp +SOURCES += ../terafly/src/terarepo/src/stitcher/resumer.cpp # set up volumeconverter -INCLUDEPATH += ../terafly/src/core/volumeconverter -HEADERS += ../terafly/src/core/volumeconverter/S_config.h -HEADERS += ../terafly/src/core/volumeconverter/VolumeConverter.h -SOURCES += ../terafly/src/core/volumeconverter/VolumeConverter.cpp +INCLUDEPATH += ../terafly/src/terarepo/src/utils/volumeconverter +HEADERS += ../terafly/src/terarepo/src/utils/volumeconverter/S_config.h +HEADERS += ../terafly/src/terarepo/src/utils/volumeconverter/VolumeConverter.h +SOURCES += ../terafly/src/terarepo/src/utils/volumeconverter/VolumeConverter.cpp # set up volumemanager -INCLUDEPATH += ../terafly/src/core/volumemanager -HEADERS += ../terafly/src/core/volumemanager/vmBlock.h -HEADERS += ../terafly/src/core/volumemanager/vmBlockVolume.h -HEADERS += ../terafly/src/core/volumemanager/vmStack.h -HEADERS += ../terafly/src/core/volumemanager/vmStackedVolume.h -HEADERS += ../terafly/src/core/volumemanager/vmVirtualStack.h -HEADERS += ../terafly/src/core/volumemanager/vmVirtualVolume.h -HEADERS += ../terafly/src/core/volumemanager/volumemanager.config.h -SOURCES += ../terafly/src/core/volumemanager/vmBlock.cpp -SOURCES += ../terafly/src/core/volumemanager/vmBlockVolume.cpp -SOURCES += ../terafly/src/core/volumemanager/vmStack.cpp -SOURCES += ../terafly/src/core/volumemanager/vmStackedVolume.cpp -SOURCES += ../terafly/src/core/volumemanager/vmVirtualStack.cpp -SOURCES += ../terafly/src/core/volumemanager/vmVirtualVolume.cpp -SOURCES += ../terafly/src/core/volumemanager/volumemanager.config.cpp +INCLUDEPATH += ../terafly/src/terarepo/src/volumemanager +HEADERS += ../terafly/src/terarepo/src/volumemanager/vmBlock.h +HEADERS += ../terafly/src/terarepo/src/volumemanager/vmBlockVolume.h +HEADERS += ../terafly/src/terarepo/src/volumemanager/vmStack.h +HEADERS += ../terafly/src/terarepo/src/volumemanager/vmStackedVolume.h +HEADERS += ../terafly/src/terarepo/src/volumemanager/vmVirtualStack.h +HEADERS += ../terafly/src/terarepo/src/volumemanager/vmVirtualVolume.h +HEADERS += ../terafly/src/terarepo/src/volumemanager/volumemanager.config.h +SOURCES += ../terafly/src/terarepo/src/volumemanager/vmBlock.cpp +SOURCES += ../terafly/src/terarepo/src/volumemanager/vmBlockVolume.cpp +SOURCES += ../terafly/src/terarepo/src/volumemanager/vmStack.cpp +SOURCES += ../terafly/src/terarepo/src/volumemanager/vmStackedVolume.cpp +SOURCES += ../terafly/src/terarepo/src/volumemanager/vmVirtualStack.cpp +SOURCES += ../terafly/src/terarepo/src/volumemanager/vmVirtualVolume.cpp +SOURCES += ../terafly/src/terarepo/src/volumemanager/volumemanager.config.cpp # set up crossmips -INCLUDEPATH += ../terafly/src/core/crossmips -HEADERS += ../terafly/src/core/crossmips/my_defs.h -HEADERS += ../terafly/src/core/crossmips/CrossMIPs.h -HEADERS += ../terafly/src/core/crossmips/compute_funcs.h -SOURCES += ../terafly/src/core/crossmips/compute_funcs.cpp -SOURCES += ../terafly/src/core/crossmips/libcrossmips.cpp +INCLUDEPATH += ../terafly/src/terarepo/src/crossmips +HEADERS += ../terafly/src/terarepo/src/crossmips/my_defs.h +HEADERS += ../terafly/src/terarepo/src/crossmips/CrossMIPs.h +HEADERS += ../terafly/src/terarepo/src/crossmips/compute_funcs.h +SOURCES += ../terafly/src/terarepo/src/crossmips/compute_funcs.cpp +SOURCES += ../terafly/src/terarepo/src/crossmips/libcrossmips.cpp # set up tinyxml -INCLUDEPATH += ../terafly/src/core/tinyxml -HEADERS += ../terafly/src/core/tinyxml/tinyxml.h -HEADERS += ../terafly/src/core/tinyxml/tinystr.h -SOURCES += ../terafly/src/core/tinyxml/tinystr.cpp -SOURCES += ../terafly/src/core/tinyxml/tinyxmlparser.cpp -SOURCES += ../terafly/src/core/tinyxml/tinyxmlerror.cpp -SOURCES += ../terafly/src/core/tinyxml/tinyxml.cpp - +INCLUDEPATH += ../terafly/src/terarepo/src/tinyxml +HEADERS += ../terafly/src/terarepo/src/tinyxml/tinyxml.h +HEADERS += ../terafly/src/terarepo/src/tinyxml/tinystr.h +SOURCES += ../terafly/src/terarepo/src/tinyxml/tinystr.cpp +SOURCES += ../terafly/src/terarepo/src/tinyxml/tinyxmlparser.cpp +SOURCES += ../terafly/src/terarepo/src/tinyxml/tinyxmlerror.cpp +SOURCES += ../terafly/src/terarepo/src/tinyxml/tinyxml.cpp + +# set up common +INCLUDEPATH += ../terafly/src/terarepo/src/common +HEADERS += ../terafly/src/terarepo/src/common/config.h +HEADERS += ../terafly/src/terarepo/src/common/ProgressBar.h +HEADERS += ../terafly/src/terarepo/src/common/QProgressSender.h +SOURCES += ../terafly/src/terarepo/src/common/config.cpp +SOURCES += ../terafly/src/terarepo/src/common/ProgressBar.cpp +SOURCES += ../terafly/src/terarepo/src/common/QProgressSender.cpp +DEFINES += WITH_QT #set up TeraFly plugin (control and presentation classes) RESOURCES += ../terafly/icons.qrc diff --git a/v3d_main/v3d/v3d_version_info.cpp b/v3d_main/v3d/v3d_version_info.cpp index 1d0085fb6f..9ae4c9562e 100644 --- a/v3d_main/v3d/v3d_version_info.cpp +++ b/v3d_main/v3d/v3d_version_info.cpp @@ -50,7 +50,7 @@ Peng, H, Ruan, Z., Atasoy, D., and Sternson, S. (2010) “Automatic reconstructi namespace v3d { // Set current version here. - VersionInfo thisVersionOfV3D(3.13); + VersionInfo thisVersionOfV3D(3.131); QString versionnumber = "Vaa3D (3D Visualization-Assisted Analysis) (" + thisVersionOfV3D.toQString() +