diff --git a/CMakeLists.txt b/CMakeLists.txt index f1b0d6002bd3cb3fd1b8996baec47d89dfa730fd..c31d605bd28213d887e01e20bb954b5bdd8c0342 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -392,6 +392,17 @@ endif() # Provide an option for generating documentation. add_subdirectory(Utilities/Doxygen) +#---------------------------------------------------------------------- +# Provide a target to generate the SuperBuild archive (only for Unix) +if(UNIX) + add_custom_target(SuperBuild-archive + COMMAND ./SuperbuildDownloadList.sh + ${OTB_BINARY_DIR}/Download + ${OTB_BINARY_DIR} + WORKING_DIRECTORY ${OTB_SOURCE_DIR}/Utilities/Maintenance + ) +endif() + # TODO cleanup # Create target to download data from the OTBData group. This must come after # all tests have been added that reference the group, so we put it last. diff --git a/Copyright/Copyright.txt b/Copyright/Copyright.txt index 6f7788f583a027750cff1a2588e9d007788f4171..eaafdd8042caa0bfd122e6b8067cd6ec2c309c42 100644 --- a/Copyright/Copyright.txt +++ b/Copyright/Copyright.txt @@ -21,7 +21,7 @@ See CrispCopyright.txt for details. * Parts of the code have been developped by Gregoire Mercier. - See GETCopyright.txt for details. + See IMTCopyright.txt for details. --------------------------- DEPENDENCIES ---------------------------------- Several utilities are mandatory dependencies used by the OTB library : diff --git a/Copyright/GETCopyright.txt b/Copyright/IMTCopyright.txt similarity index 78% rename from Copyright/GETCopyright.txt rename to Copyright/IMTCopyright.txt index 7ac8ce5f0c4fd75918cf746f9f9cfbf50fc67a8a..7fb5d5df7ace7e756cd1c3aa3c634d4d8e4738c1 100644 --- a/Copyright/GETCopyright.txt +++ b/Copyright/IMTCopyright.txt @@ -1,10 +1,8 @@ Parts of the code have been developped by Gregoire Mercier from -Groupe des Ecoles des Telecommunications / Ecole Nationale Superieure -des Telecommunications de Bretagne (GET/ENST Bretagne) during -CNES R&T contrats funded by the French Centre National d'Etudes -Spatiales, CNES. +Institut Mines-Telecom / Telecom Bretagne during CNES R&T contrats +funded by the French Centre National d'Etudes Spatiales, CNES. -Copyright (c) GET / ENST Bretagne +Copyright (c) Institut Mines-Telecom This code has been integrated into the ORFEO Toolbox (OTB) under the CeCILL licence version 2. See Licence_CeCILL_V2-en.txt or diff --git a/Examples/BasicFilters/CMakeLists.txt b/Examples/BasicFilters/CMakeLists.txt index c8fb34bd1304b95ad7c9f911bdf275115fd10b84..858e0fa5ae8d0fa920aa9e08e4c0aca335c57fe7 100644 --- a/Examples/BasicFilters/CMakeLists.txt +++ b/Examples/BasicFilters/CMakeLists.txt @@ -1,10 +1,16 @@ project(BasicFiltersExamples) +#OTB_USE_MUPARSER is OFF +if(OTBMathParser_LOADED) add_executable(BandMathFilterExample BandMathFilterExample.cxx) target_link_libraries(BandMathFilterExample ${OTB_LIBRARIES}) +endif() +#OTB_USE_MUPARSERX is OFF +if(OTBMathParserX_LOADED) add_executable(BandMathXImageFilterExample BandMathXImageFilterExample.cxx) target_link_libraries(BandMathXImageFilterExample ${OTB_LIBRARIES}) +endif() add_executable(DEMToRainbowExample DEMToRainbowExample.cxx) target_link_libraries(DEMToRainbowExample ${OTB_LIBRARIES}) @@ -21,8 +27,11 @@ target_link_libraries(IndexedToRGBExample ${OTB_LIBRARIES}) add_executable(LeeImageFilter LeeImageFilter.cxx) target_link_libraries(LeeImageFilter ${OTB_LIBRARIES}) +#OTBMeanShift depends OTBMathParser. But OTB_USE_MUPARSER is OFF +if(OTBMathParser_LOADED) add_executable(MeanShiftSegmentationFilterExample MeanShiftSegmentationFilterExample.cxx) target_link_libraries(MeanShiftSegmentationFilterExample ${OTB_LIBRARIES}) +endif() add_executable(PrintableImageFilterExample PrintableImageFilterExample.cxx) target_link_libraries(PrintableImageFilterExample ${OTB_LIBRARIES}) diff --git a/Examples/BasicFilters/test/CMakeLists.txt b/Examples/BasicFilters/test/CMakeLists.txt index 15da042a010e826cedf26779452177d37a1b5f89..cc6dabe32daa2c486acaed79481b64b63d287baf 100644 --- a/Examples/BasicFilters/test/CMakeLists.txt +++ b/Examples/BasicFilters/test/CMakeLists.txt @@ -84,7 +84,7 @@ otb_add_test(NAME bfTeIndexedToRGBExampleTest COMMAND ${OTB_TEST_DRIVER} ${TEMP}/buildingExtractionRGB.png ${TEMP}/buildingExtractionIndexed_scaled.png ) - +if(OTBMathParser_LOADED) otb_add_test(NAME bfTeMeanShiftSegmentationFilterExampleTest COMMAND ${OTB_TEST_DRIVER} --compare-n-images ${NOTOL} 4 ${BASELINE}/MSClusteredOutput.tif @@ -107,7 +107,7 @@ otb_add_test(NAME bfTeMeanShiftSegmentationFilterExampleTest COMMAND ${OTB_TEST_ 100 0.1 ) - +endif() # ------- HillShadingExampleTest ---------- otb_add_test(NAME bfTeHillShadingExampleTest COMMAND ${OTB_TEST_DRIVER} diff --git a/Examples/CMakeLists.txt b/Examples/CMakeLists.txt index 639761a6c6e94b30538e8febb535134ca33c6b1a..84b3542f4f25ff3f52fa79e88c29e1f1b99bb3ba 100644 --- a/Examples/CMakeLists.txt +++ b/Examples/CMakeLists.txt @@ -81,32 +81,12 @@ if(PROJECT_NAME STREQUAL "OTBExamples") ########################## end copied from OTB/CMakeLists.txt ########################## - #must be updated for new modules! - set(REQUIRED_MODULES "OTB6S;OTBITK;OTBAnomalyDetection;OTBBoost;OTBCommon;OTBGDAL;OTBOpenThreads;OTBOssim;OTBGeoTIFF;OTBOssimPlugins;OTBOSSIMAdapters;OTBObjectList;OTBMetadata;OTBImageBase;OTBBoostAdapters;OTBGdalAdapters;OTBTinyXML;OTBVectorDataBase;OTBIOGDAL;OTBExtendedFilename;OTBIOBSQ;OTBIOLUM;OTBIOMSTAR;OTBIOMW;OTBIOONERA;OTBIORAD;OTBCurl;OTBCurlAdapters;OTBIOTileMap;OTBStreaming;OTBImageIO;OTBInterpolation;OTBTransform;OTBImageManipulation;OTBTestKernel;OTBPath;OTBVectorDataManipulation;OTBProjection;OTBlibkml;OTBIOKML;OTBVectorDataIO;OTBApplicationEngine;OTBStatistics;OTBChangeDetection;OTBAppChangeDetection;OTBCommandLine;OTBColorMap;OTBMoments;OTBLabelMap;OTBConversion;OTBFuzzy;OTBMuParser;OTBMathParser;OTBSupervised;OTBDempsterShafer;OTBIOXML;OTBIndices;OTBMajorityVoting;OTBSOM;OTBAppClassification;OTBPointSet;OTBSiftFast;OTBDescriptors;OTBAppDescriptors;OTBDimensionalityReduction;OTBAppDimensionalityReduction;OTBSpatialObjects;OTBEdge;OTBAppEdge;OTBImageNoise;OTBAppFiltering;OTBConvolution;OTBPanSharpening;OTBAppFusion;OTBEndmembersExtraction;OTBWavelet;OTBUnmixing;OTBAppHyperspectral;OTBCarto;OTBAppImageUtils;OTBAppIndices;OTBKMZWriter;OTBAppKMZ;OTBAppMathParser;OTBMuParserX;OTBMathParserX;OTBAppMathParserX;OTBAppMoments;OTBAppMorphology;OTBOpticalCalibration;OTBAppOpticalCalibration;OTBAppProjection;OTBSARCalibration;OTBAppSARCalibration;OTBCCOBIA;OTBSmoothing;OTBMeanShift;OTBMetrics;OTBMorphologicalProfiles;OTBLabelling;OTBOGRProcessing;OTBWatersheds;OTBAppSegmentation;OTBDEM;OTBStereo;OTBDisparityMap;OTBAppStereo;OTBAppTest;OTBTextures;OTBAppTextures;OTBAppVectorDataTranslation;OTBAppVectorUtils;OTBCommandLineParser;OTBOpenThreadsAdapters;OTBCloudDetection;OTBComplexImage;OTBCorner;OTBDensity;OTBDisplacementField;OTBLandSatClassifier;OTBLearningBase;OTBMarkov;OTBMorphologicalPyramid;OTBObjectDetection;OTBPolarimetry;OTBRoadExtraction;OTBRCC8;OTBSWIGWrapper;OTBSeamCarving;OTBSimulation;OTBTimeSeries;OTBUrbanArea") - - find_package(OTB REQUIRED COMPONENTS ${REQUIRED_MODULES}) - include(${OTB_USE_FILE}) - message(STATUS "Found OTB: ${OTB_USE_FILE}") - -else() - if(NOT OTB_BUILD_DEFAULT_MODULES) - message(FATAL_ERROR "BUILD_EXAMPLES requires OTB_BUILD_DEFAULT_MODULES to be ON") - endif() - # We also need to prevent any OTB_USE_XXX option to be OFF (except mapnik and openjpeg) - # For now we parse module activation list and test if option is ON. If not the cmake configuration stop. - #TODO We should provide a better mechanism here wich will deactivate only examples required by deactivated options. - foreach (_activationOption ${OTB_MODULE_ACTIVATION_OPTION_LIST}) - if(NOT ${_activationOption} AND NOT "x${_activationOption}" STREQUAL "xOTB_USE_MAPNIK" AND NOT "x${_activationOption}" STREQUAL "xOTB_USE_OPENJPEG") - message(FATAL_ERROR "BUILD_EXAMPLES requires ${_activationOption} to be ON") - endif() - endforeach() - - find_package(OTB REQUIRED) - include(${OTB_USE_FILE}) - message(STATUS "Found OTB: ${OTB_USE_FILE}") - endif() +find_package(OTB REQUIRED) +include(${OTB_USE_FILE}) +message(STATUS "Found OTB: ${OTB_USE_FILE}") + set(OTB_TEST_DRIVER otbTestDriver) if(OTBApplicationEngine_LOADED) diff --git a/Examples/ChangeDetection/KullbackLeiblerSupervizedDistanceChDet.cxx b/Examples/ChangeDetection/KullbackLeiblerSupervizedDistanceChDet.cxx index f892976f62dd27fcc5a468ac8644a13ba60aee67..b0bb7279127beed6cefd17c148468488426aac90 100644 --- a/Examples/ChangeDetection/KullbackLeiblerSupervizedDistanceChDet.cxx +++ b/Examples/ChangeDetection/KullbackLeiblerSupervizedDistanceChDet.cxx @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. - See GETCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Examples/Classification/CMakeLists.txt b/Examples/Classification/CMakeLists.txt index 4aa4757783949ef289edc2dac459ff6805d25e64..02db6fd752225dc4bbf2508b347b7c7257dfd155 100644 --- a/Examples/Classification/CMakeLists.txt +++ b/Examples/Classification/CMakeLists.txt @@ -6,9 +6,11 @@ target_link_libraries(BayesianPluginClassifier ${OTB_LIBRARIES}) add_executable(ClassificationMapRegularizationExample ClassificationMapRegularizationExample.cxx) target_link_libraries(ClassificationMapRegularizationExample ${OTB_LIBRARIES}) +#OTBDempsterShafer depends OTBMathParser. But OTB_USE_MUPARSER is OFF +if(OTBMathParser_LOADED) add_executable(DempsterShaferFusionOfClassificationMapsExample DempsterShaferFusionOfClassificationMapsExample.cxx) target_link_libraries(DempsterShaferFusionOfClassificationMapsExample ${OTB_LIBRARIES}) - +endif() add_executable(ExpectationMaximizationMixtureModelEstimator ExpectationMaximizationMixtureModelEstimator.cxx) target_link_libraries(ExpectationMaximizationMixtureModelEstimator ${OTB_LIBRARIES}) diff --git a/Examples/DisparityMap/CMakeLists.txt b/Examples/DisparityMap/CMakeLists.txt index bd7b2c26c86cd6fb2fdbfa84dbcc28f8f200ecbc..f42b945930e97fd1cfa30117302d08759a1dc44e 100644 --- a/Examples/DisparityMap/CMakeLists.txt +++ b/Examples/DisparityMap/CMakeLists.txt @@ -9,8 +9,11 @@ target_link_libraries(NCCRegistrationFilterExample ${OTB_LIBRARIES}) add_executable(SimpleDisparityMapEstimationExample SimpleDisparityMapEstimationExample.cxx) target_link_libraries(SimpleDisparityMapEstimationExample ${OTB_LIBRARIES}) +#StereoReconstructionExample depends OTBMathParser. But OTB_USE_MUPARSER is OFF +if(OTBMathParser_LOADED) add_executable(StereoReconstructionExample StereoReconstructionExample.cxx) target_link_libraries(StereoReconstructionExample ${OTB_LIBRARIES}) +endif() if(BUILD_TESTING) add_subdirectory(test) diff --git a/Examples/DisparityMap/test/CMakeLists.txt b/Examples/DisparityMap/test/CMakeLists.txt index d90913ccfcaca5de71692741ba78d7765020168b..9c247434b91ffb8e9116882b05e8538380ae513d 100644 --- a/Examples/DisparityMap/test/CMakeLists.txt +++ b/Examples/DisparityMap/test/CMakeLists.txt @@ -17,6 +17,7 @@ otb_add_test(NAME dmTeSimpleDisparityMapEstimationExampleTest COMMAND ${OTB_TEST 100 10 15 10 10 250 0.9 ) +if(OTBMathParser_LOADED) otb_add_test(NAME dmTeStereoReconstructionExampleTest COMMAND ${OTB_TEST_DRIVER} --compare-image ${NOTOL} ${BASELINE}/elevationOutput.tif @@ -28,3 +29,4 @@ otb_add_test(NAME dmTeStereoReconstructionExampleTest COMMAND ${OTB_TEST_DRIVER} ${TEMP}/elevationOutputPrintable.png 140 ) +endif() \ No newline at end of file diff --git a/Examples/FeatureExtraction/CMakeLists.txt b/Examples/FeatureExtraction/CMakeLists.txt index ec46f9fd89a8065e4ac0d0b713aca977c89311eb..edce7bf6fac9ecc829033a2531cf3be9d5f4957c 100644 --- a/Examples/FeatureExtraction/CMakeLists.txt +++ b/Examples/FeatureExtraction/CMakeLists.txt @@ -1,8 +1,5 @@ project(FeatureExtractionExamples) -add_executable(AlignmentsExample AlignmentsExample.cxx) -target_link_libraries(AlignmentsExample ${OTB_LIBRARIES}) - add_executable(AssymmetricFusionOfLineDetectorExample AssymmetricFusionOfLineDetectorExample.cxx) target_link_libraries(AssymmetricFusionOfLineDetectorExample ${OTB_LIBRARIES}) @@ -21,12 +18,21 @@ target_link_libraries(CorrelationLineDetectorExample ${OTB_LIBRARIES}) add_executable(EdgeDensityExample EdgeDensityExample.cxx) target_link_libraries(EdgeDensityExample ${OTB_LIBRARIES}) +#OTBRoadExtraction depends OTBMathParser. But OTB_USE_MUPARSER is OFF +if(OTBMathParser_LOADED) add_executable(ExtractRoadByStepsExample ExtractRoadByStepsExample.cxx) target_link_libraries(ExtractRoadByStepsExample ${OTB_LIBRARIES}) add_executable(ExtractRoadExample ExtractRoadExample.cxx) target_link_libraries(ExtractRoadExample ${OTB_LIBRARIES}) +add_executable(ParallelLineDetectionExample ParallelLineDetectionExample.cxx) +target_link_libraries(ParallelLineDetectionExample ${OTB_LIBRARIES}) + +add_executable(AlignmentsExample AlignmentsExample.cxx) +target_link_libraries(AlignmentsExample ${OTB_LIBRARIES}) +endif() + add_executable(ExtractSegmentsByStepsExample ExtractSegmentsByStepsExample.cxx) target_link_libraries(ExtractSegmentsByStepsExample ${OTB_LIBRARIES}) @@ -45,6 +51,9 @@ target_link_libraries(HuMomentsImageFunctionExample ${OTB_LIBRARIES}) if (Module_OTBVectorDataRendering AND OTB_USE_MAPNIK) add_executable(LineSegmentDetectorExample LineSegmentDetectorExample.cxx) target_link_libraries(LineSegmentDetectorExample ${OTB_LIBRARIES}) + + add_executable(RightAngleDetectionExample RightAngleDetectionExample.cxx) + target_link_libraries(RightAngleDetectionExample ${OTB_LIBRARIES}) endif() add_executable(LocalHoughExample LocalHoughExample.cxx) @@ -53,17 +62,9 @@ target_link_libraries(LocalHoughExample ${OTB_LIBRARIES}) add_executable(PanTexExample PanTexExample.cxx) target_link_libraries(PanTexExample ${OTB_LIBRARIES}) -add_executable(ParallelLineDetectionExample ParallelLineDetectionExample.cxx) -target_link_libraries(ParallelLineDetectionExample ${OTB_LIBRARIES}) - add_executable(RatioLineDetectorExample RatioLineDetectorExample.cxx) target_link_libraries(RatioLineDetectorExample ${OTB_LIBRARIES}) -if (Module_OTBVectorDataRendering AND OTB_USE_MAPNIK) - add_executable(RightAngleDetectionExample RightAngleDetectionExample.cxx) - target_link_libraries(RightAngleDetectionExample ${OTB_LIBRARIES}) -endif() - add_executable(SeamCarvingExample SeamCarvingExample.cxx) target_link_libraries(SeamCarvingExample ${OTB_LIBRARIES}) diff --git a/Examples/FeatureExtraction/test/CMakeLists.txt b/Examples/FeatureExtraction/test/CMakeLists.txt index 9e351acd2adf21b663afe76885b8baf7d868e91e..b748caca32cb41a2726011dc662e4836b98b86c2 100644 --- a/Examples/FeatureExtraction/test/CMakeLists.txt +++ b/Examples/FeatureExtraction/test/CMakeLists.txt @@ -107,7 +107,7 @@ otb_add_test(NAME feTeRatioLineDetectorExampleTest COMMAND ${OTB_TEST_DRIVER} ) # ------- AlignmentsExampleTest---------- - +if(OTBMathParser_LOADED) otb_add_test(NAME feTeAlignmentsExampleTest COMMAND ${OTB_TEST_DRIVER} --compare-n-images ${NOTOL} 1 ${BASELINE}/QB_SuburbAlign.png @@ -145,6 +145,8 @@ otb_add_test(NAME feTeExtractRoadExampleTest COMMAND ${OTB_TEST_DRIVER} 337 557 432 859 1.0 0.00005 1.0 0.39269 1.0 10.0 25. ) +endif() + # ------- SeamCarvingExamplesTest---------- otb_add_test(NAME feTeSeamCarvingExampleTest COMMAND ${OTB_TEST_DRIVER} diff --git a/Examples/IO/CMakeLists.txt b/Examples/IO/CMakeLists.txt index a3d9b9063fee339286f5cc7b487d49560cf437d1..b4395d43a10ab34ded19381a315d54c89537d8a5 100644 --- a/Examples/IO/CMakeLists.txt +++ b/Examples/IO/CMakeLists.txt @@ -30,8 +30,10 @@ target_link_libraries(ImageReadWrite ${OTB_LIBRARIES}) add_executable(ImageSeriesIOExample ImageSeriesIOExample.cxx) target_link_libraries(ImageSeriesIOExample ${OTB_LIBRARIES}) +if(OTBlibkml_LOADED) add_executable(ImageToKmzAndMapFileProductExample ImageToKmzAndMapFileProductExample.cxx) target_link_libraries(ImageToKmzAndMapFileProductExample ${OTB_LIBRARIES}) +endif() add_executable(MetadataExample MetadataExample.cxx) target_link_libraries(MetadataExample ${OTB_LIBRARIES}) diff --git a/Examples/IO/test/CMakeLists.txt b/Examples/IO/test/CMakeLists.txt index d75692eee9a507dd0f5587cf7b209beabfef4565..720b16203b632a95e2d850822f5d722a875c9653 100644 --- a/Examples/IO/test/CMakeLists.txt +++ b/Examples/IO/test/CMakeLists.txt @@ -43,6 +43,7 @@ otb_add_test(NAME prTeDEMHandlerExampleTest COMMAND ${OTB_TEST_DRIVER} 0.001 ) +if(OTBlibkml_LOADED) otb_add_test(NAME ioTeImageToKmzAndMapFileProductExample COMMAND ${OTB_TEST_DRIVER} Execute $<TARGET_FILE:ImageToKmzAndMapFileProductExample> ${OTB_DATA_ROOT}/Input/Haiti1_sr10.jpeg @@ -78,6 +79,7 @@ otb_add_test(NAME ioTeImageToKmzAndMapFileProductExample COMMAND ${OTB_TEST_DRIV 42.000000 232.000000 -72.426552 18.540876 0.000000 ) set_property(TEST ioTeImageToKmzAndMapFileProductExample PROPERTY RESOURCE_LOCK web_access) +endif() otb_add_test(NAME ioTeTileMapImageIOExampleTest COMMAND ${OTB_TEST_DRIVER} --compare-image 10.0 diff --git a/Examples/Learning/CMakeLists.txt b/Examples/Learning/CMakeLists.txt index 4963ecaed02cf4ac4a55240d66352d464e04d13b..cbf51262616e251ee86d0bd3c921ac35cd7b4d92 100644 --- a/Examples/Learning/CMakeLists.txt +++ b/Examples/Learning/CMakeLists.txt @@ -12,6 +12,7 @@ target_link_libraries(SOMClassifierExample ${OTB_LIBRARIES}) add_executable(SOMExample SOMExample.cxx) target_link_libraries(SOMExample ${OTB_LIBRARIES}) +if(OTBLibSVM_LOADED) add_executable(SVMImageClassificationExample SVMImageClassificationExample.cxx) target_link_libraries(SVMImageClassificationExample ${OTB_LIBRARIES}) @@ -29,13 +30,15 @@ target_link_libraries(SVMPointSetExample ${OTB_LIBRARIES}) add_executable(SVMPointSetModelEstimatorExample SVMPointSetModelEstimatorExample.cxx) target_link_libraries(SVMPointSetModelEstimatorExample ${OTB_LIBRARIES}) +endif() +if(OTBOpenCV_LOADED) add_executable(TrainMachineLearningModelFromImagesExample TrainMachineLearningModelFromImagesExample.cxx) target_link_libraries(TrainMachineLearningModelFromImagesExample ${OTB_LIBRARIES}) add_executable(TrainMachineLearningModelFromSamplesExample TrainMachineLearningModelFromSamplesExample.cxx) target_link_libraries(TrainMachineLearningModelFromSamplesExample ${OTB_LIBRARIES}) - +endif() if(BUILD_TESTING) add_subdirectory(test) diff --git a/Examples/Learning/SEMModelEstimatorExample.cxx b/Examples/Learning/SEMModelEstimatorExample.cxx index bb396e906359cb004045e14364768c9dd1657c49..86f3e58f967d80e4c73031f65bd4ad32af0b87e6 100644 --- a/Examples/Learning/SEMModelEstimatorExample.cxx +++ b/Examples/Learning/SEMModelEstimatorExample.cxx @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) GET / ENST Bretagne. All rights reserved. - See GETCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Examples/Learning/SOMExample.cxx b/Examples/Learning/SOMExample.cxx index 056820dd406bd89e45b4dcfb03e98a413e999487..3f56132f43b30be9ecbaeb790f6f1f38b8e8f6ae 100644 --- a/Examples/Learning/SOMExample.cxx +++ b/Examples/Learning/SOMExample.cxx @@ -10,7 +10,7 @@ See OTBCopyright.txt for details. Copyright (c) Institut Telecom; Telecom Bretagne. All rights reserved. - See GETCopyright.txt for details. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Examples/Learning/SVMGenericKernelImageClassificationExample.cxx b/Examples/Learning/SVMGenericKernelImageClassificationExample.cxx index e11095a98a716d217f337f4a825db1f3caa308dc..765fe1530831621159d1d11ddbdcb207419961a0 100644 --- a/Examples/Learning/SVMGenericKernelImageClassificationExample.cxx +++ b/Examples/Learning/SVMGenericKernelImageClassificationExample.cxx @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) GET / ENST Bretagne. All rights reserved. - See GETCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Examples/Learning/SVMGenericKernelImageModelEstimatorExample.cxx b/Examples/Learning/SVMGenericKernelImageModelEstimatorExample.cxx index 1e411f9cb66bc1ccc22577cf69d1b94c5a66441e..61494ba7c9b46ac17a52bec3ceac83f83ca1d5d5 100644 --- a/Examples/Learning/SVMGenericKernelImageModelEstimatorExample.cxx +++ b/Examples/Learning/SVMGenericKernelImageModelEstimatorExample.cxx @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) GET / ENST Bretagne. All rights reserved. - See GETCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Examples/Learning/test/CMakeLists.txt b/Examples/Learning/test/CMakeLists.txt index d3918e252e6901babd9924b0dc092e302acc99fb..71e51049f8a57ffdca32b7606c1bcc034e7e467f 100644 --- a/Examples/Learning/test/CMakeLists.txt +++ b/Examples/Learning/test/CMakeLists.txt @@ -3,6 +3,7 @@ set(INPUTDATA ${OTB_DATA_ROOT}/Examples) # ------- SVMImageClassificationExampleTest---------- +if(OTBLibSVM_LOADED) otb_add_test(NAME leTeSVMImageClassificationExampleTest COMMAND ${OTB_TEST_DRIVER} --compare-n-images ${NOTOL} 1 ${BASELINE}/ROI_QB_MUL_1_SVN_CLASS.png @@ -26,18 +27,6 @@ otb_add_test(NAME leTeSVMImageEstimatorClassificationMultiExampleTest COMMAND ${ ${TEMP}/ROI_QB_MUL_1_SVN_CLASS_MULTI_Rescaled.png ) -# ------- GenerateTrainingImageExampleTest---------- - -otb_add_test(NAME leTeGenerateTrainingImageExampleTest COMMAND ${OTB_TEST_DRIVER} - --compare-n-images ${NOTOL} 1 - ${BASELINE}/ROI_QB_MUL_4_training.png - ${TEMP}/ROI_QB_MUL_4_training.png - Execute $<TARGET_FILE:GenerateTrainingImageExample> - ${INPUTDATA}/ROI_QB_MUL_4.tif - ${INPUTDATA}/LearningROIs.txt - ${TEMP}/ROI_QB_MUL_4_training.png -) - # ------- SVMImageModelEstimatorExampleTest---------- otb_add_test(NAME leTeSVMImageModelEstimatorExampleTest COMMAND ${OTB_TEST_DRIVER} @@ -51,6 +40,18 @@ otb_add_test(NAME leTeSVMImageModelEstimatorExampleTest COMMAND ${OTB_TEST_DRIVE ${TEMP}/svm_image_model.svn ) +endif() +# ------- GenerateTrainingImageExampleTest---------- + +otb_add_test(NAME leTeGenerateTrainingImageExampleTest COMMAND ${OTB_TEST_DRIVER} + --compare-n-images ${NOTOL} 1 + ${BASELINE}/ROI_QB_MUL_4_training.png + ${TEMP}/ROI_QB_MUL_4_training.png + Execute $<TARGET_FILE:GenerateTrainingImageExample> + ${INPUTDATA}/ROI_QB_MUL_4.tif + ${INPUTDATA}/LearningROIs.txt + ${TEMP}/ROI_QB_MUL_4_training.png +) # ------- SOMExampleTest---------- diff --git a/Examples/OBIA/CMakeLists.txt b/Examples/OBIA/CMakeLists.txt index 202bd7ae29ce81a684e3b81211dd9ba8b3ff1cca..d2f7a79be47c7627549c03ac3f633fdaafb88fa9 100644 --- a/Examples/OBIA/CMakeLists.txt +++ b/Examples/OBIA/CMakeLists.txt @@ -12,8 +12,10 @@ target_link_libraries(KeepNObjects ${OTB_LIBRARIES}) add_executable(LabelMapToVectorData LabelMapToVectorData.cxx) target_link_libraries(LabelMapToVectorData ${OTB_LIBRARIES}) +if(OTBMathParser_LOADED) add_executable(RadiometricAttributesLabelMapFilterExample RadiometricAttributesLabelMapFilterExample.cxx) target_link_libraries(RadiometricAttributesLabelMapFilterExample ${OTB_LIBRARIES}) +endif() add_executable(ShapeAttributeComputation ShapeAttributeComputation.cxx) target_link_libraries(ShapeAttributeComputation ${OTB_LIBRARIES}) diff --git a/Examples/OBIA/test/CMakeLists.txt b/Examples/OBIA/test/CMakeLists.txt index 83a32c6339f4503a4fe36a72e982a6ea9bb559a5..f3c92b30ea3d96bd545bc5c333539db8274a8c5a 100644 --- a/Examples/OBIA/test/CMakeLists.txt +++ b/Examples/OBIA/test/CMakeLists.txt @@ -22,6 +22,7 @@ otb_add_test(NAME trTeOBIAShapeAttributeComputationTest COMMAND ${OTB_TEST_DRIVE ${TEMP}/OBIAShapeAttribute.txt ) +if(OTBMathParser_LOADED) otb_add_test(NAME trTeOBIARadiometricAttributesLabelMapFilterTest COMMAND ${OTB_TEST_DRIVER} --compare-image ${NOTOL} ${BASELINE}/OBIARadiometricAttributes.png @@ -38,6 +39,7 @@ otb_add_test(NAME trTeOBIARadiometricAttributesLabelMapFilterTest COMMAND ${OTB_ 50 1.0 ) +endif() otb_add_test(NAME trTeLabelMapToVectorData COMMAND ${OTB_TEST_DRIVER} Execute $<TARGET_FILE:LabelMapToVectorData> diff --git a/Examples/Patented/CMakeLists.txt b/Examples/Patented/CMakeLists.txt index 07210c89bb2bc23db170f3b3d57925bfca0143c3..8648e956aa89809bf1eb6c47c21b1a3436fd0ddf 100644 --- a/Examples/Patented/CMakeLists.txt +++ b/Examples/Patented/CMakeLists.txt @@ -3,18 +3,18 @@ project(PatentedExamples) add_executable(EstimateAffineTransformationExample EstimateAffineTransformationExample.cxx) target_link_libraries(EstimateAffineTransformationExample ${OTB_LIBRARIES}) +if (OTBSiftFast_LOADED) add_executable(SIFTDisparityMapEstimation SIFTDisparityMapEstimation.cxx) target_link_libraries(SIFTDisparityMapEstimation ${OTB_LIBRARIES}) add_executable(SIFTExample SIFTExample.cxx) target_link_libraries(SIFTExample ${OTB_LIBRARIES}) -if (Module_OTBSiftFast) - add_executable(SIFTDensityExample SIFTDensityExample.cxx) - target_link_libraries(SIFTDensityExample ${OTB_LIBRARIES}) +add_executable(SIFTDensityExample SIFTDensityExample.cxx) +target_link_libraries(SIFTDensityExample ${OTB_LIBRARIES}) - add_executable(SIFTFastExample SIFTFastExample.cxx) - target_link_libraries(SIFTFastExample ${OTB_LIBRARIES}) +add_executable(SIFTFastExample SIFTFastExample.cxx) +target_link_libraries(SIFTFastExample ${OTB_LIBRARIES}) endif() if(BUILD_TESTING) diff --git a/Examples/Projections/test/CMakeLists.txt b/Examples/Projections/test/CMakeLists.txt index 768d49630df27a20cf546cbf0dc2e9422ec8640a..fad74a593fa3d4bde04cde96b541e4be13827c86 100644 --- a/Examples/Projections/test/CMakeLists.txt +++ b/Examples/Projections/test/CMakeLists.txt @@ -48,7 +48,7 @@ otb_add_test(NAME prTeVectorDataProjectionExampleTest COMMAND ${OTB_TEST_DRIVER} ${BASELINE}/vectorDataProjectionExample.shp ${TEMP}/vectorDataProjectionExample.shp Execute $<TARGET_FILE:VectorDataProjectionExample> - ${OTB_DATA_ROOT}/Examples/Capitole-Shadows.kml + ${OTB_DATA_ROOT}/Input/Capitole-Shadows.kml LARGEINPUT{QUICKBIRD/TOULOUSE/000000128955_01_P001_PAN/02APR01105228-P1BS-000000128955_01_P001.TIF} ${TEMP}/vectorDataProjectionExample.shp ) @@ -58,7 +58,7 @@ otb_add_test(NAME prTeGeometriesProjectionTest COMMAND ${OTB_TEST_DRIVER} ${BASELINE}/geometriesProjectionExample.shp ${TEMP}/geometriesProjectionExample.shp Execute $<TARGET_FILE:GeometriesProjectionExample> - ${OTB_DATA_ROOT}/Examples/Capitole-Shadows.shp + ${OTB_DATA_ROOT}/Input/Capitole-Shadows.shp LARGEINPUT{QUICKBIRD/TOULOUSE/000000128955_01_P001_PAN/02APR01105228-P1BS-000000128955_01_P001.TIF} ${TEMP}/geometriesProjectionExample.shp ) @@ -88,6 +88,10 @@ otb_add_test(NAME prTeEstimateRPCSensorModelExampleTest COMMAND ${OTB_TEST_DRIVE 2803 1942 -22.958868 -42.808235 0. 980 2734 -22.99534 -43.309672 0. 713 2754 -23.007862 -43.365307 0. + 72 2955 -23.012153 -43.541331 0. + 2884 1898 -22.954691 -42.786188 0. + 2539 47 -22.616041 -42.777877 0. + 577 183 -22.551654 -43.271813 0. ) otb_add_test(NAME prTePlaceNameToLonLatExampleTest COMMAND ${OTB_TEST_DRIVER} diff --git a/Examples/Radiometry/CMakeLists.txt b/Examples/Radiometry/CMakeLists.txt index 1c1e1bd3de3339396735c49983ca9509886d2c69..48c5d40d071238dd5dcd547fe80ac56f095adb08 100644 --- a/Examples/Radiometry/CMakeLists.txt +++ b/Examples/Radiometry/CMakeLists.txt @@ -3,8 +3,11 @@ project(RadiometryExamples) add_executable(ARVIMultiChannelRAndBAndNIRVegetationIndexImageFilter ARVIMultiChannelRAndBAndNIRVegetationIndexImageFilter.cxx) target_link_libraries(ARVIMultiChannelRAndBAndNIRVegetationIndexImageFilter ${OTB_LIBRARIES}) +#OTBOpticalCalibration -> OTB6S +if(OTB6S_LOADED) add_executable(AtmosphericCorrectionSequencement AtmosphericCorrectionSequencement.cxx) target_link_libraries(AtmosphericCorrectionSequencement ${OTB_LIBRARIES}) +endif() add_executable(AVIMultiChannelRAndGAndNIRVegetationIndexImageFilter AVIMultiChannelRAndGAndNIRVegetationIndexImageFilter.cxx) target_link_libraries(AVIMultiChannelRAndGAndNIRVegetationIndexImageFilter ${OTB_LIBRARIES}) diff --git a/Examples/Radiometry/test/CMakeLists.txt b/Examples/Radiometry/test/CMakeLists.txt index ff18563ad9aff969b7e84a237a1efd7377c6235e..b77c8c87e51835fe4d227fbed00b77c68f78075c 100644 --- a/Examples/Radiometry/test/CMakeLists.txt +++ b/Examples/Radiometry/test/CMakeLists.txt @@ -52,6 +52,7 @@ otb_add_test(NAME raTeNDVIRAndNIRVegetationIndexImageFilterTest COMMAND ${OTB_TE ${TEMP}/NDVIRAndNIRVegetationIndex4.tif ) +if(OTBOpticalCalibration_LOADED) otb_add_test(NAME raTeAtmosphericCorrectionSequencementTest COMMAND ${OTB_TEST_DRIVER} --compare-image ${EPSILON_8} ${BASELINE}/Example_RomaniaAtmosphericCorrectionSequencement.tif @@ -82,3 +83,4 @@ otb_add_test(NAME raTeAtmosphericCorrectionSequencementTest COMMAND ${OTB_TEST_D 2 # Radius; 0.020 # pixel spacing in kilometers ) +endif() \ No newline at end of file diff --git a/Examples/Segmentation/CMakeLists.txt b/Examples/Segmentation/CMakeLists.txt index 4fb4b89300757a0a24a675165264b9dacfbc83e0..c8cda537c20a206fbb46e6b670948e1edfb0313b 100644 --- a/Examples/Segmentation/CMakeLists.txt +++ b/Examples/Segmentation/CMakeLists.txt @@ -24,8 +24,10 @@ target_link_libraries(OtsuMultipleThresholdImageFilter ${OTB_LIBRARIES}) add_executable(OtsuThresholdImageFilter OtsuThresholdImageFilter.cxx) target_link_libraries(OtsuThresholdImageFilter ${OTB_LIBRARIES}) -add_executable(StreamingMeanShiftSegmentation StreamingMeanShiftSegmentation.cxx) -target_link_libraries(StreamingMeanShiftSegmentation ${OTB_LIBRARIES}) +if(OTBMathParser_LOADED) + add_executable(StreamingMeanShiftSegmentation StreamingMeanShiftSegmentation.cxx) + target_link_libraries(StreamingMeanShiftSegmentation ${OTB_LIBRARIES}) +endif() add_executable(VectorConfidenceConnected VectorConfidenceConnected.cxx) target_link_libraries(VectorConfidenceConnected ${OTB_LIBRARIES}) diff --git a/Examples/Segmentation/test/CMakeLists.txt b/Examples/Segmentation/test/CMakeLists.txt index d43f19ecf89f64747f546278e5a09bb23e6806c2..37d36f1ca5f27611eb1e31dd3951dd2bc56ceb4b 100644 --- a/Examples/Segmentation/test/CMakeLists.txt +++ b/Examples/Segmentation/test/CMakeLists.txt @@ -272,7 +272,7 @@ otb_add_test(NAME seTeLabelizeNeighborhoodConnectedImageFilterTest COMMAND ${OTB # ------- StreamingMeanShiftSegmentationTest ---------- - +if(OTBMathParser_LOADED) otb_add_test(NAME seTeStreamingMeanShiftSegmentationTest COMMAND ${OTB_TEST_DRIVER} # --compare-ogr ${NOTOL} # ${BASELINE_FILES}/seTeStreamingMeanShiftSegmentationTest.shp @@ -291,3 +291,4 @@ otb_add_test(NAME seTeStreamingMeanShiftSegmentationTest COMMAND ${OTB_TEST_DRIV 1 #Simplify Flag 0.2 #Simplification tolerance ) +endif() \ No newline at end of file diff --git a/Examples/Simulation/CMakeLists.txt b/Examples/Simulation/CMakeLists.txt index ece736e87f61817c03a96ce358eebac6c368f355..0e0bc86b13a38327a5e71324c4972491e85c076e 100644 --- a/Examples/Simulation/CMakeLists.txt +++ b/Examples/Simulation/CMakeLists.txt @@ -1,14 +1,16 @@ project(SimulationExamples) +#OTBSimulation -> OTBOpticalCalibration -> OTB6S +if(OTB6S_LOADED) add_executable(LAIAndPROSAILToSensorResponse LAIAndPROSAILToSensorResponse.cxx) target_link_libraries(LAIAndPROSAILToSensorResponse ${OTB_LIBRARIES}) -add_executable(LAIFromNDVIImageTransform LAIFromNDVIImageTransform.cxx) -target_link_libraries(LAIFromNDVIImageTransform ${OTB_LIBRARIES}) - add_executable(ProsailModel ProsailModel.cxx) target_link_libraries(ProsailModel ${OTB_LIBRARIES}) +endif() +add_executable(LAIFromNDVIImageTransform LAIFromNDVIImageTransform.cxx) +target_link_libraries(LAIFromNDVIImageTransform ${OTB_LIBRARIES}) if(BUILD_TESTING) add_subdirectory(test) diff --git a/Examples/Simulation/test/CMakeLists.txt b/Examples/Simulation/test/CMakeLists.txt index eed146c98e2e69eb94b99f1bda805b50254f4821..9cb0323021507d2671a12e1af58e015a5d4a796d 100644 --- a/Examples/Simulation/test/CMakeLists.txt +++ b/Examples/Simulation/test/CMakeLists.txt @@ -3,6 +3,8 @@ set(INPUTDATA ${OTB_DATA_ROOT}/Examples) # ------- ProsailModelExampleTest ---------- +#OTBSimulation -> OTBOpticalCalibration -> OTB6S +if(OTB6S_LOADED) otb_add_test(NAME siTvProsailModelExampleTest COMMAND ${OTB_TEST_DRIVER} --compare-ascii ${EPSILON_3} ${BASELINE}/siTvProsailModelExampleTest.txt @@ -25,20 +27,6 @@ otb_add_test(NAME siTvProsailModelExampleTest COMMAND ${OTB_TEST_DRIVER} ${TEMP}/siTvProsailModelExampleTest.txt ) - -otb_add_test(NAME siTvLAIFromNDVIImageTransfromExampleTest COMMAND ${OTB_TEST_DRIVER} - --compare-image ${EPSILON_8} - ${OTB_DATA_ROOT}/Baseline/OTB/Images/raRAndNIRVegetationIndex_LAIFromNDVIFormosat2_verySmallFSATSWcRcNir.tif - ${TEMP}/siTvLAIFromNDVIImageTransfromExampleTest_verySmallFSATSW.tif - Execute $<TARGET_FILE:LAIFromNDVIImageTransform> - ${INPUTDATA}/verySmallFSATSW.tif - ${TEMP}/siTvLAIFromNDVIImageTransfromExampleTest_verySmallFSATSW.tif - ${TEMP}/verySmallFSATSW_visu.png - ${TEMP}/siTvLAIFromNDVIImageTransfromExampleTest_verySmallFSATSW_visu.png - 1 # red - 4 # nir -) - otb_add_test(NAME siTvLAIAndPROSAILToSensorResponseExampleTest COMMAND ${OTB_TEST_DRIVER} --compare-image ${EPSILON_8} ${OTBAPP_BASELINE}/siTvLAIAndPROSAILToSensorResponseSmall.tif @@ -54,3 +42,18 @@ Execute $<TARGET_FILE:LAIAndPROSAILToSensorResponse> 5 ${OTB_DATA_ROOT}/Input/ ) + +endif() + +otb_add_test(NAME siTvLAIFromNDVIImageTransfromExampleTest COMMAND ${OTB_TEST_DRIVER} + --compare-image ${EPSILON_8} + ${OTB_DATA_ROOT}/Baseline/OTB/Images/raRAndNIRVegetationIndex_LAIFromNDVIFormosat2_verySmallFSATSWcRcNir.tif + ${TEMP}/siTvLAIFromNDVIImageTransfromExampleTest_verySmallFSATSW.tif + Execute $<TARGET_FILE:LAIFromNDVIImageTransform> + ${INPUTDATA}/verySmallFSATSW.tif + ${TEMP}/siTvLAIFromNDVIImageTransfromExampleTest_verySmallFSATSW.tif + ${TEMP}/verySmallFSATSW_visu.png + ${TEMP}/siTvLAIFromNDVIImageTransfromExampleTest_verySmallFSATSW_visu.png + 1 # red + 4 # nir +) diff --git a/Modules/Adapters/BoostAdapters/include/otbStringUtils.h b/Modules/Adapters/BoostAdapters/include/otbStringUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..9c675f695fd19226845e538a84e4c6a4cba3cd7b --- /dev/null +++ b/Modules/Adapters/BoostAdapters/include/otbStringUtils.h @@ -0,0 +1,130 @@ +/*========================================================================= + + Program: ORFEO Toolbox + Language: C++ + Date: $Date$ + Version: $Revision$ + + + Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. + See OTBCopyright.txt for details. + + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef otbStringUtils_h +#define otbStringUtils_h + +#include <string> +#include <vector> +#include <limits> +#include <stdexcept> +#include <boost/lexical_cast.hpp> +#include <boost/algorithm/string.hpp> +#include <boost/algorithm/string/predicate.hpp> +#include <boost/utility/enable_if.hpp> + +namespace otb +{ +namespace Utils +{ +template <typename Res, typename In > +inline +Res LexicalCast(In const& in, std::string const& kind) { + try + { + return boost::lexical_cast<Res>(in); + } + catch (boost::bad_lexical_cast &) { + std::ostringstream oss; + oss << "Cannot decode " << in << " as this is not a valid value for " << kind; + throw std::runtime_error(oss.str()); + } +} + +/**\ingroup Utils + * Converts a delimiter separated string into a collection of \c T's. + * \tparam Collection type. It shall define \c value_type and \c push_back() + * \param[out] ret output collection. + * \param[in] str input string + * \param[in] errmsg a msg complement used to build the error message to +be shown if there is \c lexical_cast exception. See \c +otb:Utils::LexicalCast(). + * \param delims delimitter characters (space is default) + * \throw std::bad_alloc in case of exhausted memory + * \throw std::runtime_error in case an element from the input string +cannot be converted into a valid \c T instance. + * \pre delims shall not be null (untested) + * + * \see \c otb::Utils::LexicalCast() + */ +template<typename T> +void +ConvertStringToVector(std::string const &str, T& ret, std::string const& errmsg, const char * delims=" ") +{ + typedef std::vector<boost::iterator_range<std::string::const_iterator> > ListType; + + ListType splitted; + + boost::split(splitted, str, boost::is_any_of(delims)); + + for(size_t i = 0; i < splitted.size(); i++) + { + typename T::value_type value = LexicalCast<typename T::value_type> (splitted[i], errmsg); + ret.push_back(value); + } +} + +/**\ingroup Utils + * split a given std::string of into key value based on given delimitter + * string. default delimitter is '='. If the string does not have a delimitter + * the key is set to input string and value is set to defValue. + * \param[in] str input string + * \param key[out] An std::string reference where key will be stored + * \param value[out] a reference of \cT where value will be stored + * \param defValue[in] a default value if there is no delimitter fo + * \param[in] errmsg a msg complement used to build the error message to +be shown if there is \c lexical_cast exception. See \cotb:Utils::LexicalCast(). + * \param delims delimitter characters (space is default) + * \throw std::bad_alloc in case of exhausted memory + * \throw std::runtime_error in case an element from the input string +cannot be converted into a valid \c T instance. + * \pre delims shall not be null (untested) + * + * \see \c otb::Utils::LexicalCast() + */ +template<typename T> +void SplitStringToSingleKeyValue(const std::string& str, + std::string& key, T& value, const T& defValue, + std::string const& errmsg, const std::string delims="=") +{ + + typedef boost::iterator_range<std::string::const_iterator> BoostRangeIteratorType; + typedef std::list< BoostRangeIteratorType > ListType; + + ListType splitted; + + boost::split( splitted, str, boost::is_any_of(delims), boost::token_compress_on ); + + typename ListType::iterator it = splitted.begin(); + BoostRangeIteratorType kIt = boost::trim_copy((*it)); + key.assign( kIt.begin(), kIt.end()); + ++it; + + if( it != splitted.end()) + { + value = LexicalCast<T>(boost::trim_copy(*it), errmsg); + ++it; + } + else + { + value = defValue; + } +} +} // end namespace Utils +} // end namespace otb + +#endif //otbStringUtils_h diff --git a/Modules/Adapters/OSSIMAdapters/include/otbDEMHandler.h b/Modules/Adapters/OSSIMAdapters/include/otbDEMHandler.h index 528144e916d3c06135cdb501bd37487718c5042d..7e51a0c79178a1e1e0489cd45eb0c797e6311343 100644 --- a/Modules/Adapters/OSSIMAdapters/include/otbDEMHandler.h +++ b/Modules/Adapters/OSSIMAdapters/include/otbDEMHandler.h @@ -107,9 +107,29 @@ public: /** return true if the directoty contain DEM */ virtual bool IsValidDEMDirectory(const char* DEMDirectory); - /** Open geoid file. */ - virtual void OpenGeoidFile(const char* geoidFile); - virtual void OpenGeoidFile(const std::string& geoidFile); + /** + * \brief Open geoid file given its filename or throw an exception + * if geoid-file could not be loaded. + * + * \param geoidFile The filename of the geoid-file. + * + * \return <code>true</code> if geoid file has been changed or + * <code>false</code> if geod-file have been set before and could + * not be changed. + */ + virtual bool OpenGeoidFile(const char* geoidFile); + + /** + * \brief Open geoid file given its filename or throw an exception + * if geoid-file could not be loaded. + * + * \param geoidFile The filename of the geoid-file. + * + * \return <code>true</code> if geoid file has been changed or + * <code>false</code> if geod-file have been set before and could + * not be changed. + */ + virtual bool OpenGeoidFile(const std::string& geoidFile); /** Compute the height above MSL(Mean Sea Level) of a geographic point. */ virtual double GetHeightAboveMSL(double lon, double lat) const; @@ -125,6 +145,11 @@ public: /** Set the default height above ellipsoid in case no information is available*/ double GetDefaultHeightAboveEllipsoid() const; + /** + * \return The number of elevation databases in the + * <code>ossimElevManager</code>. + */ + unsigned int GetDEMCount() const; /** Get DEM directory */ std::string GetDEMDirectory(unsigned int idx = 0) const; @@ -132,14 +157,18 @@ public: /** Get Goid file */ std::string GetGeoidFile() const; + /** + * \brief Remove all the ossimElevationDatabases from the + * <code>ossimElevManager</code>. + */ + void ClearDEMs(); + protected: DEMHandler(); virtual ~DEMHandler() {} void PrintSelf(std::ostream& os, itk::Indent indent) const; - ossimElevManager* m_ElevManager; - // Ossim does not allow to retrieve the geoid file path // We therefore must keep it on our side std::string m_GeoidFile; diff --git a/Modules/Adapters/OSSIMAdapters/src/otbDEMHandler.cxx b/Modules/Adapters/OSSIMAdapters/src/otbDEMHandler.cxx index 79b352417c22648288dc5a537bf99707a5f24a09..71b94952260fdcba5b6ed9f65a784976b1eaa3e1 100644 --- a/Modules/Adapters/OSSIMAdapters/src/otbDEMHandler.cxx +++ b/Modules/Adapters/OSSIMAdapters/src/otbDEMHandler.cxx @@ -18,6 +18,8 @@ #include "otbDEMHandler.h" #include "otbMacro.h" +#include <cassert> + #include "ossim/elevation/ossimElevManager.h" #include "ossim/base/ossimGeoidManager.h" #include "ossim/base/ossimFilename.h" @@ -49,23 +51,25 @@ DEMHandler::Pointer DEMHandler::Instance() DEMHandler ::DEMHandler() : - m_ElevManager(ossimElevManager::instance()), m_GeoidFile(""), m_DefaultHeightAboveEllipsoid(0) { - m_ElevManager->setDefaultHeightAboveEllipsoid(m_DefaultHeightAboveEllipsoid); + assert( ossimElevManager::instance()!=NULL ); + + ossimElevManager::instance()->setDefaultHeightAboveEllipsoid(m_DefaultHeightAboveEllipsoid); // Force geoid fallback - m_ElevManager->setUseGeoidIfNullFlag(true); + ossimElevManager::instance()->setUseGeoidIfNullFlag(true); } void DEMHandler ::OpenDEMDirectory(const char* DEMDirectory) { - ossimFilename ossimDEMDir; - ossimDEMDir = ossimFilename(DEMDirectory); + assert( ossimElevManager::instance()!=NULL ); + + ossimFilename ossimDEMDir( DEMDirectory ); - if (!m_ElevManager->loadElevationPath(ossimDEMDir)) + if (!ossimElevManager::instance()->loadElevationPath(ossimDEMDir)) { // In ossim elevation database factory code, the // ossimImageElevationDatabase is explicitly disabled by a #if 0 @@ -82,11 +86,22 @@ DEMHandler else { otbMsgDevMacro(<< "DEM directory contains general elevation image files: " << ossimDEMDir); - m_ElevManager->addDatabase(imageElevationDatabase.get()); + ossimElevManager::instance()->addDatabase(imageElevationDatabase.get()); } } } + +void +DEMHandler +::ClearDEMs() +{ + assert( ossimElevManager::instance()!=NULL ); + + ossimElevManager::instance()->clear(); +} + + void DEMHandler ::OpenDEMDirectory(const std::string& DEMDirectory) @@ -98,8 +113,10 @@ bool DEMHandler ::IsValidDEMDirectory(const char* DEMDirectory) { + assert( ossimElevManager::instance()!=NULL ); + //Try to load elevation source - bool result = m_ElevManager->loadElevationPath(DEMDirectory); + bool result = ossimElevManager::instance()->loadElevationPath(DEMDirectory); if (!result) { @@ -111,7 +128,7 @@ DEMHandler return result; } -void +bool DEMHandler ::OpenGeoidFile(const char* geoidFile) { @@ -131,22 +148,31 @@ DEMHandler // The previous flag will be ignored if // defaultHeightAboveEllipsoid is not NaN - m_ElevManager->setDefaultHeightAboveEllipsoid(ossim::nan()); + assert( ossimElevManager::instance()!=NULL ); + ossimElevManager::instance()->setDefaultHeightAboveEllipsoid(ossim::nan()); + + return true; } else { otbMsgDevMacro(<< "Failure opening geoid"); geoidPtr.release(); + + itkExceptionMacro( << "Failed to open geoid file: '" << geoidFile << "'" ); + + return false; } } + + return false; } -void +bool DEMHandler ::OpenGeoidFile(const std::string& geoidFile) { - OpenGeoidFile(geoidFile.c_str()); + return OpenGeoidFile(geoidFile.c_str()); } double @@ -155,9 +181,14 @@ DEMHandler { double height; ossimGpt ossimWorldPoint; + ossimWorldPoint.lon = lon; ossimWorldPoint.lat = lat; - height = m_ElevManager->getHeightAboveMSL(ossimWorldPoint); + + assert( ossimElevManager::instance()!=NULL ); + + height = ossimElevManager::instance()->getHeightAboveMSL(ossimWorldPoint); + return height; } @@ -174,9 +205,13 @@ DEMHandler { double height; ossimGpt ossimWorldPoint; + ossimWorldPoint.lon = lon; ossimWorldPoint.lat = lat; - height = m_ElevManager->getHeightAboveEllipsoid(ossimWorldPoint); + + assert( ossimElevManager::instance()!=NULL ); + + height = ossimElevManager::instance()->getHeightAboveEllipsoid(ossimWorldPoint); return height; } @@ -195,7 +230,10 @@ DEMHandler // Ossim does not allow to retrieve the default height above // ellipsoid We therefore must keep it on our side m_DefaultHeightAboveEllipsoid = h; - m_ElevManager->setDefaultHeightAboveEllipsoid(h); + + assert( ossimElevManager::instance()!=NULL ); + + ossimElevManager::instance()->setDefaultHeightAboveEllipsoid(h); } double @@ -207,13 +245,24 @@ DEMHandler return m_DefaultHeightAboveEllipsoid; } +unsigned int +DEMHandler +::GetDEMCount() const +{ + assert( ossimElevManager::instance()!=NULL ); + + return ossimElevManager::instance()->getNumberOfElevationDatabases(); +} + std::string DEMHandler::GetDEMDirectory(unsigned int idx) const { std::string demDir = ""; - if(m_ElevManager->getNumberOfElevationDatabases() > 0) + if(ossimElevManager::instance()->getNumberOfElevationDatabases() > 0) { - demDir = m_ElevManager->getElevationDatabase(idx)->getConnectionString().string(); + assert( ossimElevManager::instance()!=NULL ); + + demDir = ossimElevManager::instance()->getElevationDatabase(idx)->getConnectionString().string(); } return demDir; } diff --git a/Modules/Adapters/OSSIMAdapters/src/otbImageKeywordlist.cxx b/Modules/Adapters/OSSIMAdapters/src/otbImageKeywordlist.cxx index 0a0309e5f3dba0a46c02262d9a6529903f4fd798..98d873885e84be567549957fb78fa6985d72e2ee 100644 --- a/Modules/Adapters/OSSIMAdapters/src/otbImageKeywordlist.cxx +++ b/Modules/Adapters/OSSIMAdapters/src/otbImageKeywordlist.cxx @@ -139,41 +139,51 @@ bool ImageKeywordlist:: convertToGDALRPC(GDALRPCInfo &rpc) const { - ossimKeywordlist geom_kwl; - - this->convertToOSSIMKeywordlist(geom_kwl); - - if( geom_kwl.hasKey("polynomial_format")) //RK - { - ossimRefPtr<ossimRpcModel> rpcModel = new ossimRpcModel; - if (rpcModel->loadState(geom_kwl)) - { - ossimRpcModel::rpcModelStruct ossimRpcStruct; - rpcModel->getRpcParameters(ossimRpcStruct); + /* ossimRpcModel::loadState() actually expects certain keyword values to be + * present in the keywordlist. So We check a single keyword value + * (polynomial_format) first. Even though it is not enough to ensure a valid + * ossimRpcModel by checking for presence of one single key but atleast we + * are sure about not to create an ossimRpcModel. + * + * The current mechanism creates ossimRpcModel instance, calls loadState() + * and fails. The below check for 'polynomial_format' save us from creating + * an ossimRpcModel which will be invalid if the 'polynomial_format' is not + * present. + */ + if( m_Keywordlist.find("polynomial_format") != m_Keywordlist.end() ) + { + ossimKeywordlist geom_kwl; + this->convertToOSSIMKeywordlist(geom_kwl); - if (ossimRpcStruct.type == 'B') + ossimRefPtr<ossimRpcModel> rpcModel = new ossimRpcModel; + if (rpcModel->loadState(geom_kwl)) { - rpc.dfSAMP_OFF = ossimRpcStruct.sampOffset; - rpc.dfLINE_OFF = ossimRpcStruct.lineOffset; - rpc.dfSAMP_SCALE = ossimRpcStruct.sampScale; - rpc.dfLINE_SCALE = ossimRpcStruct.lineScale; - rpc.dfLAT_OFF = ossimRpcStruct.latOffset; - rpc.dfLONG_OFF = ossimRpcStruct.lonOffset; - rpc.dfHEIGHT_OFF = ossimRpcStruct.hgtOffset; - rpc.dfLAT_SCALE = ossimRpcStruct.latScale; - rpc.dfLONG_SCALE = ossimRpcStruct.lonScale; - rpc.dfHEIGHT_SCALE = ossimRpcStruct.hgtScale; - - memcpy(rpc.adfLINE_NUM_COEFF, ossimRpcStruct.lineNumCoef, sizeof(double) * 20); - memcpy(rpc.adfLINE_DEN_COEFF, ossimRpcStruct.lineDenCoef, sizeof(double) * 20); - memcpy(rpc.adfSAMP_NUM_COEFF, ossimRpcStruct.sampNumCoef, sizeof(double) * 20); - memcpy(rpc.adfSAMP_DEN_COEFF, ossimRpcStruct.sampDenCoef, sizeof(double) * 20); - - return true; + ossimRpcModel::rpcModelStruct ossimRpcStruct; + rpcModel->getRpcParameters(ossimRpcStruct); + + if (ossimRpcStruct.type == 'B') + { + rpc.dfSAMP_OFF = ossimRpcStruct.sampOffset; + rpc.dfLINE_OFF = ossimRpcStruct.lineOffset; + rpc.dfSAMP_SCALE = ossimRpcStruct.sampScale; + rpc.dfLINE_SCALE = ossimRpcStruct.lineScale; + rpc.dfLAT_OFF = ossimRpcStruct.latOffset; + rpc.dfLONG_OFF = ossimRpcStruct.lonOffset; + rpc.dfHEIGHT_OFF = ossimRpcStruct.hgtOffset; + rpc.dfLAT_SCALE = ossimRpcStruct.latScale; + rpc.dfLONG_SCALE = ossimRpcStruct.lonScale; + rpc.dfHEIGHT_SCALE = ossimRpcStruct.hgtScale; + + memcpy(rpc.adfLINE_NUM_COEFF, ossimRpcStruct.lineNumCoef, sizeof(double) * 20); + memcpy(rpc.adfLINE_DEN_COEFF, ossimRpcStruct.lineDenCoef, sizeof(double) * 20); + memcpy(rpc.adfSAMP_NUM_COEFF, ossimRpcStruct.sampNumCoef, sizeof(double) * 20); + memcpy(rpc.adfSAMP_DEN_COEFF, ossimRpcStruct.sampDenCoef, sizeof(double) * 20); + + return true; + } } - } - } - return false; + } + return false; } void diff --git a/Modules/Adapters/OSSIMAdapters/test/CMakeLists.txt b/Modules/Adapters/OSSIMAdapters/test/CMakeLists.txt index d11608709f0552643a238bb01042453df869e9d2..42440cd9a65cea1d85f0099a6ba1760664f64e8e 100644 --- a/Modules/Adapters/OSSIMAdapters/test/CMakeLists.txt +++ b/Modules/Adapters/OSSIMAdapters/test/CMakeLists.txt @@ -441,6 +441,7 @@ otb_add_test(NAME uaTvDEMHandler_AboveEllipsoid_SRTM_BadGeoid COMMAND otbOSSIMAd 339.513 0.001 ) +set_property(TEST uaTvDEMHandler_AboveEllipsoid_SRTM_BadGeoid PROPERTY WILL_FAIL true) otb_add_test(NAME uaTvDEMHandler_AboveMSL_SRTM_NoGeoid_NoData COMMAND otbOSSIMAdaptersTestDriver otbDEMHandlerTest diff --git a/Modules/Adapters/OSSIMAdapters/test/otbDEMHandlerTest.cxx b/Modules/Adapters/OSSIMAdapters/test/otbDEMHandlerTest.cxx index 9987db6a5bcd5cd74ac0793cd8e5b0aaea5261f2..09ab37cf7c098c990a0668f176099eda0109ab94 100644 --- a/Modules/Adapters/OSSIMAdapters/test/otbDEMHandlerTest.cxx +++ b/Modules/Adapters/OSSIMAdapters/test/otbDEMHandlerTest.cxx @@ -59,7 +59,19 @@ int otbDEMHandlerTest(int argc, char * argv[]) if(geoid != "no") { - demHandler->OpenGeoidFile(geoid); + try + { + demHandler->OpenGeoidFile(geoid); + } + catch( const std::exception & exception ) + { + std::cout + << "Exception thrown while opening geod-file '" << geoid << "':" << std::endl + << exception.what(); + + fail = true; + } + std::cout<<"GetGeoidFile() = "<<demHandler->GetGeoidFile()<<std::endl; } diff --git a/Modules/Applications/AppClassification/app/CMakeLists.txt b/Modules/Applications/AppClassification/app/CMakeLists.txt index 7613f5a2612a7c62bfe8ecc648dab3f8b0b40436..692aa710eba22f1cf1274dcd08171c063764c9b1 100644 --- a/Modules/Applications/AppClassification/app/CMakeLists.txt +++ b/Modules/Applications/AppClassification/app/CMakeLists.txt @@ -65,16 +65,19 @@ otb_create_application( SOURCES otbKMeansClassification.cxx LINK_LIBRARIES ${${otb-module}_LIBRARIES}) -set(TrainImagesClassifier_SRC - otbTrainSVM.cxx otbTrainBoost.cxx otbTrainDecisionTree.cxx - otbTrainGradientBoostedTree.cxx otbTrainNeuralNetwork.cxx - otbTrainNormalBayes.cxx otbTrainRandomForests.cxx otbTrainKNN.cxx - otbTrainLibSVM.cxx - otbTrainImagesClassifier.cxx) - otb_create_application( NAME TrainImagesClassifier - SOURCES ${TrainImagesClassifier_SRC} + SOURCES otbTrainImagesClassifier.cxx + LINK_LIBRARIES ${${otb-module}_LIBRARIES}) + +otb_create_application( + NAME TrainRegression + SOURCES otbTrainRegression.cxx + LINK_LIBRARIES ${${otb-module}_LIBRARIES}) + +otb_create_application( + NAME PredictRegression + SOURCES otbPredictRegression.cxx LINK_LIBRARIES ${${otb-module}_LIBRARIES}) otb_create_application( diff --git a/Modules/Applications/AppClassification/app/otbPredictRegression.cxx b/Modules/Applications/AppClassification/app/otbPredictRegression.cxx new file mode 100644 index 0000000000000000000000000000000000000000..413d70f05d08d50efaef54a0bd38e0c58bd1ca7d --- /dev/null +++ b/Modules/Applications/AppClassification/app/otbPredictRegression.cxx @@ -0,0 +1,275 @@ +/*========================================================================= + + Program: ORFEO Toolbox + Language: C++ + Date: $Date$ + Version: $Revision$ + + + Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. + See OTBCopyright.txt for details. + + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#include "otbWrapperApplication.h" +#include "otbWrapperApplicationFactory.h" + +#include "itkUnaryFunctorImageFilter.h" +#include "otbChangeLabelImageFilter.h" +#include "otbStandardWriterWatcher.h" +#include "otbStatisticsXMLFileReader.h" +#include "otbShiftScaleVectorImageFilter.h" +#include "otbImageClassificationFilter.h" +#include "otbMultiToMonoChannelExtractROI.h" +#include "otbImageToVectorImageCastFilter.h" +#include "otbMachineLearningModelFactory.h" + +namespace otb +{ +namespace Functor +{ +/** + * simple affine function : y = ax+b + */ +template<class TInput, class TOutput> +class AffineFunctor +{ +public: + typedef double InternalType; + + // constructor + AffineFunctor() : m_A(1.0),m_B(0.0) {} + + // destructor + virtual ~AffineFunctor() {} + + void SetA(InternalType a) + { + m_A = a; + } + + void SetB(InternalType b) + { + m_B = b; + } + + inline TOutput operator()(const TInput & x) const + { + return static_cast<TOutput>( static_cast<InternalType>(x)*m_A + m_B); + } +private: + InternalType m_A; + InternalType m_B; +}; + +} + +namespace Wrapper +{ + +class PredictRegression : public Application +{ +public: + /** Standard class typedefs. */ + typedef PredictRegression Self; + typedef Application Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** Standard macro */ + itkNewMacro(Self); + + itkTypeMacro(PredictRegression, otb::Application); + + /** Filters typedef */ + typedef UInt8ImageType MaskImageType; + typedef itk::VariableLengthVector<FloatVectorImageType::InternalPixelType> MeasurementType; + typedef otb::StatisticsXMLFileReader<MeasurementType> StatisticsReader; + typedef otb::ShiftScaleVectorImageFilter<FloatVectorImageType, FloatVectorImageType> RescalerType; + typedef itk::UnaryFunctorImageFilter< + FloatImageType, + FloatImageType, + otb::Functor::AffineFunctor<float,float> > OutputRescalerType; + typedef otb::ImageClassificationFilter<FloatVectorImageType, FloatImageType, MaskImageType> ClassificationFilterType; + typedef ClassificationFilterType::Pointer ClassificationFilterPointerType; + typedef ClassificationFilterType::ModelType ModelType; + typedef ModelType::Pointer ModelPointerType; + typedef ClassificationFilterType::ValueType ValueType; + typedef ClassificationFilterType::LabelType LabelType; + typedef otb::MachineLearningModelFactory<ValueType, LabelType> MachineLearningModelFactoryType; + +private: + void DoInit() + { + SetName("PredictRegression"); + SetDescription("Performs a prediction of the input image according to a regression model file."); + + // Documentation + SetDocName("Predict Regression"); + SetDocLongDescription("This application predict output values from an input" + " image, based on a regression model file produced by" + " the TrainRegression application. Pixels of the " + "output image will contain the predicted values from" + "the regression model (single band). The input pixels" + " can be optionally centered and reduced according " + "to the statistics file produced by the " + "ComputeImagesStatistics application. An optional " + "input mask can be provided, in which case only " + "input image pixels whose corresponding mask value " + "is greater than 0 will be processed. The remaining" + " of pixels will be given the value 0 in the output" + " image."); + + SetDocLimitations("The input image must contain the feature bands used for" + " the model training (without the predicted value). " + "If a statistics file was used during training by the " + "TrainRegression, it is mandatory to use the same " + "statistics file for prediction. If an input mask is " + "used, its size must match the input image size."); + SetDocAuthors("OTB-Team"); + SetDocSeeAlso("TrainRegression, ComputeImagesStatistics"); + + AddDocTag(Tags::Learning); + + AddParameter(ParameterType_InputImage, "in", "Input Image"); + SetParameterDescription( "in", "The input image to predict."); + + // TODO : use CSV input/output ? + + AddParameter(ParameterType_InputImage, "mask", "Input Mask"); + SetParameterDescription( "mask", "The mask allows to restrict " + "classification of the input image to the area where mask pixel values " + "are greater than 0."); + MandatoryOff("mask"); + + AddParameter(ParameterType_InputFilename, "model", "Model file"); + SetParameterDescription("model", "A regression model file (produced by " + "TrainRegression application)."); + + AddParameter(ParameterType_InputFilename, "imstat", "Statistics file"); + SetParameterDescription("imstat", "A XML file containing mean and standard" + " deviation to center and reduce samples before prediction " + "(produced by ComputeImagesStatistics application). If this file contains" + "one more band than the sample size, the last stat of last band will be" + "applied to expand the output predicted value"); + MandatoryOff("imstat"); + + AddParameter(ParameterType_OutputImage, "out", "Output Image"); + SetParameterDescription( "out", "Output image containing predicted values"); + + AddRAMParameter(); + + // Doc example parameter settings + SetDocExampleParameterValue("in", "QB_1_ortho.tif"); + SetDocExampleParameterValue("imstat", "EstimateImageStatisticsQB1.xml"); + SetDocExampleParameterValue("model", "clsvmModelQB1.svm"); + SetDocExampleParameterValue("out", "clLabeledImageQB1.tif"); + } + + void DoUpdateParameters() + { + // Nothing to do here : all parameters are independent + } + + void DoExecute() + { + // Load input image + FloatVectorImageType::Pointer inImage = GetParameterImage("in"); + inImage->UpdateOutputInformation(); + unsigned int nbFeatures = inImage->GetNumberOfComponentsPerPixel(); + + // Load svm model + otbAppLogINFO("Loading model"); + m_Model = MachineLearningModelFactoryType::CreateMachineLearningModel(GetParameterString("model"), + MachineLearningModelFactoryType::ReadMode); + + if (m_Model.IsNull()) + { + otbAppLogFATAL(<< "Error when loading model " << GetParameterString("model") << " : unsupported model type"); + } + + m_Model->Load(GetParameterString("model")); + m_Model->SetRegressionMode(true); + otbAppLogINFO("Model loaded"); + + // Classify + m_ClassificationFilter = ClassificationFilterType::New(); + m_ClassificationFilter->SetModel(m_Model); + + FloatImageType::Pointer outputImage = m_ClassificationFilter->GetOutput(); + + // Normalize input image if asked + if(IsParameterEnabled("imstat") ) + { + otbAppLogINFO("Input image normalization activated."); + // Normalize input image (optional) + StatisticsReader::Pointer statisticsReader = StatisticsReader::New(); + MeasurementType meanMeasurementVector; + MeasurementType stddevMeasurementVector; + m_Rescaler = RescalerType::New(); + // Load input image statistics + statisticsReader->SetFileName(GetParameterString("imstat")); + meanMeasurementVector = statisticsReader->GetStatisticVectorByName("mean"); + stddevMeasurementVector = statisticsReader->GetStatisticVectorByName("stddev"); + otbAppLogINFO( "mean used: " << meanMeasurementVector ); + otbAppLogINFO( "standard deviation used: " << stddevMeasurementVector ); + if (meanMeasurementVector.Size() == nbFeatures + 1) + { + double outMean = meanMeasurementVector[nbFeatures]; + double outStdDev = stddevMeasurementVector[nbFeatures]; + meanMeasurementVector.SetSize(nbFeatures,false); + stddevMeasurementVector.SetSize(nbFeatures,false); + m_OutRescaler = OutputRescalerType::New(); + m_OutRescaler->SetInput(m_ClassificationFilter->GetOutput()); + m_OutRescaler->GetFunctor().SetA(outStdDev); + m_OutRescaler->GetFunctor().SetB(outMean); + outputImage = m_OutRescaler->GetOutput(); + } + else if (meanMeasurementVector.Size() != nbFeatures) + { + otbAppLogFATAL("Wrong number of components in statistics file : "<<meanMeasurementVector.Size()); + } + + // Rescale vector image + m_Rescaler->SetScale(stddevMeasurementVector); + m_Rescaler->SetShift(meanMeasurementVector); + m_Rescaler->SetInput(inImage); + + m_ClassificationFilter->SetInput(m_Rescaler->GetOutput()); + } + else + { + otbAppLogINFO("Input image normalization deactivated."); + m_ClassificationFilter->SetInput(inImage); + } + + + if(IsParameterEnabled("mask")) + { + otbAppLogINFO("Using input mask"); + // Load mask image and cast into LabeledImageType + MaskImageType::Pointer inMask = GetParameterUInt8Image("mask"); + + m_ClassificationFilter->SetInputMask(inMask); + } + + SetParameterOutputImage<FloatImageType>("out", outputImage); + + } + + ClassificationFilterType::Pointer m_ClassificationFilter; + ModelPointerType m_Model; + RescalerType::Pointer m_Rescaler; + OutputRescalerType::Pointer m_OutRescaler; + +}; + + +} +} + +OTB_APPLICATION_EXPORT(otb::Wrapper::PredictRegression) diff --git a/Modules/Applications/AppClassification/app/otbTrainImagesClassifier.cxx b/Modules/Applications/AppClassification/app/otbTrainImagesClassifier.cxx index 1b9358f04832bed66ec463d1510fbb371ea2a3de..de1520dfca4855e523513f8a4542a95bff1cde84 100644 --- a/Modules/Applications/AppClassification/app/otbTrainImagesClassifier.cxx +++ b/Modules/Applications/AppClassification/app/otbTrainImagesClassifier.cxx @@ -14,15 +14,95 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ +#include "otbLearningApplicationBase.h" +#include "otbWrapperApplicationFactory.h" -#include "otbTrainImagesClassifier.h" +#include "otbListSampleGenerator.h" + +// Statistic XML Reader +#include "otbStatisticsXMLFileReader.h" + +// Validation +#include "otbConfusionMatrixCalculator.h" + +#include "itkTimeProbe.h" +#include "otbStandardFilterWatcher.h" + +// Normalize the samples +#include "otbShiftScaleSampleListFilter.h" + +// List sample concatenation +#include "otbConcatenateSampleListFilter.h" + +// Balancing ListSample +#include "otbListSampleToBalancedListSampleFilter.h" + +// VectorData projection filter + +// Extract a ROI of the vectordata +#include "otbVectorDataIntoImageProjectionFilter.h" + +// Elevation handler +#include "otbWrapperElevationParametersHandler.h" namespace otb { namespace Wrapper { -void TrainImagesClassifier::DoInit() +class TrainImagesClassifier: public LearningApplicationBase<float,int> +{ +public: + /** Standard class typedefs. */ + typedef TrainImagesClassifier Self; + typedef LearningApplicationBase<float,int> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** Standard macro */ + itkNewMacro(Self) + + itkTypeMacro(TrainImagesClassifier, otb::Wrapper::LearningApplicationBase) + + typedef Superclass::SampleType SampleType; + typedef Superclass::ListSampleType ListSampleType; + typedef Superclass::TargetSampleType TargetSampleType; + typedef Superclass::TargetListSampleType TargetListSampleType; + + typedef Superclass::SampleImageType SampleImageType; + typedef SampleImageType::PixelType PixelType; + + // SampleList manipulation + typedef otb::ListSampleGenerator<SampleImageType, VectorDataType> ListSampleGeneratorType; + + typedef otb::Statistics::ConcatenateSampleListFilter<ListSampleType> ConcatenateListSampleFilterType; + typedef otb::Statistics::ConcatenateSampleListFilter<TargetListSampleType> ConcatenateLabelListSampleFilterType; + + // Statistic XML file Reader + typedef otb::StatisticsXMLFileReader<SampleType> StatisticsReader; + + // Enhance List Sample typedef otb::Statistics::ListSampleToBalancedListSampleFilter<ListSampleType, LabelListSampleType> BalancingListSampleFilterType; + typedef otb::Statistics::ShiftScaleSampleListFilter<ListSampleType, ListSampleType> ShiftScaleFilterType; + + // Estimate performance on validation sample + typedef otb::ConfusionMatrixCalculator<TargetListSampleType, TargetListSampleType> ConfusionMatrixCalculatorType; + typedef ConfusionMatrixCalculatorType::ConfusionMatrixType ConfusionMatrixType; + typedef ConfusionMatrixCalculatorType::MapOfIndicesType MapOfIndicesType; + typedef ConfusionMatrixCalculatorType::ClassLabelType ClassLabelType; + + // VectorData projection filter + typedef otb::VectorDataProjectionFilter<VectorDataType, VectorDataType> VectorDataProjectionFilterType; + + // Extract ROI + typedef otb::VectorDataIntoImageProjectionFilter<VectorDataType, SampleImageType> VectorDataReprojectionType; + +protected: + //using Superclass::AddParameter; + //friend void InitSVMParams(TrainImagesClassifier & app); + +private: + +void DoInit() { SetName("TrainImagesClassifier"); SetDescription( @@ -46,8 +126,6 @@ void TrainImagesClassifier::DoInit() SetDocAuthors("OTB-Team"); SetDocSeeAlso("OpenCV documentation for machine learning http://docs.opencv.org/modules/ml/doc/ml.html "); - AddDocTag(Tags::Learning); - //Group IO AddParameter(ParameterType_Group, "io", "Input and output data"); SetParameterDescription("io", "This group of parameters allows to set input and output data."); @@ -101,24 +179,7 @@ void TrainImagesClassifier::DoInit() SetParameterDescription("sample.vfn", "Name of the field used to discriminate class labels in the input vector data files."); SetParameterString("sample.vfn", "Class"); - AddParameter(ParameterType_Choice, "classifier", "Classifier to use for the training"); - SetParameterDescription("classifier", "Choice of the classifier to use for the training."); - - //Group LibSVM -#ifdef OTB_USE_LIBSVM - InitLibSVMParams(); -#endif - -#ifdef OTB_USE_OPENCV - InitSVMParams(); - InitBoostParams(); - InitDecisionTreeParams(); - InitGradientBoostedTreeParams(); - InitNeuralNetworkParams(); - InitNormalBayesParams(); - InitRandomForestsParams(); - InitKNNParams(); -#endif + Superclass::DoInit(); AddRANDParameter(); // Doc example parameter settings @@ -136,15 +197,14 @@ void TrainImagesClassifier::DoInit() SetDocExampleParameterValue("classifier.libsvm.opt", "false"); SetDocExampleParameterValue("io.out", "svmModelQB1.txt"); SetDocExampleParameterValue("io.confmatout", "svmConfusionMatrixQB1.csv"); -} +} -void TrainImagesClassifier::DoUpdateParameters() +void DoUpdateParameters() { // Nothing to do here : all parameters are independent } - -void TrainImagesClassifier::LogConfusionMatrix(ConfusionMatrixCalculatorType* confMatCalc) +void LogConfusionMatrix(ConfusionMatrixCalculatorType* confMatCalc) { ConfusionMatrixCalculatorType::ConfusionMatrixType matrix = confMatCalc->GetConfusionMatrix(); @@ -215,24 +275,7 @@ void TrainImagesClassifier::LogConfusionMatrix(ConfusionMatrixCalculatorType* co otbAppLogINFO("Confusion matrix (rows = reference labels, columns = produced labels):\n" << os.str()); } -void TrainImagesClassifier::Classify(ListSampleType::Pointer validationListSample, LabelListSampleType::Pointer predictedList) -{ - //Classification - ModelPointerType model = MachineLearningModelFactoryType::CreateMachineLearningModel(GetParameterString("io.out"), - MachineLearningModelFactoryType::ReadMode); - - if (model.IsNull()) - { - otbAppLogFATAL(<< "Error when loading model " << GetParameterString("io.out")); - } - - model->Load(GetParameterString("io.out")); - model->SetInputListSample(validationListSample); - model->SetTargetListSample(predictedList); - model->PredictAll(); -} - -void TrainImagesClassifier::DoExecute() +void DoExecute() { GetLogger()->Debug("Entering DoExecute\n"); //Create training and validation for list samples and label list samples @@ -243,8 +286,8 @@ void TrainImagesClassifier::DoExecute() ConcatenateLabelListSampleFilterType::New(); ConcatenateListSampleFilterType::Pointer concatenateValidationSamples = ConcatenateListSampleFilterType::New(); - MeasurementType meanMeasurementVector; - MeasurementType stddevMeasurementVector; + SampleType meanMeasurementVector; + SampleType stddevMeasurementVector; //-------------------------- // Load measurements from images @@ -358,7 +401,7 @@ void TrainImagesClassifier::DoExecute() } ListSampleType::Pointer listSample; - LabelListSampleType::Pointer labelListSample; + TargetListSampleType::Pointer labelListSample; //-------------------------- // Balancing training sample (if needed) // if (IsParameterEnabled("sample.b")) @@ -384,9 +427,9 @@ void TrainImagesClassifier::DoExecute() //-------------------------- // Split the data set into training/validation set ListSampleType::Pointer trainingListSample = listSample; - LabelListSampleType::Pointer trainingLabeledListSample = labelListSample; + TargetListSampleType::Pointer trainingLabeledListSample = labelListSample; - LabelListSampleType::Pointer validationLabeledListSample = concatenateValidationLabels->GetOutput(); + TargetListSampleType::Pointer validationLabeledListSample = concatenateValidationLabels->GetOutput(); otbAppLogINFO("Size of training set: " << trainingListSample->Size()); otbAppLogINFO("Size of validation set: " << validationListSample->Size()); otbAppLogINFO("Size of labeled training set: " << trainingLabeledListSample->Size()); @@ -395,88 +438,14 @@ void TrainImagesClassifier::DoExecute() //-------------------------- // Estimate model //-------------------------- - LabelListSampleType::Pointer predictedList = LabelListSampleType::New(); - const std::string classifierType = GetParameterString("classifier"); - - if (classifierType == "libsvm") - { - #ifdef OTB_USE_LIBSVM - TrainLibSVM(trainingListSample, trainingLabeledListSample); - #else - otbAppLogFATAL("Module LIBSVM is not installed. You should consider turning OTB_USE_LIBSVM on during cmake configuration."); - #endif - } - else if (classifierType == "svm") - { - #ifdef OTB_USE_OPENCV - TrainSVM(trainingListSample, trainingLabeledListSample); - #else - otbAppLogFATAL("Module OPENCV is not installed. You should consider turning OTB_USE_OPENCV on during cmake configuration."); - #endif - } - else if (classifierType == "boost") - { - #ifdef OTB_USE_OPENCV - TrainBoost(trainingListSample, trainingLabeledListSample); - #else - otbAppLogFATAL("Module OPENCV is not installed. You should consider turning OTB_USE_OPENCV on during cmake configuration."); - #endif - } - else if (classifierType == "dt") - { - #ifdef OTB_USE_OPENCV - TrainDecisionTree(trainingListSample, trainingLabeledListSample); - #else - otbAppLogFATAL("Module OPENCV is not installed. You should consider turning OTB_USE_OPENCV on during cmake configuration."); - #endif - } - else if (classifierType == "gbt") - { - #ifdef OTB_USE_OPENCV - TrainGradientBoostedTree(trainingListSample, trainingLabeledListSample); - #else - otbAppLogFATAL("Module OPENCV is not installed. You should consider turning OTB_USE_OPENCV on during cmake configuration."); - #endif - } - else if (classifierType == "ann") - { - #ifdef OTB_USE_OPENCV - TrainNeuralNetwork(trainingListSample, trainingLabeledListSample); - #else - otbAppLogFATAL("Module OPENCV is not installed. You should consider turning OTB_USE_OPENCV on during cmake configuration."); - #endif - } - else if (classifierType == "bayes") - { - #ifdef OTB_USE_OPENCV - TrainNormalBayes(trainingListSample, trainingLabeledListSample); - #else - otbAppLogFATAL("Module OPENCV is not installed. You should consider turning OTB_USE_OPENCV on during cmake configuration."); - #endif - } - else if (classifierType == "rf") - { - #ifdef OTB_USE_OPENCV - TrainRandomForests(trainingListSample, trainingLabeledListSample); - #else - otbAppLogFATAL("Module OPENCV is not installed. You should consider turning OTB_USE_OPENCV on during cmake configuration."); - #endif - } - else if (classifierType == "knn") - { - #ifdef OTB_USE_OPENCV - TrainKNN(trainingListSample, trainingLabeledListSample); - #else - otbAppLogFATAL("Module OPENCV is not installed. You should consider turning OTB_USE_OPENCV on during cmake configuration."); - #endif - } - + this->Train(trainingListSample,trainingLabeledListSample,GetParameterString("io.out")); //-------------------------- // Performances estimation //-------------------------- + TargetListSampleType::Pointer predictedList = TargetListSampleType::New(); ListSampleType::Pointer performanceListSample=ListSampleType::New(); - LabelListSampleType::Pointer performanceLabeledListSample=LabelListSampleType::New(); + TargetListSampleType::Pointer performanceLabeledListSample=TargetListSampleType::New(); //Test the input validation set size if(validationLabeledListSample->Size() != 0) @@ -491,7 +460,7 @@ void TrainImagesClassifier::DoExecute() performanceLabeledListSample = trainingLabeledListSample; } - Classify(performanceListSample, predictedList); + this->Classify(performanceListSample, predictedList, GetParameterString("io.out")); ConfusionMatrixCalculatorType::Pointer confMatCalc = ConfusionMatrixCalculatorType::New(); @@ -605,11 +574,12 @@ void TrainImagesClassifier::DoExecute() } // END if (this->HasValue("io.confmatout")) // TODO: implement hyperplane distance classifier and performance validation (cf. object detection) ? - } + VectorDataReprojectionType::Pointer vdreproj; +}; -} -} +} // end namespace Wrapper +} // end namespace otb OTB_APPLICATION_EXPORT(otb::Wrapper::TrainImagesClassifier) diff --git a/Modules/Applications/AppClassification/app/otbTrainImagesClassifier.h b/Modules/Applications/AppClassification/app/otbTrainImagesClassifier.h deleted file mode 100644 index 235613fd56eaa5a265dc66f1e60ad26c849e1a27..0000000000000000000000000000000000000000 --- a/Modules/Applications/AppClassification/app/otbTrainImagesClassifier.h +++ /dev/null @@ -1,198 +0,0 @@ -/*========================================================================= - Program: ORFEO Toolbox - Language: C++ - Date: $Date$ - Version: $Revision$ - - - Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. - See OTBCopyright.txt for details. - - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ -#include "otbConfigure.h" - -#include "otbWrapperApplicationFactory.h" - -#include <iostream> - -//Image -#include "otbVectorImage.h" -#include "otbVectorData.h" -#include "otbListSampleGenerator.h" - -// ListSample -#include "itkVariableLengthVector.h" - -//Estimator -#include "otbMachineLearningModelFactory.h" - -#ifdef OTB_USE_OPENCV -# include "otbKNearestNeighborsMachineLearningModel.h" -# include "otbRandomForestsMachineLearningModel.h" -# include "otbSVMMachineLearningModel.h" -# include "otbBoostMachineLearningModel.h" -# include "otbDecisionTreeMachineLearningModel.h" -# include "otbGradientBoostedTreeMachineLearningModel.h" -# include "otbNormalBayesMachineLearningModel.h" -# include "otbNeuralNetworkMachineLearningModel.h" -#endif - -#ifdef OTB_USE_LIBSVM -#include "otbLibSVMMachineLearningModel.h" -#endif - -// Statistic XML Reader -#include "otbStatisticsXMLFileReader.h" - -// Validation -#include "otbConfusionMatrixCalculator.h" - -#include "itkTimeProbe.h" -#include "otbStandardFilterWatcher.h" - -// Normalize the samples -#include "otbShiftScaleSampleListFilter.h" - -// List sample concatenation -#include "otbConcatenateSampleListFilter.h" - -// Balancing ListSample -#include "otbListSampleToBalancedListSampleFilter.h" - -// VectorData projection filter - -// Extract a ROI of the vectordata -#include "otbVectorDataIntoImageProjectionFilter.h" - -// Elevation handler -#include "otbWrapperElevationParametersHandler.h" - -namespace otb -{ -namespace Wrapper -{ - -class TrainImagesClassifier: public Application -{ -public: - /** Standard class typedefs. */ - typedef TrainImagesClassifier Self; - typedef Application Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** Standard macro */ - itkNewMacro(Self) - - itkTypeMacro(TrainImagesClassifier, otb::Application) - - typedef FloatVectorImageType::PixelType PixelType; - typedef FloatVectorImageType::InternalPixelType InternalPixelType; - - // Training vectordata - typedef itk::VariableLengthVector<InternalPixelType> MeasurementType; - - // SampleList manipulation - typedef otb::ListSampleGenerator<FloatVectorImageType, VectorDataType> ListSampleGeneratorType; - - typedef ListSampleGeneratorType::ListSampleType ListSampleType; - typedef ListSampleGeneratorType::LabelType LabelType; - typedef ListSampleGeneratorType::ListLabelType LabelListSampleType; - typedef otb::Statistics::ConcatenateSampleListFilter<ListSampleType> ConcatenateListSampleFilterType; - typedef otb::Statistics::ConcatenateSampleListFilter<LabelListSampleType> ConcatenateLabelListSampleFilterType; - - // Statistic XML file Reader - typedef otb::StatisticsXMLFileReader<MeasurementType> StatisticsReader; - - // Enhance List Sample typedef otb::Statistics::ListSampleToBalancedListSampleFilter<ListSampleType, LabelListSampleType> BalancingListSampleFilterType; - typedef otb::Statistics::ShiftScaleSampleListFilter<ListSampleType, ListSampleType> ShiftScaleFilterType; - - // Machine Learning models - typedef otb::MachineLearningModelFactory<InternalPixelType, ListSampleGeneratorType::ClassLabelType> MachineLearningModelFactoryType; - typedef MachineLearningModelFactoryType::MachineLearningModelTypePointer ModelPointerType; - -#ifdef OTB_USE_OPENCV - typedef otb::RandomForestsMachineLearningModel<InternalPixelType, ListSampleGeneratorType::ClassLabelType> RandomForestType; - typedef otb::KNearestNeighborsMachineLearningModel<InternalPixelType, ListSampleGeneratorType::ClassLabelType> KNNType; - typedef otb::SVMMachineLearningModel<InternalPixelType, ListSampleGeneratorType::ClassLabelType> SVMType; - typedef otb::BoostMachineLearningModel<InternalPixelType, ListSampleGeneratorType::ClassLabelType> BoostType; - typedef otb::DecisionTreeMachineLearningModel<InternalPixelType, ListSampleGeneratorType::ClassLabelType> DecisionTreeType; - typedef otb::GradientBoostedTreeMachineLearningModel<InternalPixelType, ListSampleGeneratorType::ClassLabelType> GradientBoostedTreeType; - typedef otb::NeuralNetworkMachineLearningModel<InternalPixelType, ListSampleGeneratorType::ClassLabelType> NeuralNetworkType; - typedef otb::NormalBayesMachineLearningModel<InternalPixelType, ListSampleGeneratorType::ClassLabelType> NormalBayesType; -#endif - -#ifdef OTB_USE_LIBSVM - typedef otb::LibSVMMachineLearningModel<InternalPixelType, ListSampleGeneratorType::ClassLabelType> LibSVMType; -#endif - - // Estimate performance on validation sample - typedef otb::ConfusionMatrixCalculator<LabelListSampleType, LabelListSampleType> ConfusionMatrixCalculatorType; - typedef ConfusionMatrixCalculatorType::ConfusionMatrixType ConfusionMatrixType; - typedef ConfusionMatrixCalculatorType::MapOfIndicesType MapOfIndicesType; - typedef ConfusionMatrixCalculatorType::ClassLabelType ClassLabelType; - - - // VectorData projection filter - typedef otb::VectorDataProjectionFilter<VectorDataType, VectorDataType> VectorDataProjectionFilterType; - - // Extract ROI - typedef otb::VectorDataIntoImageProjectionFilter<VectorDataType, FloatVectorImageType> VectorDataReprojectionType; - -protected: - using Superclass::AddParameter; - friend void InitSVMParams(TrainImagesClassifier & app); - -private: - void DoInit(); - - void DoUpdateParameters(); - - void LogConfusionMatrix(ConfusionMatrixCalculatorType* confMatCalc); - -#ifdef OTB_USE_LIBSVM - void InitLibSVMParams(); -#endif - -#ifdef OTB_USE_OPENCV - void InitBoostParams(); - void InitSVMParams(); - void InitDecisionTreeParams(); - void InitGradientBoostedTreeParams(); - void InitNeuralNetworkParams(); - void InitNormalBayesParams(); - void InitRandomForestsParams(); - void InitKNNParams(); -#endif - -#ifdef OTB_USE_LIBSVM - void TrainLibSVM(ListSampleType::Pointer trainingListSample, LabelListSampleType::Pointer trainingLabeledListSample); -#endif - -#ifdef OTB_USE_OPENCV - void TrainBoost(ListSampleType::Pointer trainingListSample, LabelListSampleType::Pointer trainingLabeledListSample); - void TrainSVM(ListSampleType::Pointer trainingListSample, LabelListSampleType::Pointer trainingLabeledListSample); - void TrainDecisionTree(ListSampleType::Pointer trainingListSample, LabelListSampleType::Pointer trainingLabeledListSample); - void TrainGradientBoostedTree(ListSampleType::Pointer trainingListSample, LabelListSampleType::Pointer trainingLabeledListSample); - void TrainNeuralNetwork(ListSampleType::Pointer trainingListSample, LabelListSampleType::Pointer trainingLabeledListSample); - void TrainNormalBayes(ListSampleType::Pointer trainingListSample, LabelListSampleType::Pointer trainingLabeledListSample); - void TrainRandomForests(ListSampleType::Pointer trainingListSample, LabelListSampleType::Pointer trainingLabeledListSample); - void TrainKNN(ListSampleType::Pointer trainingListSample, LabelListSampleType::Pointer trainingLabeledListSample); -#endif - - void Classify(ListSampleType::Pointer validationListSample, LabelListSampleType::Pointer predictedList); - - void DoExecute(); - - VectorDataReprojectionType::Pointer vdreproj; -}; - -} -} - - diff --git a/Modules/Applications/AppClassification/app/otbTrainKNN.cxx b/Modules/Applications/AppClassification/app/otbTrainKNN.cxx deleted file mode 100644 index bc31cd4fce6c1c0207570161bd6df033e8fbff45..0000000000000000000000000000000000000000 --- a/Modules/Applications/AppClassification/app/otbTrainKNN.cxx +++ /dev/null @@ -1,52 +0,0 @@ -/*========================================================================= - Program: ORFEO Toolbox - Language: C++ - Date: $Date$ - Version: $Revision$ - - - Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. - See OTBCopyright.txt for details. - - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ - -#include "otbTrainImagesClassifier.h" - - -namespace otb -{ -namespace Wrapper -{ -#ifdef OTB_USE_OPENCV - void TrainImagesClassifier::InitKNNParams() - { - AddChoice("classifier.knn", "KNN classifier"); - SetParameterDescription("classifier.knn", "This group of parameters allows to set KNN classifier parameters. " - "See complete documentation here \\url{http://docs.opencv.org/modules/ml/doc/k_nearest_neighbors.html}."); - - //K parameter - AddParameter(ParameterType_Int, "classifier.knn.k", "Number of Neighbors"); - SetParameterInt("classifier.knn.k", 32); - SetParameterDescription("classifier.knn.k","The number of neighbors to use."); - - } - - - void TrainImagesClassifier::TrainKNN(ListSampleType::Pointer trainingListSample, LabelListSampleType::Pointer trainingLabeledListSample) - { - KNNType::Pointer knnClassifier = KNNType::New(); - knnClassifier->SetInputListSample(trainingListSample); - knnClassifier->SetTargetListSample(trainingLabeledListSample); - knnClassifier->SetK(GetParameterInt("classifier.knn.k")); - - knnClassifier->Train(); - knnClassifier->Save(GetParameterString("io.out")); - } -#endif -} //end namespace wrapper -} //end namespace otb diff --git a/Modules/Applications/AppClassification/app/otbTrainRegression.cxx b/Modules/Applications/AppClassification/app/otbTrainRegression.cxx new file mode 100644 index 0000000000000000000000000000000000000000..82e865194dd0418e98d04c17550df9919f19ff76 --- /dev/null +++ b/Modules/Applications/AppClassification/app/otbTrainRegression.cxx @@ -0,0 +1,543 @@ +/*========================================================================= + Program: ORFEO Toolbox + Language: C++ + Date: $Date$ + Version: $Revision$ + + + Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. + See OTBCopyright.txt for details. + + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + + =========================================================================*/ +#include "otbLearningApplicationBase.h" +#include "otbWrapperApplicationFactory.h" + +#include "otbListSampleGenerator.h" + +#include "otbImageToEnvelopeVectorDataFilter.h" +#include "itkPreOrderTreeIterator.h" + +// Statistic XML Reader +#include "otbStatisticsXMLFileReader.h" + +#include "itkTimeProbe.h" +#include "otbStandardFilterWatcher.h" + +// Normalize the samples +#include "otbShiftScaleSampleListFilter.h" + +// List sample concatenation +#include "otbConcatenateSampleListFilter.h" + +// Balancing ListSample +#include "otbListSampleToBalancedListSampleFilter.h" + +#include "itkMersenneTwisterRandomVariateGenerator.h" + +// Elevation handler +#include "otbWrapperElevationParametersHandler.h" + +namespace otb +{ +namespace Wrapper +{ + +class TrainRegression: public LearningApplicationBase<float,float> +{ +public: + /** Standard class typedefs. */ + typedef TrainRegression Self; + typedef LearningApplicationBase<float,float> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** Standard macro */ + itkNewMacro(Self) + + itkTypeMacro(TrainRegression, otb::Wrapper::LearningApplicationBase) + + typedef Superclass::SampleType SampleType; + typedef Superclass::ListSampleType ListSampleType; + typedef Superclass::TargetSampleType TargetSampleType; + typedef Superclass::TargetListSampleType TargetListSampleType; + + typedef Superclass::SampleImageType SampleImageType; + typedef SampleImageType::PixelType PixelType; + + // SampleList manipulation + typedef otb::ListSampleGenerator<SampleImageType, VectorDataType> ListSampleGeneratorType; + + typedef otb::Statistics::ConcatenateSampleListFilter<ListSampleType> ConcatenateListSampleFilterType; + typedef otb::Statistics::ConcatenateSampleListFilter<TargetListSampleType> ConcatenateLabelListSampleFilterType; + + // Statistic XML file Reader + typedef otb::StatisticsXMLFileReader<SampleType> StatisticsReader; + + // Enhance List Sample typedef otb::Statistics::ListSampleToBalancedListSampleFilter<ListSampleType, LabelListSampleType> BalancingListSampleFilterType; + typedef otb::Statistics::ShiftScaleSampleListFilter<ListSampleType, ListSampleType> ShiftScaleFilterType; + + typedef otb::ImageToEnvelopeVectorDataFilter<SampleImageType,VectorDataType> EnvelopeFilterType; + + typedef itk::PreOrderTreeIterator<VectorDataType::DataTreeType> TreeIteratorType; + + typedef itk::Statistics::MersenneTwisterRandomVariateGenerator RandomGeneratorType; + +protected: + TrainRegression() + { + this->m_RegressionFlag = true; + } + +private: + +void DoInit() +{ + SetName("TrainRegression"); + SetDescription( + "Train a classifier from multiple images to perform regression."); + + // Documentation + SetDocName("Train a regression model"); + SetDocLongDescription( + "This application trains a classifier from multiple input images or a csv " + "file, in order to perform regression. Predictors are composed of pixel " + "values in each band optionally centered and reduced using an XML " + "statistics file produced by the ComputeImagesStatistics application.\n " + "The output value for each predictor is assumed to be the last band " + "(or the last column for CSV files). Training and validation predictor " + "lists are built such that their size is inferior to maximum bounds given " + "by the user, and the proportion corresponds to the balance parameter. " + "Several classifier parameters can be set depending on the chosen " + "classifier. In the validation process, the mean square error is computed\n" + " This application is based on LibSVM and on OpenCV Machine Learning " + "classifiers, and is compatible with OpenCV 2.3.1 and later."); + SetDocLimitations("None"); + SetDocAuthors("OTB-Team"); + SetDocSeeAlso("OpenCV documentation for machine learning http://docs.opencv.org/modules/ml/doc/ml.html "); + + //Group IO + AddParameter(ParameterType_Group, "io", "Input and output data"); + SetParameterDescription("io", "This group of parameters allows to set input and output data."); + AddParameter(ParameterType_InputImageList, "io.il", "Input Image List"); + SetParameterDescription("io.il", "A list of input images. First (n-1) bands should contain the predictor. The last band should contain the output value to predict."); + AddParameter(ParameterType_InputFilename, "io.csv", "Input CSV file"); + SetParameterDescription("io.csv","Input CSV file containing the predictors, and the output values in last column. Only used when no input image is given"); + MandatoryOff("io.csv"); + + AddParameter(ParameterType_InputFilename, "io.imstat", "Input XML image statistics file"); + MandatoryOff("io.imstat"); + SetParameterDescription("io.imstat", + "Input XML file containing the mean and the standard deviation of the input images."); + AddParameter(ParameterType_OutputFilename, "io.out", "Output regression model"); + SetParameterDescription("io.out", "Output file containing the model estimated (.txt format)."); + + AddParameter(ParameterType_Float,"io.mse","Mean Square Error"); + SetParameterDescription("io.mse","Mean square error computed with the validation predictors"); + SetParameterRole("io.mse",Role_Output); + DisableParameter("io.mse"); + + //Group Sample list + AddParameter(ParameterType_Group, "sample", "Training and validation samples parameters"); + SetParameterDescription("sample", + "This group of parameters allows to set training and validation sample lists parameters."); + + AddParameter(ParameterType_Int, "sample.mt", "Maximum training predictors"); + //MandatoryOff("mt"); + SetDefaultParameterInt("sample.mt", 1000); + SetParameterDescription("sample.mt", "Maximum number of training predictors (default = 1000) (no limit = -1)."); + + AddParameter(ParameterType_Int, "sample.mv", "Maximum validation predictors"); + // MandatoryOff("mv"); + SetDefaultParameterInt("sample.mv", 1000); + SetParameterDescription("sample.mv", "Maximum number of validation predictors (default = 1000) (no limit = -1)."); + + AddParameter(ParameterType_Float, "sample.vtr", "Training and validation sample ratio"); + SetParameterDescription("sample.vtr", + "Ratio between training and validation samples (0.0 = all training, 1.0 = all validation) (default = 0.5)."); + SetParameterFloat("sample.vtr", 0.5); + + Superclass::DoInit(); + + AddRANDParameter(); + + // Doc example parameter settings + SetDocExampleParameterValue("io.il", "training_dataset.tif"); + SetDocExampleParameterValue("io.out", "regression_model.txt"); + SetDocExampleParameterValue("io.imstat", "training_statistics.xml"); + SetDocExampleParameterValue("classifier", "svm"); +} + +void DoUpdateParameters() +{ + if (HasValue("io.csv") && IsParameterEnabled("io.csv")) + { + MandatoryOff("io.il"); + } + else + { + MandatoryOn("io.il"); + } +} + +void ParseCSVPredictors(std::string path, ListSampleType* outputList) +{ + std::ifstream ifs; + ifs.open(path.c_str()); + unsigned int nbCols = 0; + char sep = '\t'; + std::istringstream iss; + SampleType elem; + while(!ifs.eof()) + { + std::string line; + std::getline(ifs,line); + // filter current line + while (!line.empty() && (line[0] == ' ' || line[0] == '\t')) + { + line.erase(line.begin()); + } + while (!line.empty() && ( *(line.end()-1) == ' ' || *(line.end()-1) == '\t' || *(line.end()-1) == '\r')) + { + line.erase(line.end()-1); + } + + // Avoid commented lines or too short ones + if (!line.empty() && line[0] != '#') + { + std::vector<itksys::String> words = itksys::SystemTools::SplitString(line.c_str(),sep); + if (nbCols == 0) + { + // detect separator and feature size + if (words.size() < 2) + { + sep = ' '; + words = itksys::SystemTools::SplitString(line.c_str(),sep); + } + if (words.size() < 2) + { + sep = ';'; + words = itksys::SystemTools::SplitString(line.c_str(),sep); + } + if (words.size() < 2) + { + sep = ','; + words = itksys::SystemTools::SplitString(line.c_str(),sep); + } + if (words.size() < 2) + { + otbAppLogFATAL(<< "Can't parse CSV file : less than 2 columns or unknonw separator (knowns ones are tab, space, comma and semi-colon)"); + } + nbCols = words.size(); + elem.SetSize(nbCols,false); + outputList->SetMeasurementVectorSize(nbCols); + } + else if (words.size() != nbCols ) + { + otbAppLogWARNING(<< "Skip CSV line, wrong number of columns : got "<<words.size() << ", expected "<<nbCols); + continue; + } + elem.Fill(0.0); + for (unsigned int i=0 ; i<nbCols ; ++i) + { + iss.str(words[i]); + iss >> elem[i]; + } + outputList->PushBack(elem); + } + } + ifs.close(); +} + +void DoExecute() +{ + GetLogger()->Debug("Entering DoExecute\n"); + //Create training and validation for list samples and label list samples + ConcatenateListSampleFilterType::Pointer concatenateTrainingSamples = ConcatenateListSampleFilterType::New(); + ConcatenateListSampleFilterType::Pointer concatenateValidationSamples = ConcatenateListSampleFilterType::New(); + + SampleType meanMeasurementVector; + SampleType stddevMeasurementVector; + + //-------------------------- + // Load measurements from images + unsigned int nbBands = 0; + unsigned int nbFeatures = 0; + //Iterate over all input images + + FloatVectorImageListType* imageList = GetParameterImageList("io.il"); + + //Iterate over all input images + for (unsigned int imgIndex = 0; imgIndex < imageList->Size(); ++imgIndex) + { + FloatVectorImageType::Pointer image = imageList->GetNthElement(imgIndex); + image->UpdateOutputInformation(); + + if (imgIndex == 0) + { + nbBands = image->GetNumberOfComponentsPerPixel(); + nbFeatures = static_cast<unsigned int>(static_cast<int>(nbBands) - 1); + if (nbBands < 2) + { + otbAppLogFATAL(<< "Need at least two bands per image, got "<<nbBands); + } + else + { + if (nbBands != image->GetNumberOfComponentsPerPixel()) + { + otbAppLogFATAL(<< "Image has a different number of components than " + "the first one, expected "<<nbBands<<", got "<< image->GetNumberOfComponentsPerPixel()); + } + } + } + + // Extract image envelope to feed in sampleGenerator + EnvelopeFilterType::Pointer envelopeFilter = EnvelopeFilterType::New(); + envelopeFilter->SetInput(image); + envelopeFilter->SetSamplingRate(0); + if (!image->GetProjectionRef().empty()) + { + envelopeFilter->SetOutputProjectionRef(image->GetProjectionRef()); + } + + // Setup the DEM Handler + // otb::Wrapper::ElevationParametersHandler::SetupDEMHandlerFromElevationParameters(this,"elev"); + + envelopeFilter->Update(); + + VectorDataType::Pointer envelope = envelopeFilter->GetOutput(); + + TreeIteratorType itVector(envelope->GetDataTree()); + for (itVector.GoToBegin(); !itVector.IsAtEnd(); ++itVector) + { + if (itVector.Get()->IsPolygonFeature()) + { + itVector.Get()->SetFieldAsInt(std::string("class"),1); + } + } + + + //Sample list generator + ListSampleGeneratorType::Pointer sampleGenerator = ListSampleGeneratorType::New(); + + sampleGenerator->SetInput(image); + sampleGenerator->SetInputVectorData(envelope); + + sampleGenerator->SetClassKey("class"); + sampleGenerator->SetMaxTrainingSize(GetParameterInt("sample.mt")); + sampleGenerator->SetMaxValidationSize(GetParameterInt("sample.mv")); + sampleGenerator->SetValidationTrainingProportion(GetParameterFloat("sample.vtr")); + sampleGenerator->SetBoundByMin(false); + sampleGenerator->SetPolygonEdgeInclusion(true); + + sampleGenerator->Update(); + + //Concatenate training and validation samples from the image + concatenateTrainingSamples->AddInput(sampleGenerator->GetTrainingListSample()); + concatenateValidationSamples->AddInput(sampleGenerator->GetValidationListSample()); + } + + // if no input image, try CSV + if (imageList->Size() == 0) + { + if (HasValue("io.csv") && IsParameterEnabled("io.csv")) + { + ListSampleType::Pointer csvListSample = ListSampleType::New(); + this->ParseCSVPredictors(this->GetParameterString("io.csv"), csvListSample); + unsigned int totalCSVSize = csvListSample->Size(); + if (totalCSVSize == 0) + { + otbAppLogFATAL("No input image and empty CSV file. Missing input data"); + } + nbBands = csvListSample->GetMeasurementVectorSize(); + nbFeatures = static_cast<unsigned int>(static_cast<int>(nbBands) - 1); + ListSampleType::Pointer csvTrainListSample = ListSampleType::New(); + ListSampleType::Pointer csvValidListSample = ListSampleType::New(); + csvTrainListSample->SetMeasurementVectorSize(nbBands); + csvValidListSample->SetMeasurementVectorSize(nbBands); + double ratio = this->GetParameterFloat("sample.vtr"); + int trainSize = static_cast<int>(static_cast<double>(totalCSVSize)*(1.0-ratio)); + int validSize = static_cast<int>(static_cast<double>(totalCSVSize)*(ratio)); + if (trainSize > this->GetParameterInt("sample.mt")) + { + trainSize = this->GetParameterInt("sample.mt"); + } + if (validSize > this->GetParameterInt("sample.mv")) + { + validSize = this->GetParameterInt("sample.mv"); + } + double probaTrain = static_cast<double>(trainSize)/static_cast<double>(totalCSVSize); + double probaValid = static_cast<double>(validSize)/static_cast<double>(totalCSVSize); + + RandomGeneratorType::Pointer randomGenerator = RandomGeneratorType::GetInstance(); + for (unsigned int i=0; i<totalCSVSize; ++i) + { + double random = randomGenerator->GetUniformVariate(0.0, 1.0); + if (random < probaTrain) + { + csvTrainListSample->PushBack(csvListSample->GetMeasurementVector(i)); + } + else if (random < probaTrain + probaValid) + { + csvValidListSample->PushBack(csvListSample->GetMeasurementVector(i)); + } + } + concatenateTrainingSamples->AddInput(csvTrainListSample); + concatenateValidationSamples->AddInput(csvValidListSample); + } + } + + // Update + concatenateTrainingSamples->Update(); + concatenateValidationSamples->Update(); + + if (concatenateTrainingSamples->GetOutput()->Size() == 0) + { + otbAppLogFATAL("No training samples, cannot perform training."); + } + + if (concatenateValidationSamples->GetOutput()->Size() == 0) + { + otbAppLogWARNING("No validation samples."); + } + + if (IsParameterEnabled("io.imstat")) + { + StatisticsReader::Pointer statisticsReader = StatisticsReader::New(); + statisticsReader->SetFileName(GetParameterString("io.imstat")); + meanMeasurementVector = statisticsReader->GetStatisticVectorByName("mean"); + stddevMeasurementVector = statisticsReader->GetStatisticVectorByName("stddev"); + // handle stat file without output normalization + if (meanMeasurementVector.Size() == nbFeatures) + { + meanMeasurementVector.SetSize(nbBands,false); + meanMeasurementVector[nbFeatures] = 0.0; + stddevMeasurementVector.SetSize(nbBands,false); + stddevMeasurementVector[nbFeatures] = 1.0; + } + } + else + { + meanMeasurementVector.SetSize(nbBands); + meanMeasurementVector.Fill(0.); + stddevMeasurementVector.SetSize(nbBands); + stddevMeasurementVector.Fill(1.); + } + + // Shift scale the samples + ShiftScaleFilterType::Pointer trainingShiftScaleFilter = ShiftScaleFilterType::New(); + trainingShiftScaleFilter->SetInput(concatenateTrainingSamples->GetOutput()); + trainingShiftScaleFilter->SetShifts(meanMeasurementVector); + trainingShiftScaleFilter->SetScales(stddevMeasurementVector); + trainingShiftScaleFilter->Update(); + + ListSampleType::Pointer rawValidationListSample=ListSampleType::New(); + + //Test if the validation test is empty + if ( concatenateValidationSamples->GetOutput()->Size() != 0 ) + { + ShiftScaleFilterType::Pointer validationShiftScaleFilter = ShiftScaleFilterType::New(); + validationShiftScaleFilter->SetInput(concatenateValidationSamples->GetOutput()); + validationShiftScaleFilter->SetShifts(meanMeasurementVector); + validationShiftScaleFilter->SetScales(stddevMeasurementVector); + validationShiftScaleFilter->Update(); + rawValidationListSample = validationShiftScaleFilter->GetOutput(); + } + + // Split between predictors and output values + ListSampleType::Pointer rawlistSample = trainingShiftScaleFilter->GetOutput(); + ListSampleType::Pointer listSample = ListSampleType::New(); + listSample->SetMeasurementVectorSize(nbFeatures); + listSample->Resize(rawlistSample->Size()); + TargetListSampleType::Pointer labelListSample = TargetListSampleType::New(); + labelListSample->SetMeasurementVectorSize(1); + labelListSample->Resize(rawlistSample->Size()); + + ListSampleType::Pointer validationListSample = ListSampleType::New(); + validationListSample->SetMeasurementVectorSize(nbFeatures); + validationListSample->Resize(rawValidationListSample->Size()); + TargetListSampleType::Pointer validationLabeledListSample = TargetListSampleType::New(); + validationLabeledListSample->SetMeasurementVectorSize(1); + validationLabeledListSample->Resize(rawValidationListSample->Size()); + + ListSampleType::MeasurementVectorType elem; + TargetListSampleType::MeasurementVectorType outElem; + for (ListSampleType::InstanceIdentifier i=0; i<rawlistSample->Size() ; ++i) + { + elem = rawlistSample->GetMeasurementVector(i); + outElem[0] = elem[nbFeatures]; + labelListSample->SetMeasurementVector(i,outElem); + elem.SetSize(nbFeatures,false); + listSample->SetMeasurementVector(i,elem); + } + for (ListSampleType::InstanceIdentifier i=0; i<rawValidationListSample->Size() ; ++i) + { + elem = rawValidationListSample->GetMeasurementVector(i); + outElem[0] = elem[nbFeatures]; + validationLabeledListSample->SetMeasurementVector(i,outElem); + elem.SetSize(nbFeatures,false); + validationListSample->SetMeasurementVector(i,elem); + } + + + otbAppLogINFO("Number of training samples: " << concatenateTrainingSamples->GetOutput()->Size()); + //-------------------------- + // Split the data set into training/validation set + ListSampleType::Pointer trainingListSample = listSample; + TargetListSampleType::Pointer trainingLabeledListSample = labelListSample; + + otbAppLogINFO("Size of training set: " << trainingListSample->Size()); + otbAppLogINFO("Size of validation set: " << validationListSample->Size()); + + //-------------------------- + // Estimate model + //-------------------------- + this->Train(trainingListSample,trainingLabeledListSample,GetParameterString("io.out")); + + //-------------------------- + // Performances estimation + //-------------------------- + ListSampleType::Pointer performanceListSample; + TargetListSampleType::Pointer predictedList = TargetListSampleType::New(); + predictedList->SetMeasurementVectorSize(1); + TargetListSampleType::Pointer performanceLabeledListSample; + + //Test the input validation set size + if(validationLabeledListSample->Size() != 0) + { + performanceListSample = validationListSample; + performanceLabeledListSample = validationLabeledListSample; + } + else + { + otbAppLogWARNING("The validation set is empty. The performance estimation is done using the input training set in this case."); + performanceListSample = trainingListSample; + performanceLabeledListSample = trainingLabeledListSample; + } + + this->Classify(performanceListSample, predictedList, GetParameterString("io.out")); + + otbAppLogINFO("Training performances"); + double mse=0.0; + TargetListSampleType::MeasurementVectorType predictedElem; + for (TargetListSampleType::InstanceIdentifier i=0; i<performanceListSample->Size() ; ++i) + { + outElem = performanceLabeledListSample->GetMeasurementVector(i); + predictedElem = predictedList->GetMeasurementVector(i); + mse += (outElem[0] - predictedElem[0]) * (outElem[0] - predictedElem[0]); + } + mse /= static_cast<double>(performanceListSample->Size()); + otbAppLogINFO("Mean Square Error = "<<mse); + this->SetParameterFloat("io.mse",mse); +} + +}; + +} // end namespace Wrapper +} // end namespace otb + +OTB_APPLICATION_EXPORT(otb::Wrapper::TrainRegression) diff --git a/Modules/Applications/AppClassification/include/otbLearningApplicationBase.h b/Modules/Applications/AppClassification/include/otbLearningApplicationBase.h new file mode 100644 index 0000000000000000000000000000000000000000..9af1259c73ff6356d515588f52887db569f63c43 --- /dev/null +++ b/Modules/Applications/AppClassification/include/otbLearningApplicationBase.h @@ -0,0 +1,222 @@ +/*========================================================================= + Program: ORFEO Toolbox + Language: C++ + Date: $Date$ + Version: $Revision$ + + + Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. + See OTBCopyright.txt for details. + + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + + =========================================================================*/ +#ifndef __otbLearningApplicationBase_h +#define __otbLearningApplicationBase_h + +#include "otbConfigure.h" + +#include "otbWrapperApplication.h" + +#include <iostream> + +// ListSample +#include "itkListSample.h" +#include "itkVariableLengthVector.h" + +//Estimator +#include "otbMachineLearningModelFactory.h" + +#ifdef OTB_USE_OPENCV +# include "otbKNearestNeighborsMachineLearningModel.h" +# include "otbRandomForestsMachineLearningModel.h" +# include "otbSVMMachineLearningModel.h" +# include "otbBoostMachineLearningModel.h" +# include "otbDecisionTreeMachineLearningModel.h" +# include "otbGradientBoostedTreeMachineLearningModel.h" +# include "otbNormalBayesMachineLearningModel.h" +# include "otbNeuralNetworkMachineLearningModel.h" +#endif + +#ifdef OTB_USE_LIBSVM +#include "otbLibSVMMachineLearningModel.h" +#endif + +namespace otb +{ +namespace Wrapper +{ + +/** \class LearningApplicationBase + * \brief LearningApplicationBase is the base class for application that + * use machine learning model. + * + * This base class offers a DoInit() method to initialize all the parameters + * related to machine learning models. They will all be in the choice parameter + * named "classifier". The class also offers generic Train() and Classify() + * methods. The classes derived from LearningApplicationBase only need these + * 3 methods to handle the machine learning model. + * + * There are multiple machine learning models in OTB, some imported from OpenCV, + * and one imported from LibSVM. They all have different parameters. The + * purpose of this class is to handle the creation of all parameters related to + * machine learning models (in DoInit() ), and to dispatch the calls to + * specific train functions in function Train(). + * + * This class is templated over scalar types for input and output values. + * Typically, the input value type will be either float of double. The choice + * of an output value type depends on the learning mode. This base class + * supports both classification and regression modes. For classification + * (enabled by default), the output value type corresponds to a class + * identifier so integer types suit well. For regression, the output value + * should not be an integer type, but rather a floating point type. In addition, + * an application deriving this base class for regression should initialize + * the m_RegressionFlag to true in their constructor. + * + * \sa TrainImagesClassifier + * \sa TrainRegression + * + * \ingroup OTBAppClassification + */ +template <class TInputValue, class TOutputValue> +class LearningApplicationBase: public Application +{ +public: + /** Standard class typedefs. */ + typedef LearningApplicationBase Self; + typedef Application Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** Standard macro */ + itkTypeMacro(LearningApplicationBase, otb::Application) + + typedef TInputValue InputValueType; + typedef TOutputValue OutputValueType; + + typedef otb::VectorImage<InputValueType> SampleImageType; + typedef typename SampleImageType::PixelType PixelType; + + // Machine Learning models + typedef otb::MachineLearningModelFactory< + InputValueType, OutputValueType> ModelFactoryType; + typedef typename ModelFactoryType::MachineLearningModelTypePointer ModelPointerType; + typedef typename ModelFactoryType::MachineLearningModelType ModelType; + + typedef typename ModelType::InputSampleType SampleType; + typedef typename ModelType::InputListSampleType ListSampleType; + + typedef typename ModelType::TargetSampleType TargetSampleType; + typedef typename ModelType::TargetListSampleType TargetListSampleType; + typedef typename ModelType::TargetValueType TargetValueType; + +#ifdef OTB_USE_OPENCV + typedef otb::RandomForestsMachineLearningModel<InputValueType, OutputValueType> RandomForestType; + typedef otb::KNearestNeighborsMachineLearningModel<InputValueType, OutputValueType> KNNType; + typedef otb::SVMMachineLearningModel<InputValueType, OutputValueType> SVMType; + typedef otb::BoostMachineLearningModel<InputValueType, OutputValueType> BoostType; + typedef otb::DecisionTreeMachineLearningModel<InputValueType, OutputValueType> DecisionTreeType; + typedef otb::GradientBoostedTreeMachineLearningModel<InputValueType, OutputValueType> GradientBoostedTreeType; + typedef otb::NeuralNetworkMachineLearningModel<InputValueType, OutputValueType> NeuralNetworkType; + typedef otb::NormalBayesMachineLearningModel<InputValueType, OutputValueType> NormalBayesType; +#endif + +#ifdef OTB_USE_LIBSVM + typedef otb::LibSVMMachineLearningModel<InputValueType, OutputValueType> LibSVMType; +#endif + +protected: + LearningApplicationBase(); + + /** Generic method to train and save the machine learning model. This method + * uses specific train methods depending on the chosen model.*/ + void Train(typename ListSampleType::Pointer trainingListSample, + typename TargetListSampleType::Pointer trainingLabeledListSample, + std::string modelPath); + + /** Generic method to load a model file and use it to classify a sample list*/ + void Classify(typename ListSampleType::Pointer validationListSample, + typename TargetListSampleType::Pointer predictedList, + std::string modelPath); + + /** Init method that creates all the parameters for machine learning models */ + void DoInit(); + + /** Flag to switch between classification and regression mode. + * False by default, child classes may change it in their constructor */ + bool m_RegressionFlag; + +private: + + /** Specific Init and Train methods for each machine learning model */ + //@{ +#ifdef OTB_USE_LIBSVM + void InitLibSVMParams(); + + void TrainLibSVM(typename ListSampleType::Pointer trainingListSample, + typename TargetListSampleType::Pointer trainingLabeledListSample, + std::string modelPath); +#endif + +#ifdef OTB_USE_OPENCV + void InitBoostParams(); + void InitSVMParams(); + void InitDecisionTreeParams(); + void InitGradientBoostedTreeParams(); + void InitNeuralNetworkParams(); + void InitNormalBayesParams(); + void InitRandomForestsParams(); + void InitKNNParams(); + + void TrainBoost(typename ListSampleType::Pointer trainingListSample, + typename TargetListSampleType::Pointer trainingLabeledListSample, + std::string modelPath); + void TrainSVM(typename ListSampleType::Pointer trainingListSample, + typename TargetListSampleType::Pointer trainingLabeledListSample, + std::string modelPath); + void TrainDecisionTree(typename ListSampleType::Pointer trainingListSample, + typename TargetListSampleType::Pointer trainingLabeledListSample, + std::string modelPath); + void TrainGradientBoostedTree(typename ListSampleType::Pointer trainingListSample, + typename TargetListSampleType::Pointer trainingLabeledListSample, + std::string modelPath); + void TrainNeuralNetwork(typename ListSampleType::Pointer trainingListSample, + typename TargetListSampleType::Pointer trainingLabeledListSample, + std::string modelPath); + void TrainNormalBayes(typename ListSampleType::Pointer trainingListSample, + typename TargetListSampleType::Pointer trainingLabeledListSample, + std::string modelPath); + void TrainRandomForests(typename ListSampleType::Pointer trainingListSample, + typename TargetListSampleType::Pointer trainingLabeledListSample, + std::string modelPath); + void TrainKNN(typename ListSampleType::Pointer trainingListSample, + typename TargetListSampleType::Pointer trainingLabeledListSample, + std::string modelPath); +#endif + //@} +}; + +} +} + +#ifndef OTB_MANUAL_INSTANTIATION +#include "otbLearningApplicationBase.txx" +#ifdef OTB_USE_OPENCV +#include "otbTrainBoost.txx" +#include "otbTrainDecisionTree.txx" +#include "otbTrainGradientBoostedTree.txx" +#include "otbTrainKNN.txx" +#include "otbTrainNeuralNetwork.txx" +#include "otbTrainNormalBayes.txx" +#include "otbTrainRandomForests.txx" +#include "otbTrainSVM.txx" +#endif +#ifdef OTB_USE_LIBSVM +#include "otbTrainLibSVM.txx" +#endif +#endif + +#endif diff --git a/Modules/Applications/AppClassification/include/otbLearningApplicationBase.txx b/Modules/Applications/AppClassification/include/otbLearningApplicationBase.txx new file mode 100644 index 0000000000000000000000000000000000000000..a545538656efbafd98fa520944b09a183ef87fcb --- /dev/null +++ b/Modules/Applications/AppClassification/include/otbLearningApplicationBase.txx @@ -0,0 +1,177 @@ +/*========================================================================= + Program: ORFEO Toolbox + Language: C++ + Date: $Date$ + Version: $Revision$ + + + Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. + See OTBCopyright.txt for details. + + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + + =========================================================================*/ +#ifndef __otbLearningApplicationBase_txx +#define __otbLearningApplicationBase_txx + +#include "otbLearningApplicationBase.h" + +namespace otb +{ +namespace Wrapper +{ + +template <class TInputValue, class TOutputValue> +LearningApplicationBase<TInputValue,TOutputValue> +::LearningApplicationBase() : m_RegressionFlag(false) +{ +} + +template <class TInputValue, class TOutputValue> +void +LearningApplicationBase<TInputValue,TOutputValue> +::DoInit() +{ + AddDocTag(Tags::Learning); + + // main choice parameter that will contain all machine learning options + AddParameter(ParameterType_Choice, "classifier", "Classifier to use for the training"); + SetParameterDescription("classifier", "Choice of the classifier to use for the training."); + + //Group LibSVM +#ifdef OTB_USE_LIBSVM + InitLibSVMParams(); +#endif + +#ifdef OTB_USE_OPENCV + InitSVMParams(); + if (!m_RegressionFlag) + { + InitBoostParams(); // Regression not supported + } + InitDecisionTreeParams(); + InitGradientBoostedTreeParams(); + InitNeuralNetworkParams(); + if (!m_RegressionFlag) + { + InitNormalBayesParams(); // Regression not supported + } + InitRandomForestsParams(); + InitKNNParams(); +#endif +} + +template <class TInputValue, class TOutputValue> +void +LearningApplicationBase<TInputValue,TOutputValue> +::Classify(typename ListSampleType::Pointer validationListSample, + typename TargetListSampleType::Pointer predictedList, + std::string modelPath) +{ + // load a machine learning model from file and predict the input sample list + ModelPointerType model = ModelFactoryType::CreateMachineLearningModel(modelPath, + ModelFactoryType::ReadMode); + + if (model.IsNull()) + { + otbAppLogFATAL(<< "Error when loading model " << modelPath); + } + + model->Load(modelPath); + model->SetRegressionMode(this->m_RegressionFlag); + model->SetInputListSample(validationListSample); + model->SetTargetListSample(predictedList); + model->PredictAll(); +} + +template <class TInputValue, class TOutputValue> +void +LearningApplicationBase<TInputValue,TOutputValue> +::Train(typename ListSampleType::Pointer trainingListSample, + typename TargetListSampleType::Pointer trainingLabeledListSample, + std::string modelPath) +{ + // get the name of the chosen machine learning model + const std::string modelName = GetParameterString("classifier"); + // call specific train function + if (modelName == "libsvm") + { + #ifdef OTB_USE_LIBSVM + TrainLibSVM(trainingListSample, trainingLabeledListSample, modelPath); + #else + otbAppLogFATAL("Module LIBSVM is not installed. You should consider turning OTB_USE_LIBSVM on during cmake configuration."); + #endif + } + else if (modelName == "svm") + { + #ifdef OTB_USE_OPENCV + TrainSVM(trainingListSample, trainingLabeledListSample, modelPath); + #else + otbAppLogFATAL("Module OPENCV is not installed. You should consider turning OTB_USE_OPENCV on during cmake configuration."); + #endif + } + else if (modelName == "boost") + { + #ifdef OTB_USE_OPENCV + TrainBoost(trainingListSample, trainingLabeledListSample, modelPath); + #else + otbAppLogFATAL("Module OPENCV is not installed. You should consider turning OTB_USE_OPENCV on during cmake configuration."); + #endif + } + else if (modelName == "dt") + { + #ifdef OTB_USE_OPENCV + TrainDecisionTree(trainingListSample, trainingLabeledListSample, modelPath); + #else + otbAppLogFATAL("Module OPENCV is not installed. You should consider turning OTB_USE_OPENCV on during cmake configuration."); + #endif + } + else if (modelName == "gbt") + { + #ifdef OTB_USE_OPENCV + TrainGradientBoostedTree(trainingListSample, trainingLabeledListSample, modelPath); + #else + otbAppLogFATAL("Module OPENCV is not installed. You should consider turning OTB_USE_OPENCV on during cmake configuration."); + #endif + } + else if (modelName == "ann") + { + #ifdef OTB_USE_OPENCV + TrainNeuralNetwork(trainingListSample, trainingLabeledListSample, modelPath); + #else + otbAppLogFATAL("Module OPENCV is not installed. You should consider turning OTB_USE_OPENCV on during cmake configuration."); + #endif + } + else if (modelName == "bayes") + { + #ifdef OTB_USE_OPENCV + TrainNormalBayes(trainingListSample, trainingLabeledListSample, modelPath); + #else + otbAppLogFATAL("Module OPENCV is not installed. You should consider turning OTB_USE_OPENCV on during cmake configuration."); + #endif + } + else if (modelName == "rf") + { + #ifdef OTB_USE_OPENCV + TrainRandomForests(trainingListSample, trainingLabeledListSample, modelPath); + #else + otbAppLogFATAL("Module OPENCV is not installed. You should consider turning OTB_USE_OPENCV on during cmake configuration."); + #endif + } + else if (modelName == "knn") + { + #ifdef OTB_USE_OPENCV + TrainKNN(trainingListSample, trainingLabeledListSample, modelPath); + #else + otbAppLogFATAL("Module OPENCV is not installed. You should consider turning OTB_USE_OPENCV on during cmake configuration."); + #endif + } +} + +} +} + +#endif diff --git a/Modules/Applications/AppClassification/app/otbTrainBoost.cxx b/Modules/Applications/AppClassification/include/otbTrainBoost.txx similarity index 82% rename from Modules/Applications/AppClassification/app/otbTrainBoost.cxx rename to Modules/Applications/AppClassification/include/otbTrainBoost.txx index c107f8016ea1bdecaf2ca9a68c8af259184715c2..23e666bfc1d877072b41312ce0478a8a41036500 100644 --- a/Modules/Applications/AppClassification/app/otbTrainBoost.cxx +++ b/Modules/Applications/AppClassification/include/otbTrainBoost.txx @@ -14,16 +14,19 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ - -#include "otbTrainImagesClassifier.h" - +#ifndef __otbTrainBoost_txx +#define __otbTrainBoost_txx +#include "otbLearningApplicationBase.h" namespace otb { namespace Wrapper { -#ifdef OTB_USE_OPENCV - void TrainImagesClassifier::InitBoostParams() + + template <class TInputValue, class TOutputValue> + void + LearningApplicationBase<TInputValue,TOutputValue> + ::InitBoostParams() { AddChoice("classifier.boost", "Boost classifier"); SetParameterDescription("classifier.boost", "This group of parameters allows to set Boost classifier parameters. " @@ -55,10 +58,15 @@ namespace Wrapper SetParameterDescription("classifier.boost.m","Maximum depth of the tree."); } - - void TrainImagesClassifier::TrainBoost(ListSampleType::Pointer trainingListSample, LabelListSampleType::Pointer trainingLabeledListSample) + template <class TInputValue, class TOutputValue> + void + LearningApplicationBase<TInputValue,TOutputValue> + ::TrainBoost(typename ListSampleType::Pointer trainingListSample, + typename TargetListSampleType::Pointer trainingLabeledListSample, + std::string modelPath) { - BoostType::Pointer boostClassifier = BoostType::New(); + typename BoostType::Pointer boostClassifier = BoostType::New(); + boostClassifier->SetRegressionMode(this->m_RegressionFlag); boostClassifier->SetInputListSample(trainingListSample); boostClassifier->SetTargetListSample(trainingLabeledListSample); boostClassifier->SetBoostType(GetParameterInt("classifier.boost.t")); @@ -67,9 +75,10 @@ namespace Wrapper boostClassifier->SetMaxDepth(GetParameterInt("classifier.boost.m")); boostClassifier->Train(); - boostClassifier->Save(GetParameterString("io.out")); + boostClassifier->Save(modelPath); } -#endif } //end namespace wrapper } //end namespace otb + +#endif diff --git a/Modules/Applications/AppClassification/app/otbTrainDecisionTree.cxx b/Modules/Applications/AppClassification/include/otbTrainDecisionTree.txx similarity index 86% rename from Modules/Applications/AppClassification/app/otbTrainDecisionTree.cxx rename to Modules/Applications/AppClassification/include/otbTrainDecisionTree.txx index 9f94a7fc6050bb13a2169242619e8232f32d47c3..04df9380caacca8975caf05f8bb0b6b8237d0ff5 100644 --- a/Modules/Applications/AppClassification/app/otbTrainDecisionTree.cxx +++ b/Modules/Applications/AppClassification/include/otbTrainDecisionTree.txx @@ -14,15 +14,19 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ - -#include "otbTrainImagesClassifier.h" +#ifndef __otbTrainDecisionTree_txx +#define __otbTrainDecisionTree_txx +#include "otbLearningApplicationBase.h" namespace otb { namespace Wrapper { -#ifdef OTB_USE_OPENCV -void TrainImagesClassifier::InitDecisionTreeParams() + +template <class TInputValue, class TOutputValue> +void +LearningApplicationBase<TInputValue,TOutputValue> +::InitDecisionTreeParams() { AddChoice("classifier.dt", "Decision Tree classifier"); SetParameterDescription("classifier.dt", @@ -81,10 +85,15 @@ void TrainImagesClassifier::InitDecisionTreeParams() } -void TrainImagesClassifier::TrainDecisionTree(ListSampleType::Pointer trainingListSample, - LabelListSampleType::Pointer trainingLabeledListSample) +template <class TInputValue, class TOutputValue> +void +LearningApplicationBase<TInputValue,TOutputValue> +::TrainDecisionTree(typename ListSampleType::Pointer trainingListSample, + typename TargetListSampleType::Pointer trainingLabeledListSample, + std::string modelPath) { - DecisionTreeType::Pointer classifier = DecisionTreeType::New(); + typename DecisionTreeType::Pointer classifier = DecisionTreeType::New(); + classifier->SetRegressionMode(this->m_RegressionFlag); classifier->SetInputListSample(trainingListSample); classifier->SetTargetListSample(trainingLabeledListSample); classifier->SetMaxDepth(GetParameterInt("classifier.dt.max")); @@ -101,8 +110,10 @@ void TrainImagesClassifier::TrainDecisionTree(ListSampleType::Pointer trainingLi classifier->SetTruncatePrunedTree(false); } classifier->Train(); - classifier->Save(GetParameterString("io.out")); + classifier->Save(modelPath); } -#endif + } //end namespace wrapper } //end namespace otb + +#endif diff --git a/Modules/Applications/AppClassification/app/otbTrainGradientBoostedTree.cxx b/Modules/Applications/AppClassification/include/otbTrainGradientBoostedTree.txx similarity index 63% rename from Modules/Applications/AppClassification/app/otbTrainGradientBoostedTree.cxx rename to Modules/Applications/AppClassification/include/otbTrainGradientBoostedTree.txx index c703ad4c57a0d8efb8103dadc64a92701a16d162..b55612581cd1140185ae53eab3ae407c51536b6b 100644 --- a/Modules/Applications/AppClassification/app/otbTrainGradientBoostedTree.cxx +++ b/Modules/Applications/AppClassification/include/otbTrainGradientBoostedTree.txx @@ -14,23 +14,34 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ - -#include "otbTrainImagesClassifier.h" +#ifndef __otbTrainGradientBoostedTree_txx +#define __otbTrainGradientBoostedTree_txx +#include "otbLearningApplicationBase.h" namespace otb { namespace Wrapper { -#ifdef OTB_USE_OPENCV -void TrainImagesClassifier::InitGradientBoostedTreeParams() + +template <class TInputValue, class TOutputValue> +void +LearningApplicationBase<TInputValue,TOutputValue> +::InitGradientBoostedTreeParams() { AddChoice("classifier.gbt", "Gradient Boosted Tree classifier"); SetParameterDescription( "classifier.gbt", "This group of parameters allows to set Gradient Boosted Tree classifier parameters. " "See complete documentation here \\url{http://docs.opencv.org/modules/ml/doc/gradient_boosted_trees.html}."); - //LossFunctionType : not exposed, as only one type is used for Classification, - // the other three are used for regression. + + if (m_RegressionFlag) + { + AddParameter(ParameterType_Choice, "classifier.gbt.t", "Loss Function Type"); + SetParameterDescription("classifier.gbt.t","Type of loss functionused for training."); + AddChoice("classifier.gbt.t.sqr","Squared Loss"); + AddChoice("classifier.gbt.t.abs","Absolute Loss"); + AddChoice("classifier.gbt.t.hub","Huber Loss"); + } //WeakCount AddParameter(ParameterType_Int, "classifier.gbt.w", "Number of boosting algorithm iterations"); @@ -67,10 +78,15 @@ void TrainImagesClassifier::InitGradientBoostedTreeParams() } -void TrainImagesClassifier::TrainGradientBoostedTree( - ListSampleType::Pointer trainingListSample, LabelListSampleType::Pointer trainingLabeledListSample) +template <class TInputValue, class TOutputValue> +void +LearningApplicationBase<TInputValue,TOutputValue> +::TrainGradientBoostedTree(typename ListSampleType::Pointer trainingListSample, + typename TargetListSampleType::Pointer trainingLabeledListSample, + std::string modelPath) { - GradientBoostedTreeType::Pointer classifier = GradientBoostedTreeType::New(); + typename GradientBoostedTreeType::Pointer classifier = GradientBoostedTreeType::New(); + classifier->SetRegressionMode(this->m_RegressionFlag); classifier->SetInputListSample(trainingListSample); classifier->SetTargetListSample(trainingLabeledListSample); classifier->SetWeakCount(GetParameterInt("classifier.gbt.w")); @@ -78,9 +94,34 @@ void TrainImagesClassifier::TrainGradientBoostedTree( classifier->SetSubSamplePortion(GetParameterFloat("classifier.gbt.p")); classifier->SetMaxDepth(GetParameterInt("classifier.gbt.max")); + if (m_RegressionFlag) + { + switch (GetParameterInt("classifier.gbt.t")) + { + case 0: // SQUARED_LOSS + classifier->SetLossFunctionType(CvGBTrees::SQUARED_LOSS); + break; + case 1: // ABSOLUTE_LOSS + classifier->SetLossFunctionType(CvGBTrees::ABSOLUTE_LOSS); + break; + case 2: // HUBER_LOSS + classifier->SetLossFunctionType(CvGBTrees::HUBER_LOSS); + break; + default: + classifier->SetLossFunctionType(CvGBTrees::SQUARED_LOSS); + break; + } + } + else + { + classifier->SetLossFunctionType(CvGBTrees::DEVIANCE_LOSS); + } + classifier->Train(); - classifier->Save(GetParameterString("io.out")); + classifier->Save(modelPath); } -#endif + } //end namespace wrapper } //end namespace otb + +#endif diff --git a/Modules/Applications/AppClassification/include/otbTrainKNN.txx b/Modules/Applications/AppClassification/include/otbTrainKNN.txx new file mode 100644 index 0000000000000000000000000000000000000000..93656003a1b24e601a630393983934bb65b5e797 --- /dev/null +++ b/Modules/Applications/AppClassification/include/otbTrainKNN.txx @@ -0,0 +1,86 @@ +/*========================================================================= + Program: ORFEO Toolbox + Language: C++ + Date: $Date$ + Version: $Revision$ + + + Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. + See OTBCopyright.txt for details. + + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + + =========================================================================*/ +#ifndef __otbTrainKNN_txx +#define __otbTrainKNN_txx +#include "otbLearningApplicationBase.h" + +namespace otb +{ +namespace Wrapper +{ + + template <class TInputValue, class TOutputValue> + void + LearningApplicationBase<TInputValue,TOutputValue> + ::InitKNNParams() + { + AddChoice("classifier.knn", "KNN classifier"); + SetParameterDescription("classifier.knn", "This group of parameters allows to set KNN classifier parameters. " + "See complete documentation here \\url{http://docs.opencv.org/modules/ml/doc/k_nearest_neighbors.html}."); + + //K parameter + AddParameter(ParameterType_Int, "classifier.knn.k", "Number of Neighbors"); + SetParameterInt("classifier.knn.k", 32); + SetParameterDescription("classifier.knn.k","The number of neighbors to use."); + + if (this->m_RegressionFlag) + { + // Decision rule : mean / median + AddParameter(ParameterType_Choice, "classifier.knn.rule", "Decision rule"); + SetParameterDescription("classifier.knn.rule", "Decision rule for regression output"); + + AddChoice("classifier.knn.rule.mean", "Mean of neighbors values"); + SetParameterDescription("classifier.knn.rule.mean","Returns the mean of neighbors values"); + + AddChoice("classifier.knn.rule.median", "Median of neighbors values"); + SetParameterDescription("classifier.knn.rule.median","Returns the median of neighbors values"); + } + } + + template <class TInputValue, class TOutputValue> + void + LearningApplicationBase<TInputValue,TOutputValue> + ::TrainKNN(typename ListSampleType::Pointer trainingListSample, + typename TargetListSampleType::Pointer trainingLabeledListSample, + std::string modelPath) + { + typename KNNType::Pointer knnClassifier = KNNType::New(); + knnClassifier->SetRegressionMode(this->m_RegressionFlag); + knnClassifier->SetInputListSample(trainingListSample); + knnClassifier->SetTargetListSample(trainingLabeledListSample); + knnClassifier->SetK(GetParameterInt("classifier.knn.k")); + if (this->m_RegressionFlag) + { + std::string decision = this->GetParameterString("classifier.knn.rule"); + if (decision == "mean") + { + knnClassifier->SetDecisionRule(KNNType::KNN_MEAN); + } + else if (decision == "median") + { + knnClassifier->SetDecisionRule(KNNType::KNN_MEDIAN); + } + } + + knnClassifier->Train(); + knnClassifier->Save(modelPath); + } + +} //end namespace wrapper +} //end namespace otb + +#endif diff --git a/Modules/Applications/AppClassification/app/otbTrainLibSVM.cxx b/Modules/Applications/AppClassification/include/otbTrainLibSVM.txx similarity index 52% rename from Modules/Applications/AppClassification/app/otbTrainLibSVM.cxx rename to Modules/Applications/AppClassification/include/otbTrainLibSVM.txx index e117337708d3effd267a462a1d24f8b2f6736e18..928245655fd30d983c970947feef81dbd0c8304f 100644 --- a/Modules/Applications/AppClassification/app/otbTrainLibSVM.cxx +++ b/Modules/Applications/AppClassification/include/otbTrainLibSVM.txx @@ -14,16 +14,19 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ - -#include "otbTrainImagesClassifier.h" - +#ifndef __otbTrainLibSVM_txx +#define __otbTrainLibSVM_txx +#include "otbLearningApplicationBase.h" namespace otb { namespace Wrapper { -#ifdef OTB_USE_LIBSVM - void TrainImagesClassifier::InitLibSVMParams() + + template <class TInputValue, class TOutputValue> + void + LearningApplicationBase<TInputValue,TOutputValue> + ::InitLibSVMParams() { AddChoice("classifier.libsvm", "LibSVM classifier"); SetParameterDescription("classifier.libsvm", "This group of parameters allows to set SVM classifier parameters."); @@ -34,6 +37,21 @@ namespace Wrapper AddChoice("classifier.libsvm.k.sigmoid", "Sigmoid"); SetParameterString("classifier.libsvm.k", "linear"); SetParameterDescription("classifier.libsvm.k", "SVM Kernel Type."); + AddParameter(ParameterType_Choice, "classifier.libsvm.m", "SVM Model Type"); + SetParameterDescription("classifier.libsvm.m", "Type of SVM formulation."); + if (this->m_RegressionFlag) + { + AddChoice("classifier.libsvm.m.epssvr", "Epsilon Support Vector Regression"); + AddChoice("classifier.libsvm.m.nusvr", "Nu Support Vector Regression"); + SetParameterString("classifier.libsvm.m", "epssvr"); + } + else + { + AddChoice("classifier.libsvm.m.csvc", "C support vector classification"); + AddChoice("classifier.libsvm.m.nusvc", "Nu support vector classification"); + AddChoice("classifier.libsvm.m.oneclass", "Distribution estimation (One Class SVM)"); + SetParameterString("classifier.libsvm.m", "csvc"); + } AddParameter(ParameterType_Float, "classifier.libsvm.c", "Cost parameter C"); SetParameterFloat("classifier.libsvm.c", 1.0); SetParameterDescription( @@ -45,12 +63,25 @@ namespace Wrapper AddParameter(ParameterType_Empty, "classifier.libsvm.prob", "Probability estimation"); MandatoryOff("classifier.libsvm.prob"); SetParameterDescription("classifier.libsvm.prob", "Probability estimation flag."); - } + if (this->m_RegressionFlag) + { + AddParameter(ParameterType_Float, "classifier.libsvm.eps", "Epsilon"); + SetParameterFloat("classifier.libsvm.eps", 1e-3); + AddParameter(ParameterType_Float, "classifier.libsvm.nu", "Nu"); + SetParameterFloat("classifier.libsvm.nu", 0.5); + } + } - void TrainImagesClassifier::TrainLibSVM(ListSampleType::Pointer trainingListSample, LabelListSampleType::Pointer trainingLabeledListSample) + template <class TInputValue, class TOutputValue> + void + LearningApplicationBase<TInputValue,TOutputValue> + ::TrainLibSVM(typename ListSampleType::Pointer trainingListSample, + typename TargetListSampleType::Pointer trainingLabeledListSample, + std::string modelPath) { - LibSVMType::Pointer libSVMClassifier = LibSVMType::New(); + typename LibSVMType::Pointer libSVMClassifier = LibSVMType::New(); + libSVMClassifier->SetRegressionMode(this->m_RegressionFlag); libSVMClassifier->SetInputListSample(trainingListSample); libSVMClassifier->SetTargetListSample(trainingLabeledListSample); //SVM Option @@ -83,9 +114,47 @@ namespace Wrapper libSVMClassifier->SetKernelType(LINEAR); break; } + if (this->m_RegressionFlag) + { + switch (GetParameterInt("classifier.libsvm.m")) + { + case 0: // EPSILON_SVR + libSVMClassifier->SetSVMType(EPSILON_SVR); + break; + case 1: // NU_SVR + libSVMClassifier->SetSVMType(NU_SVR); + break; + default: + libSVMClassifier->SetSVMType(EPSILON_SVR); + break; + } + libSVMClassifier->SetEpsilon(GetParameterFloat("classifier.libsvm.eps")); + libSVMClassifier->SetNu(GetParameterFloat("classifier.libsvm.nu")); + } + else + { + switch (GetParameterInt("classifier.libsvm.m")) + { + case 0: // C_SVC + libSVMClassifier->SetSVMType(C_SVC); + break; + case 1: // NU_SVC + libSVMClassifier->SetSVMType(NU_SVC); + break; + case 2: // ONE_CLASS + libSVMClassifier->SetSVMType(ONE_CLASS); + break; + default: + libSVMClassifier->SetSVMType(C_SVC); + break; + } + } + libSVMClassifier->Train(); - libSVMClassifier->Save(GetParameterString("io.out")); + libSVMClassifier->Save(modelPath); } -#endif + } //end namespace wrapper } //end namespace otb + +#endif diff --git a/Modules/Applications/AppClassification/app/otbTrainNeuralNetwork.cxx b/Modules/Applications/AppClassification/include/otbTrainNeuralNetwork.txx similarity index 87% rename from Modules/Applications/AppClassification/app/otbTrainNeuralNetwork.cxx rename to Modules/Applications/AppClassification/include/otbTrainNeuralNetwork.txx index 29b3657ad2ef612a89a83f923cf370c3a9bbbc5c..40f120f69bcaa1df15454070d63e38feda46e960 100644 --- a/Modules/Applications/AppClassification/app/otbTrainNeuralNetwork.cxx +++ b/Modules/Applications/AppClassification/include/otbTrainNeuralNetwork.txx @@ -14,16 +14,20 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ - +#ifndef __otbTrainNeuralNetwork_txx +#define __otbTrainNeuralNetwork_txx #include <boost/lexical_cast.hpp> -#include "otbTrainImagesClassifier.h" +#include "otbLearningApplicationBase.h" namespace otb { namespace Wrapper { -#ifdef OTB_USE_OPENCV -void TrainImagesClassifier::InitNeuralNetworkParams() + +template <class TInputValue, class TOutputValue> +void +LearningApplicationBase<TInputValue,TOutputValue> +::InitNeuralNetworkParams() { AddChoice("classifier.ann", "Artificial Neural Network classifier"); SetParameterDescription("classifier.ann", @@ -119,10 +123,15 @@ void TrainImagesClassifier::InitNeuralNetworkParams() } -void TrainImagesClassifier::TrainNeuralNetwork(ListSampleType::Pointer trainingListSample, - LabelListSampleType::Pointer trainingLabeledListSample) +template <class TInputValue, class TOutputValue> +void +LearningApplicationBase<TInputValue,TOutputValue> +::TrainNeuralNetwork(typename ListSampleType::Pointer trainingListSample, + typename TargetListSampleType::Pointer trainingLabeledListSample, + std::string modelPath) { - NeuralNetworkType::Pointer classifier = NeuralNetworkType::New(); + typename NeuralNetworkType::Pointer classifier = NeuralNetworkType::New(); + classifier->SetRegressionMode(this->m_RegressionFlag); classifier->SetInputListSample(trainingListSample); classifier->SetTargetListSample(trainingLabeledListSample); @@ -153,18 +162,23 @@ void TrainImagesClassifier::TrainNeuralNetwork(ListSampleType::Pointer trainingL unsigned int nbClasses = 0; - LabelType currentLabel = 0, prevLabel = 0; - for (unsigned int itLab = 0; itLab < trainingLabeledListSample->Size(); ++itLab) + if (this->m_RegressionFlag) + { + layerSizes.push_back(1); + } + else { - currentLabel = trainingLabeledListSample->GetMeasurementVector(itLab); - if ((currentLabel != prevLabel) || (itLab == 0)) + std::set<TargetValueType> labelSet; + TargetSampleType currentLabel; + for (unsigned int itLab = 0; itLab < trainingLabeledListSample->Size(); ++itLab) { - ++nbClasses; + currentLabel = trainingLabeledListSample->GetMeasurementVector(itLab); + labelSet.insert(currentLabel[0]); } - prevLabel = currentLabel; + nbClasses = labelSet.size(); + layerSizes.push_back(nbClasses); } - layerSizes.push_back(nbClasses); classifier->SetLayerSizes(layerSizes); switch (GetParameterInt("classifier.ann.f")) @@ -208,8 +222,10 @@ void TrainImagesClassifier::TrainNeuralNetwork(ListSampleType::Pointer trainingL classifier->SetEpsilon(GetParameterFloat("classifier.ann.eps")); classifier->SetMaxIter(GetParameterInt("classifier.ann.iter")); classifier->Train(); - classifier->Save(GetParameterString("io.out")); + classifier->Save(modelPath); } -#endif + } //end namespace wrapper } //end namespace otb + +#endif diff --git a/Modules/Applications/AppClassification/app/otbTrainNormalBayes.cxx b/Modules/Applications/AppClassification/include/otbTrainNormalBayes.txx similarity index 59% rename from Modules/Applications/AppClassification/app/otbTrainNormalBayes.cxx rename to Modules/Applications/AppClassification/include/otbTrainNormalBayes.txx index d33e6eaf9cd79a99120a5176b096a94fb98b190c..d5f3cce8e3ef2ae3fbe02a2b21e99d0004df3944 100644 --- a/Modules/Applications/AppClassification/app/otbTrainNormalBayes.cxx +++ b/Modules/Applications/AppClassification/include/otbTrainNormalBayes.txx @@ -14,16 +14,19 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ - -#include "otbTrainImagesClassifier.h" - +#ifndef __otbTrainNormalBayes_txx +#define __otbTrainNormalBayes_txx +#include "otbLearningApplicationBase.h" namespace otb { namespace Wrapper { -#ifdef OTB_USE_OPENCV - void TrainImagesClassifier::InitNormalBayesParams() + + template <class TInputValue, class TOutputValue> + void + LearningApplicationBase<TInputValue,TOutputValue> + ::InitNormalBayesParams() { AddChoice("classifier.bayes", "Normal Bayes classifier"); SetParameterDescription("classifier.bayes", "Use a Normal Bayes Classifier. " @@ -31,15 +34,22 @@ namespace Wrapper } - - void TrainImagesClassifier::TrainNormalBayes(ListSampleType::Pointer trainingListSample, LabelListSampleType::Pointer trainingLabeledListSample) + template <class TInputValue, class TOutputValue> + void + LearningApplicationBase<TInputValue,TOutputValue> + ::TrainNormalBayes(typename ListSampleType::Pointer trainingListSample, + typename TargetListSampleType::Pointer trainingLabeledListSample, + std::string modelPath) { - NormalBayesType::Pointer classifier = NormalBayesType::New(); + typename NormalBayesType::Pointer classifier = NormalBayesType::New(); + classifier->SetRegressionMode(this->m_RegressionFlag); classifier->SetInputListSample(trainingListSample); classifier->SetTargetListSample(trainingLabeledListSample); classifier->Train(); - classifier->Save(GetParameterString("io.out")); + classifier->Save(modelPath); } -#endif + } //end namespace wrapper } //end namespace otb + +#endif diff --git a/Modules/Applications/AppClassification/app/otbTrainRandomForests.cxx b/Modules/Applications/AppClassification/include/otbTrainRandomForests.txx similarity index 87% rename from Modules/Applications/AppClassification/app/otbTrainRandomForests.cxx rename to Modules/Applications/AppClassification/include/otbTrainRandomForests.txx index 1798b9d9b59b7ffa2323936084736b6b423a3cb5..a856243a300dfc35d559e683aef21268d8c25a12 100644 --- a/Modules/Applications/AppClassification/app/otbTrainRandomForests.cxx +++ b/Modules/Applications/AppClassification/include/otbTrainRandomForests.txx @@ -14,15 +14,19 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ - -#include "otbTrainImagesClassifier.h" +#ifndef __otbTrainRandomForests_txx +#define __otbTrainRandomForests_txx +#include "otbLearningApplicationBase.h" namespace otb { namespace Wrapper { -#ifdef OTB_USE_OPENCV -void TrainImagesClassifier::InitRandomForestsParams() + +template <class TInputValue, class TOutputValue> +void +LearningApplicationBase<TInputValue,TOutputValue> +::InitRandomForestsParams() { AddChoice("classifier.rf", "Random forests classifier"); SetParameterDescription("classifier.rf", @@ -95,10 +99,15 @@ void TrainImagesClassifier::InitRandomForestsParams() //TerminationCriteria not exposed } -void TrainImagesClassifier::TrainRandomForests(ListSampleType::Pointer trainingListSample, - LabelListSampleType::Pointer trainingLabeledListSample) +template <class TInputValue, class TOutputValue> +void +LearningApplicationBase<TInputValue,TOutputValue> +::TrainRandomForests(typename ListSampleType::Pointer trainingListSample, + typename TargetListSampleType::Pointer trainingLabeledListSample, + std::string modelPath) { - RandomForestType::Pointer classifier = RandomForestType::New(); + typename RandomForestType::Pointer classifier = RandomForestType::New(); + classifier->SetRegressionMode(this->m_RegressionFlag); classifier->SetInputListSample(trainingListSample); classifier->SetTargetListSample(trainingLabeledListSample); classifier->SetMaxDepth(GetParameterInt("classifier.rf.max")); @@ -110,8 +119,10 @@ void TrainImagesClassifier::TrainRandomForests(ListSampleType::Pointer trainingL classifier->SetForestAccuracy(GetParameterFloat("classifier.rf.acc")); classifier->Train(); - classifier->Save(GetParameterString("io.out")); + classifier->Save(modelPath); } -#endif + } //end namespace wrapper } //end namespace otb + +#endif diff --git a/Modules/Applications/AppClassification/app/otbTrainSVM.cxx b/Modules/Applications/AppClassification/include/otbTrainSVM.txx similarity index 57% rename from Modules/Applications/AppClassification/app/otbTrainSVM.cxx rename to Modules/Applications/AppClassification/include/otbTrainSVM.txx index a41e103746f5f5d7968f26220791436232caac74..ac0f153ed4f78df8c5a7d838c3e32beed62ddd9f 100644 --- a/Modules/Applications/AppClassification/app/otbTrainSVM.cxx +++ b/Modules/Applications/AppClassification/include/otbTrainSVM.txx @@ -14,28 +14,38 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ - -#include "otbTrainImagesClassifier.h" - +#ifndef __otbTrainSVM_txx +#define __otbTrainSVM_txx +#include "otbLearningApplicationBase.h" namespace otb { namespace Wrapper { -#ifdef OTB_USE_OPENCV - void TrainImagesClassifier::InitSVMParams() + + template <class TInputValue, class TOutputValue> + void + LearningApplicationBase<TInputValue,TOutputValue> + ::InitSVMParams() { AddChoice("classifier.svm", "SVM classifier (OpenCV)"); SetParameterDescription("classifier.svm", "This group of parameters allows to set SVM classifier parameters. " "See complete documentation here \\url{http://docs.opencv.org/modules/ml/doc/support_vector_machines.html}."); AddParameter(ParameterType_Choice, "classifier.svm.m", "SVM Model Type"); - AddChoice("classifier.svm.m.csvc", "C support vector classification"); - AddChoice("classifier.svm.m.nusvc", "Nu support vector classification"); - AddChoice("classifier.svm.m.oneclass", "Distribution estimation (One Class SVM)"); - //AddChoice("classifier.svm.m.epssvr", "Epsilon Support Vector Regression"); - //AddChoice("classifier.svm.m.nusvr", "Nu Support Vector Regression"); - SetParameterString("classifier.svm.m", "csvc"); SetParameterDescription("classifier.svm.m", "Type of SVM formulation."); + if (this->m_RegressionFlag) + { + AddChoice("classifier.svm.m.epssvr", "Epsilon Support Vector Regression"); + AddChoice("classifier.svm.m.nusvr", "Nu Support Vector Regression"); + SetParameterString("classifier.svm.m", "epssvr"); + } + else + { + AddChoice("classifier.svm.m.csvc", "C support vector classification"); + AddChoice("classifier.svm.m.nusvc", "Nu support vector classification"); + AddChoice("classifier.svm.m.oneclass", "Distribution estimation (One Class SVM)"); + SetParameterString("classifier.svm.m", "csvc"); + } AddParameter(ParameterType_Choice, "classifier.svm.k", "SVM Kernel Type"); AddChoice("classifier.svm.k.linear", "Linear"); AddChoice("classifier.svm.k.rbf", "Gaussian radial basis function"); @@ -52,9 +62,26 @@ namespace Wrapper "Parameter nu of a SVM optimization problem (NU_SVC / ONE_CLASS)"); SetParameterFloat("classifier.svm.nu", 0.0); SetParameterDescription("classifier.svm.nu", "Parameter nu of a SVM optimization problem."); - //AddParameter(ParameterType_Float, "classifier.svm.p", "Parameter epsilon of a SVM optimization problem (EPS_SVR)"); - //SetParameterFloat("classifier.svm.p", 0.0); - //SetParameterDescription("classifier.svm.p", "Parameter epsilon of a SVM optimization problem (EPS_SVR)."); + if (this->m_RegressionFlag) + { + AddParameter(ParameterType_Float, "classifier.svm.p", "Parameter epsilon of a SVM optimization problem (EPS_SVR)"); + SetParameterFloat("classifier.svm.p", 1.0); + SetParameterDescription("classifier.svm.p", "Parameter epsilon of a SVM optimization problem (EPS_SVR)."); + + AddParameter(ParameterType_Choice, "classifier.svm.term", "Termination criteria"); + SetParameterDescription("classifier.svm.term","Termination criteria for iterative algorithm"); + AddChoice("classifier.svm.term.iter", "Stops when maximum iteration is reached."); + AddChoice("classifier.svm.term.eps", "Stops when accuracy is lower than epsilon."); + AddChoice("classifier.svm.term.all", "Stops when either iteration or epsilon criteria is true"); + + AddParameter(ParameterType_Float, "classifier.svm.iter", "Maximum iteration"); + SetParameterFloat("classifier.svm.iter", 1000); + SetParameterDescription("classifier.svm.iter", "Maximum number of iterations (corresponds to the termination criteria 'iter')."); + + AddParameter(ParameterType_Float, "classifier.svm.eps", "Epsilon accuracy threshold"); + SetParameterFloat("classifier.svm.eps", FLT_EPSILON); + SetParameterDescription("classifier.svm.eps", "Epsilon accuracy (corresponds to the termination criteria 'eps')."); + } AddParameter(ParameterType_Float, "classifier.svm.coef0", "Parameter coef0 of a kernel function (POLY / SIGMOID)"); SetParameterFloat("classifier.svm.coef0", 0.0); SetParameterDescription("classifier.svm.coef0", "Parameter coef0 of a kernel function (POLY / SIGMOID)."); @@ -76,9 +103,15 @@ namespace Wrapper "because the samples are not identically processed within OpenCV."); } - void TrainImagesClassifier::TrainSVM(ListSampleType::Pointer trainingListSample, LabelListSampleType::Pointer trainingLabeledListSample) + template <class TInputValue, class TOutputValue> + void + LearningApplicationBase<TInputValue,TOutputValue> + ::TrainSVM(typename ListSampleType::Pointer trainingListSample, + typename TargetListSampleType::Pointer trainingLabeledListSample, + std::string modelPath) { - SVMType::Pointer SVMClassifier = SVMType::New(); + typename SVMType::Pointer SVMClassifier = SVMType::New(); + SVMClassifier->SetRegressionMode(this->m_RegressionFlag); SVMClassifier->SetInputListSample(trainingListSample); SVMClassifier->SetTargetListSample(trainingLabeledListSample); switch (GetParameterInt("classifier.svm.k")) @@ -104,36 +137,69 @@ namespace Wrapper std::cout << "CvSVM::LINEAR = " << CvSVM::LINEAR << std::endl; break; } - switch (GetParameterInt("classifier.svm.m")) + if (this->m_RegressionFlag) { - case 0: // C_SVC - SVMClassifier->SetSVMType(CvSVM::C_SVC); - std::cout << "CvSVM::C_SVC = " << CvSVM::C_SVC << std::endl; - break; - case 1: // NU_SVC - SVMClassifier->SetSVMType(CvSVM::NU_SVC); - std::cout << "CvSVM::NU_SVC = " << CvSVM::NU_SVC << std::endl; - break; - case 2: // ONE_CLASS - SVMClassifier->SetSVMType(CvSVM::ONE_CLASS); - std::cout << "CvSVM::ONE_CLASS = " << CvSVM::ONE_CLASS << std::endl; - break; - /*case 3: // EPS_SVR - SVMClassifier->SetSVMType(CvSVM::EPS_SVR); - std::cout<<"CvSVM::EPS_SVR = "<<CvSVM::EPS_SVR<<std::endl; - break; - case 4: // NU_SVR - SVMClassifier->SetSVMType(CvSVM::NU_SVR); - std::cout<<"CvSVM::NU_SVR = "<<CvSVM::NU_SVR<<std::endl; - break; */ - default: // DEFAULT = C_SVC - SVMClassifier->SetSVMType(CvSVM::C_SVC); - std::cout << "CvSVM::C_SVC = " << CvSVM::C_SVC << std::endl; - break; + switch (GetParameterInt("classifier.svm.m")) + { + case 0: // EPS_SVR + SVMClassifier->SetSVMType(CvSVM::EPS_SVR); + std::cout<<"CvSVM::EPS_SVR = "<<CvSVM::EPS_SVR<<std::endl; + break; + case 1: // NU_SVR + SVMClassifier->SetSVMType(CvSVM::NU_SVR); + std::cout<<"CvSVM::NU_SVR = "<<CvSVM::NU_SVR<<std::endl; + break; + default: // DEFAULT = EPS_SVR + SVMClassifier->SetSVMType(CvSVM::EPS_SVR); + std::cout << "CvSVM::EPS_SVR = " << CvSVM::EPS_SVR << std::endl; + break; + } + } + else + { + switch (GetParameterInt("classifier.svm.m")) + { + case 0: // C_SVC + SVMClassifier->SetSVMType(CvSVM::C_SVC); + std::cout << "CvSVM::C_SVC = " << CvSVM::C_SVC << std::endl; + break; + case 1: // NU_SVC + SVMClassifier->SetSVMType(CvSVM::NU_SVC); + std::cout << "CvSVM::NU_SVC = " << CvSVM::NU_SVC << std::endl; + break; + case 2: // ONE_CLASS + SVMClassifier->SetSVMType(CvSVM::ONE_CLASS); + std::cout << "CvSVM::ONE_CLASS = " << CvSVM::ONE_CLASS << std::endl; + break; + default: // DEFAULT = C_SVC + SVMClassifier->SetSVMType(CvSVM::C_SVC); + std::cout << "CvSVM::C_SVC = " << CvSVM::C_SVC << std::endl; + break; + } } SVMClassifier->SetC(GetParameterFloat("classifier.svm.c")); SVMClassifier->SetNu(GetParameterFloat("classifier.svm.nu")); - //SVMClassifier->SetP(GetParameterFloat("classifier.svm.p")); + if (this->m_RegressionFlag) + { + SVMClassifier->SetP(GetParameterFloat("classifier.svm.p")); + switch (GetParameterInt("classifier.svm.term")) + { + case 0: // ITER + SVMClassifier->SetTermCriteriaType(CV_TERMCRIT_ITER); + break; + case 1: // EPS + SVMClassifier->SetTermCriteriaType(CV_TERMCRIT_EPS); + break; + case 2: // ITER+EPS + SVMClassifier->SetTermCriteriaType(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS); + break; + default: + SVMClassifier->SetTermCriteriaType(CV_TERMCRIT_ITER); + break; + } + SVMClassifier->SetMaxIter(GetParameterInt("classifier.svm.iter")); + SVMClassifier->SetEpsilon(GetParameterFloat("classifier.svm.eps")); + } SVMClassifier->SetCoef0(GetParameterFloat("classifier.svm.coef0")); SVMClassifier->SetGamma(GetParameterFloat("classifier.svm.gamma")); SVMClassifier->SetDegree(GetParameterFloat("classifier.svm.degree")); @@ -142,17 +208,21 @@ namespace Wrapper SVMClassifier->SetParameterOptimization(true); } SVMClassifier->Train(); - SVMClassifier->Save(GetParameterString("io.out")); + SVMClassifier->Save(modelPath); // Update the displayed parameters in the GUI after the training process, for further use of them SetParameterFloat("classifier.svm.c", static_cast<float> (SVMClassifier->GetOutputC())); SetParameterFloat("classifier.svm.nu", static_cast<float> (SVMClassifier->GetOutputNu())); - //SetParameterFloat("classifier.svm.p", static_cast<float> (SVMClassifier->GetOutputP())); + if (this->m_RegressionFlag) + { + SetParameterFloat("classifier.svm.p", static_cast<float> (SVMClassifier->GetOutputP())); + } SetParameterFloat("classifier.svm.coef0", static_cast<float> (SVMClassifier->GetOutputCoef0())); SetParameterFloat("classifier.svm.gamma", static_cast<float> (SVMClassifier->GetOutputGamma())); SetParameterFloat("classifier.svm.degree", static_cast<float> (SVMClassifier->GetOutputDegree())); } -#endif } //end namespace wrapper } //end namespace otb + +#endif diff --git a/Modules/Applications/AppClassification/test/CMakeLists.txt b/Modules/Applications/AppClassification/test/CMakeLists.txt index c4e275fe5a33fc8e629a13c9016a5584c8a4b0a3..63a5c0918f5df9138ab25e78968b8305743f2409 100644 --- a/Modules/Applications/AppClassification/test/CMakeLists.txt +++ b/Modules/Applications/AppClassification/test/CMakeLists.txt @@ -841,3 +841,36 @@ otb_test_application(NAME cdbTvVectorDataDSValidationWrongRoads_LI ${OTBAPP_BASELINE_FILES}/cdbTvVectorDataDSValidationOutpout_LI_wr.shp ${TEMP}/cdbTvVectorDataDSValidationOutpout_LI_wr.shp) +if(OTB_USE_OPENCV) +#----------- TrainRegression TESTS ---------------- +# y = 0.01*x^2 + 1.5*x - 300 +otb_test_application(NAME apTvClTrainRegressionTest_monovar + APP TrainRegression + OPTIONS -io.il ${INPUTDATA}/QB_Toulouse_Ortho_regression.tif + -io.imstat ${INPUTDATA}/QB_Toulouse_Ortho_regression.xml + -io.out ${TEMP}/apTvClTrainRegressionTest_monovar.rf + -sample.mt 20000 + -sample.mv 20000 + -sample.vtr 0.5 + -rand 121212 + -classifier rf + -classifier.rf.ra 0.0001 + -classifier.rf.max 6 + -classifier.rf.acc 0.0005 + VALID --compare-ascii ${NOTOL} + ${OTBAPP_BASELINE_FILES}/apTvClTrainRegressionTest_monovar.rf + ${TEMP}/apTvClTrainRegressionTest_monovar.rf) + +#----------- PredictRegression TESTS ---------------- +otb_test_application(NAME apTvClPredictRegressionTest_monovar + APP PredictRegression + OPTIONS -in ${INPUTDATA}/QB_Toulouse_Ortho_PAN.tif + -model ${OTBAPP_BASELINE_FILES}/apTvClTrainRegressionTest_monovar.rf + -imstat ${INPUTDATA}/QB_Toulouse_Ortho_regression.xml + -out ${TEMP}/apTvClPredictRegressionTest_monovar.tif + VALID --compare-image 1 + ${OTBAPP_BASELINE}/apTvClPredictRegressionTest_monovar.tif + ${TEMP}/apTvClPredictRegressionTest_monovar.tif) + +endif() + diff --git a/Modules/Applications/AppFiltering/test/CMakeLists.txt b/Modules/Applications/AppFiltering/test/CMakeLists.txt index d497c9bf8e1b6d51f5668b4ce2ee4be134d91078..984c1830c277999af835fefc934ffcf6bbb2ef8d 100644 --- a/Modules/Applications/AppFiltering/test/CMakeLists.txt +++ b/Modules/Applications/AppFiltering/test/CMakeLists.txt @@ -51,8 +51,8 @@ otb_test_application(NAME apTvDespeckleFrost -filter.frost.rad 5 -filter.frost.deramp 0.1 VALID --compare-image ${EPSILON_7} - ${BASELINE}/bfFiltreLee_05_05_12.tif - ${TEMP}/bfFiltreLee_05_05_12_app.tif) + ${BASELINE}/bfFiltreFrost_05_05_12_app.tif + ${TEMP}/bfFiltreFrost_05_05_12_app.tif) otb_test_application(NAME apTvDespeckleGammaMAP APP Despeckle diff --git a/Modules/Applications/AppImageUtils/app/CMakeLists.txt b/Modules/Applications/AppImageUtils/app/CMakeLists.txt index 82ef77a5887523595bdf30570c5bdebe3b3c5cdc..637eb926408db14daecc6cfd79401ada43a884a3 100644 --- a/Modules/Applications/AppImageUtils/app/CMakeLists.txt +++ b/Modules/Applications/AppImageUtils/app/CMakeLists.txt @@ -89,6 +89,6 @@ otb_create_application( LINK_LIBRARIES ${${otb-module}_LIBRARIES}) otb_create_application( - NAME NoDataMask - SOURCES otbNoDataMask.cxx + NAME ManageNoData + SOURCES otbManageNoData.cxx LINK_LIBRARIES ${${otb-module}_LIBRARIES}) diff --git a/Modules/Applications/AppImageUtils/app/otbManageNoData.cxx b/Modules/Applications/AppImageUtils/app/otbManageNoData.cxx new file mode 100644 index 0000000000000000000000000000000000000000..2449029c861368d5d34121d875608b009e79a530 --- /dev/null +++ b/Modules/Applications/AppImageUtils/app/otbManageNoData.cxx @@ -0,0 +1,145 @@ +/*========================================================================= + + Program: ORFEO Toolbox + Language: C++ + Date: $Date$ + Version: $Revision$ + + + Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. + See OTBCopyright.txt for details. + + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + + =========================================================================*/ +#include "otbWrapperApplication.h" +#include "otbWrapperApplicationFactory.h" + +#include "otbImageToNoDataMaskFilter.h" +#include "otbChangeNoDataValueFilter.h" + +namespace otb +{ +namespace Wrapper +{ + +class ManageNoData : public Application +{ +public: + /** Standard class typedefs. */ + typedef ManageNoData Self; + typedef Application Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** Standard macro */ + itkNewMacro(Self); + + itkTypeMacro(ManageNoData, otb::Application); + + /** Filters typedef */ + typedef otb::ImageToNoDataMaskFilter<FloatVectorImageType,UInt8ImageType> FilterType; + typedef otb::ChangeNoDataValueFilter<FloatVectorImageType,FloatVectorImageType> ChangeNoDataFilterType; + +private: + void DoInit() + { + SetName("ManageNoData"); + SetDescription("Manage No-Data"); + // Documentation + SetDocName("No Data management"); + SetDocLongDescription("This application has two modes. The first allows to build a mask of no-data pixels from the no-data flags read from the image file. The second allows to update the change the no-data value of an image (pixels value and metadata). This last mode also allows to replace NaN in images with a proper no-data value. To do so, one should activate the NaN is no-data option."); + SetDocLimitations("None"); + SetDocAuthors("OTB-Team"); + SetDocSeeAlso("BanMath"); + AddDocTag("Conversion"); + AddDocTag("Image Dynamic"); + AddDocTag(Tags::Manip); + + AddParameter(ParameterType_InputImage, "in", "Input image"); + SetParameterDescription("in", "Input image"); + + AddParameter(ParameterType_OutputImage, "out", "Output Image"); + SetParameterDescription("out", "Output image"); + + AddParameter(ParameterType_Empty,"usenan", "Consider NaN as no-data"); + SetParameterDescription("usenan","If active, the application will consider NaN as no-data values as well"); + MandatoryOff("usenan"); + DisableParameter("usenan"); + + AddParameter(ParameterType_Choice,"mode","No-data handling mode"); + SetParameterDescription("mode","Allows to choose between different no-data handling options"); + + AddChoice("mode.buildmask","Build a no-data Mask"); + + AddParameter(ParameterType_Float,"mode.buildmask.inv","Inside Value"); + SetParameterDescription("mode.buildmask.inv","Value given in the output mask to pixels that are not no data pixels"); + SetDefaultParameterInt("mode.buildmask.inv",1); + + AddParameter(ParameterType_Float,"mode.buildmask.outv","Outside Value"); + SetParameterDescription("mode.buildmask.outv","Value given in the output mask to pixels that are no data pixels"); + SetDefaultParameterInt("mode.buildmask.outv",0); + + AddChoice("mode.changevalue","Change the no-data value"); + + AddParameter(ParameterType_Float,"mode.changevalue.newv","The new no-data value"); + SetParameterDescription("mode.changevalue.newv","The new no-data value"); + SetDefaultParameterInt("mode.changevalue.newv",0); + + SetParameterString("mode","buildmask"); + + AddRAMParameter(); + + // Doc example parameter settings + SetDocExampleParameterValue("in", "QB_Toulouse_Ortho_XS.tif"); + SetDocExampleParameterValue("out", "QB_Toulouse_Ortho_XS_nodatamask.tif uint8"); + SetDocExampleParameterValue("mode.buildmask.inv", "255"); + SetDocExampleParameterValue("mode.buildmask.outv", "0"); + } + + void DoUpdateParameters() + { + // Nothing to do here for the parameters : all are independent + } + + + void DoExecute() + { + FloatVectorImageType::Pointer inputPtr = this->GetParameterImage("in"); + + m_Filter = FilterType::New(); + m_Filter->SetInsideValue(this->GetParameterFloat("mode.buildmask.inv")); + m_Filter->SetOutsideValue(this->GetParameterFloat("mode.buildmask.outv")); + m_Filter->SetNaNIsNoData(IsParameterEnabled("usenan")); + m_Filter->SetInput(inputPtr); + + m_ChangeNoDataFilter = ChangeNoDataFilterType::New(); + m_ChangeNoDataFilter->SetInput(inputPtr); + m_ChangeNoDataFilter->SetNaNIsNoData(IsParameterEnabled("usenan")); + + std::vector<double> newNoData(inputPtr->GetNumberOfComponentsPerPixel(),GetParameterFloat("mode.changevalue.newv")); + + m_ChangeNoDataFilter->SetNewNoDataValues(newNoData); + + if(GetParameterString("mode") == "buildmask") + { + SetParameterOutputImage("out",m_Filter->GetOutput()); + } + else if(GetParameterString("mode") == "changevalue") + { + SetParameterOutputImage("out",m_ChangeNoDataFilter->GetOutput()); + } + } + + FilterType::Pointer m_Filter; + ChangeNoDataFilterType::Pointer m_ChangeNoDataFilter; +}; + +} +} + +OTB_APPLICATION_EXPORT(otb::Wrapper::ManageNoData) + diff --git a/Modules/Applications/AppImageUtils/app/otbNoDataMask.cxx b/Modules/Applications/AppImageUtils/app/otbNoDataMask.cxx deleted file mode 100644 index dd99a9a7949132a1bf64ab95684408b39cee873a..0000000000000000000000000000000000000000 --- a/Modules/Applications/AppImageUtils/app/otbNoDataMask.cxx +++ /dev/null @@ -1,107 +0,0 @@ -/*========================================================================= - - Program: ORFEO Toolbox - Language: C++ - Date: $Date$ - Version: $Revision$ - - - Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. - See OTBCopyright.txt for details. - - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ -#include "otbWrapperApplication.h" -#include "otbWrapperApplicationFactory.h" - -#include "otbImageToNoDataMaskFilter.h" - -namespace otb -{ -namespace Wrapper -{ - - -class NoDataMask : public Application -{ -public: - /** Standard class typedefs. */ - typedef NoDataMask Self; - typedef Application Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** Standard macro */ - itkNewMacro(Self); - - itkTypeMacro(NoDataMask, otb::Application); - - /** Filters typedef */ - typedef otb::ImageToNoDataMaskFilter<FloatVectorImageType,UInt8ImageType> FilterType; - -private: - void DoInit() - { - SetName("NoDataMask"); - SetDescription("NoDataMask"); - // Documentation - SetDocName("No Data Mask management"); - SetDocLongDescription("This application builds a nodata mask from the no data flags found in metadata or from NaN pixels."); - SetDocLimitations("None"); - SetDocAuthors("OTB-Team"); - SetDocSeeAlso("BanMath"); - AddDocTag("Conversion"); - AddDocTag("Image Dynamic"); - AddDocTag(Tags::Manip); - - AddParameter(ParameterType_InputImage, "in", "Input image"); - SetParameterDescription("in", "Input image"); - - AddParameter(ParameterType_OutputImage, "out", "Output Image"); - SetParameterDescription("out", "Output image"); - - AddParameter(ParameterType_Int,"inv","Inside Value"); - SetParameterDescription("inv","Value given in the output mask to pixels that are not no data pixels"); - SetDefaultParameterInt("inv",1); - - AddParameter(ParameterType_Int,"outv","Outside Value"); - SetParameterDescription("outv","Value given in the output mask to pixels that are no data pixels"); - SetDefaultParameterInt("outv",0); - - AddRAMParameter(); - - // Doc example parameter settings - SetDocExampleParameterValue("in", "QB_Toulouse_Ortho_XS.tif"); - SetDocExampleParameterValue("out", "QB_Toulouse_Ortho_XS_nodatamask.tif uint8"); - SetDocExampleParameterValue("inv", "255"); - SetDocExampleParameterValue("outv", "0"); - } - - void DoUpdateParameters() - { - // Nothing to do here for the parameters : all are independent - } - - - void DoExecute() - { - m_Filter = FilterType::New(); - m_Filter->SetInsideValue(this->GetParameterInt("inv")); - m_Filter->SetOutsideValue(this->GetParameterInt("outv")); - m_Filter->SetInput(this->GetParameterImage("in")); - - SetParameterOutputImage("out",m_Filter->GetOutput()); - } - - FilterType::Pointer m_Filter; -}; - -} -} - -OTB_APPLICATION_EXPORT(otb::Wrapper::NoDataMask) - diff --git a/Modules/Core/Common/include/otbDecimateImageFilter.h b/Modules/Core/Common/include/otbDecimateImageFilter.h index d0edccc95bb698f120c46c632efcaa0e349828cb..a171a7670ee7ff27e7adf247faf6e93dfda1e2b8 100644 --- a/Modules/Core/Common/include/otbDecimateImageFilter.h +++ b/Modules/Core/Common/include/otbDecimateImageFilter.h @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Core/Common/include/otbDecimateImageFilter.txx b/Modules/Core/Common/include/otbDecimateImageFilter.txx index b6eeede4ff84046b54e118d783132535959918c9..554c2c6a900fa9d3d5bba9e22d671425a7921d56 100644 --- a/Modules/Core/Common/include/otbDecimateImageFilter.txx +++ b/Modules/Core/Common/include/otbDecimateImageFilter.txx @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Core/Common/include/otbImageRegionAdaptativeSplitter.txx b/Modules/Core/Common/include/otbImageRegionAdaptativeSplitter.txx index 154c73b8c4805ade35f63410d841b2999b2fe751..ef5b28192b5d1f658327d89fa9b8a0b0ec403610 100644 --- a/Modules/Core/Common/include/otbImageRegionAdaptativeSplitter.txx +++ b/Modules/Core/Common/include/otbImageRegionAdaptativeSplitter.txx @@ -107,10 +107,14 @@ ImageRegionAdaptativeSplitter<VImageDimension> // Now we can handle the case where we have a tile hint and a // non-trivial requested number of splits SizeType tilesPerDim, splitsPerDim; - - tilesPerDim[0] = (m_ImageRegion.GetSize()[0] + m_TileHint[0] -1) / m_TileHint[0]; - tilesPerDim[1] = (m_ImageRegion.GetSize()[1] + m_TileHint[1] -1) / m_TileHint[1]; - + IndexType firstTileCovered; + + // First, we need to get which tiles are covered by ROI + firstTileCovered[0] = m_ImageRegion.GetIndex()[0] / m_TileHint[0]; + firstTileCovered[1] = m_ImageRegion.GetIndex()[1] / m_TileHint[1]; + tilesPerDim[0] = (m_ImageRegion.GetIndex()[0] + m_ImageRegion.GetSize()[0] + m_TileHint[0] -1) / m_TileHint[0] - firstTileCovered[0]; + tilesPerDim[1] = (m_ImageRegion.GetIndex()[1] + m_ImageRegion.GetSize()[1] + m_TileHint[1] -1) / m_TileHint[1] - firstTileCovered[1]; + unsigned int totalTiles = tilesPerDim[0] * tilesPerDim[1]; // In this case, we have to group input tiles @@ -134,13 +138,14 @@ ImageRegionAdaptativeSplitter<VImageDimension> i = (i+1)%2; } + splitsPerDim[0] = tilesPerDim[0] / groupTiles[0]; + splitsPerDim[1] = tilesPerDim[1] / groupTiles[1]; // Handle the last small tile if any if(tilesPerDim[0] % groupTiles[0] > 0) splitsPerDim[0]++; - splitsPerDim[1] = tilesPerDim[1] / groupTiles[1]; if(tilesPerDim[1] % groupTiles[1] > 0) splitsPerDim[1]++; @@ -157,8 +162,8 @@ ImageRegionAdaptativeSplitter<VImageDimension> newSplitSize[0] = groupTiles[0] * m_TileHint[0]; newSplitSize[1] = groupTiles[1] * m_TileHint[1]; - newSplitIndex[0] = splitx * newSplitSize[0]; - newSplitIndex[1] = splity * newSplitSize[1]; + newSplitIndex[0] = firstTileCovered[0] * m_TileHint[0] + splitx * newSplitSize[0]; + newSplitIndex[1] = firstTileCovered[1] * m_TileHint[1] + splity * newSplitSize[1]; newSplit.SetIndex(newSplitIndex); newSplit.SetSize(newSplitSize); @@ -181,7 +186,9 @@ ImageRegionAdaptativeSplitter<VImageDimension> unsigned int i = 1; - while(totalTiles * (divideTiles[0] * divideTiles[1]) < m_RequestedNumberOfSplits) + // Exit condition if divideTiles=m_TileHint (i.e. no more subdivision available) + while(totalTiles * (divideTiles[0] * divideTiles[1]) < m_RequestedNumberOfSplits + && (divideTiles[0] < m_TileHint[0] || divideTiles[1] < m_TileHint[1])) { if(divideTiles[i] < m_TileHint[i]) { @@ -195,6 +202,8 @@ ImageRegionAdaptativeSplitter<VImageDimension> splitSize[0] = (m_TileHint[0] + divideTiles[0] - 1)/ divideTiles[0]; splitSize[1] = (m_TileHint[1] + divideTiles[1] - 1)/ divideTiles[1]; + RegionType tileHintRegion; + tileHintRegion.SetSize(m_TileHint); // Fill the tiling scheme for(unsigned int tiley = 0; tiley < tilesPerDim[1]; ++tiley) { @@ -208,19 +217,27 @@ ImageRegionAdaptativeSplitter<VImageDimension> RegionType newSplit; IndexType newSplitIndex; - newSplitIndex[0] = tilex * m_TileHint[0] + divx * splitSize[0]; - newSplitIndex[1] = tiley * m_TileHint[1] + divy * splitSize[1]; + newSplitIndex[0] = (tilex + firstTileCovered[0]) * m_TileHint[0] + divx * splitSize[0]; + newSplitIndex[1] = (tiley + firstTileCovered[1]) * m_TileHint[1] + divy * splitSize[1]; newSplit.SetIndex(newSplitIndex); newSplit.SetSize(splitSize); + tileHintRegion.SetIndex(0, tilex * m_TileHint[0]); + tileHintRegion.SetIndex(1, tiley * m_TileHint[1]); + bool cropped = newSplit.Crop(m_ImageRegion); // If newSplit could not be cropped, it means that it is // outside m_ImageRegion. In this case we ignore it. if(cropped) { - m_StreamVector.push_back(newSplit); + // check that the split stays inside its tile + cropped = newSplit.Crop(tileHintRegion); + if (cropped) + { + m_StreamVector.push_back(newSplit); + } } } } diff --git a/Modules/Core/Common/include/otbModelComponentBase.h b/Modules/Core/Common/include/otbModelComponentBase.h index cdf80a0fa23f9a2b55e079429e7d3519c0532ad4..f8956cd307f52042e506271f6d485cc51c9d8cc1 100644 --- a/Modules/Core/Common/include/otbModelComponentBase.h +++ b/Modules/Core/Common/include/otbModelComponentBase.h @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Some parts of this code are covered by the GET copyright. - See GETCopyright.txt for details. + Some parts of this code are covered by the IMT copyright. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Core/Common/include/otbModelComponentBase.txx b/Modules/Core/Common/include/otbModelComponentBase.txx index c3a130cedfccf448019a9b3fc86ecf1084746da6..bfdb3c7e0af35b5bbf60f11db46fb03049f5e781 100644 --- a/Modules/Core/Common/include/otbModelComponentBase.txx +++ b/Modules/Core/Common/include/otbModelComponentBase.txx @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Some parts of this code are covered by the GET copyright. - See GETCopyright.txt for details. + Some parts of this code are covered by the IMT copyright. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Core/Common/include/otbSubsampledImageRegionConstIterator.h b/Modules/Core/Common/include/otbSubsampledImageRegionConstIterator.h index ea8276f1677133d38b959bee714127db8ac933a6..ef49212f570bcebe112883c1cb192ee8ddd26017 100644 --- a/Modules/Core/Common/include/otbSubsampledImageRegionConstIterator.h +++ b/Modules/Core/Common/include/otbSubsampledImageRegionConstIterator.h @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Core/Common/include/otbSubsampledImageRegionConstIterator.txx b/Modules/Core/Common/include/otbSubsampledImageRegionConstIterator.txx index 58f1035b3adc70e4d87a28cd45a24472bfbb0bcc..1a9552d1d9475fd19c4741ebf99e31270d578028 100644 --- a/Modules/Core/Common/include/otbSubsampledImageRegionConstIterator.txx +++ b/Modules/Core/Common/include/otbSubsampledImageRegionConstIterator.txx @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Core/Common/include/otbSubsampledImageRegionIterator.h b/Modules/Core/Common/include/otbSubsampledImageRegionIterator.h index eb0e45d7d06350ce55ae0a1e7e49264ab622b95f..0fa6f966784b8e7335849e8fa19df498c8b39b67 100644 --- a/Modules/Core/Common/include/otbSubsampledImageRegionIterator.h +++ b/Modules/Core/Common/include/otbSubsampledImageRegionIterator.h @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Core/Common/test/CMakeLists.txt b/Modules/Core/Common/test/CMakeLists.txt index e32118293bc838491f5be7754ed53d22c35699b3..c40b6a289fdce16ec39937f9db531dbe9d61a38c 100644 --- a/Modules/Core/Common/test/CMakeLists.txt +++ b/Modules/Core/Common/test/CMakeLists.txt @@ -78,6 +78,36 @@ otb_add_test(NAME coTvImageRegionAdaptativeSplitterStripLargeStream COMMAND otbC ${TEMP}/coTvImageRegionAdaptativeSplitterStripLargeStreamOutput.txt ) +otb_add_test(NAME coTvImageRegionAdaptativeSplitterShiftedROILargeStream COMMAND otbCommonTestDriver + --compare-ascii ${NOTOL} + ${BASELINE_FILES}/coTvImageRegionAdaptativeSplitterShiftedROILargeStreamOutput.txt + ${TEMP}/coTvImageRegionAdaptativeSplitterShiftedROILargeStreamOutput.txt + otbImageRegionAdaptativeSplitter + 1000 1000 4000 4000 2000 2000 5 + ${TEMP}/coTvImageRegionAdaptativeSplitterShiftedROILargeStreamOutput.txt + ) + +otb_add_test(NAME coTvImageRegionAdaptativeSplitterShiftedROISmallStream COMMAND otbCommonTestDriver + --compare-ascii ${NOTOL} + ${BASELINE_FILES}/coTvImageRegionAdaptativeSplitterShiftedROISmallStreamOutput.txt + ${TEMP}/coTvImageRegionAdaptativeSplitterShiftedROISmallStreamOutput.txt + otbImageRegionAdaptativeSplitter + 1000 1000 4000 4000 2000 2000 10 + ${TEMP}/coTvImageRegionAdaptativeSplitterShiftedROISmallStreamOutput.txt + ) + +otb_add_test(NAME coTvImageRegionAdaptativeSplitterMissingLine COMMAND otbCommonTestDriver + otbImageRegionAdaptativeSplitter + 0 0 1000 1000 1000 1 37 + ${TEMP}/coTvImageRegionAdaptativeSplitterMissingLine.txt + ) + +otb_add_test(NAME coTvImageRegionAdaptativeSplitterDivideBlock COMMAND otbCommonTestDriver + otbImageRegionAdaptativeSplitter + 0 0 10 10 5 5 36 + ${TEMP}/coTvImageRegionAdaptativeSplitterDivideBlock.txt + ) + otb_add_test(NAME coTuRGBAPixelConverter COMMAND otbCommonTestDriver otbRGBAPixelConverterNew ) diff --git a/Modules/Core/Common/test/otbImageRegionAdaptativeSplitter.cxx b/Modules/Core/Common/test/otbImageRegionAdaptativeSplitter.cxx index 638993505239432d2926178eff637ca2b94c6720..66cc0ae45d7159fe3f84b945cdbaf2edf2a903bb 100644 --- a/Modules/Core/Common/test/otbImageRegionAdaptativeSplitter.cxx +++ b/Modules/Core/Common/test/otbImageRegionAdaptativeSplitter.cxx @@ -59,16 +59,63 @@ int otbImageRegionAdaptativeSplitter(int itkNotUsed(argc), char * argv[]) unsigned int nbSplits = splitter->GetNumberOfSplits(region, requestedNbSplits); + std::vector<RegionType> splits; outfile<<splitter<<std::endl; outfile<<"Split map: "<<std::endl; for(unsigned int i = 0; i < nbSplits; ++i) { - outfile<<"Split "<<i<<": "<<splitter->GetSplit(i, requestedNbSplits, region); + RegionType tmpRegion = splitter->GetSplit(i, requestedNbSplits, region); + splits.push_back(tmpRegion); + outfile<<"Split "<<i<<": "<<tmpRegion; } outfile.close(); + // Basic consistency check on split map + if (requestedNbSplits != nbSplits) + { + std::cout << "Wrong number of splits : got "<<nbSplits<<" , expected "<<requestedNbSplits<< std::endl; + } + IndexType tmpIndex; + for (unsigned int i=regionIndex[0] ; i<(regionIndex[0]+regionSize[0]) ; ++i) + { + for (unsigned int j=regionIndex[1] ; j<(regionIndex[1]+regionSize[1]) ; ++j) + { + tmpIndex[0] = i; + tmpIndex[1] = j; + unsigned int count = 0; + for (unsigned int k=0 ; k<nbSplits ; ++k ) + { + if (splits[k].IsInside(tmpIndex)) + { + count++; + } + } + if (count == 0) + { + std::cout << "Index ["<<i<<","<<j<<"] is missing in split map" << std::endl; + return EXIT_FAILURE; + } + if (count > 1) + { + std::cout << "Index ["<<i<<","<<j<<"] occurs more than once in the split map" << std::endl; + return EXIT_FAILURE; + } + } + } + + unsigned int pixelInSplit = 0; + for (unsigned int k=0 ; k<nbSplits ; ++k ) + { + pixelInSplit += splits[k].GetSize(0) * splits[k].GetSize(1); + } + if (pixelInSplit != regionSize[0]*regionSize[1]) + { + std::cout << "Wrong number of pixels in split : got "<<pixelInSplit << " , expected "<< regionSize[0]*regionSize[1] << std::endl; + return EXIT_FAILURE; + } + return EXIT_SUCCESS; } diff --git a/Modules/Core/ImageBase/include/otbNoDataHelper.h b/Modules/Core/ImageBase/include/otbNoDataHelper.h deleted file mode 100644 index 16bfdc4cd85f916804b59d8c7ee05828d47e1897..0000000000000000000000000000000000000000 --- a/Modules/Core/ImageBase/include/otbNoDataHelper.h +++ /dev/null @@ -1,75 +0,0 @@ -/*========================================================================= - - Program: ORFEO Toolbox - Language: C++ - Date: $Date$ - Version: $Revision$ - - - Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. - See OTBCopyright.txt for details. - - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ -#ifndef __otbNoDataHelper_h -#define __otbNoDataHelper_h -#include <vector> -#include <cassert> -#include "vnl/vnl_math.h" -#include <itkVariableLengthVector.h> - -namespace otb -{ -/** -* Test if the pixel corresponds to a no data pixel according to a -* vector of no data flags, and a vector of no data values. -* \param pixel The pixel to test -* \param flags A vector of size > 1 containing a flag per band to -* indicate if a no data value is available for this band -* \param values A vector of size > 1 corresponding to the no data -* value for each band. If flag is 0, the value will be ignored. -*/ -template<typename T> bool IsNoData(const T & pixel, const -std::vector<bool> & flags, const std::vector<double> & values) { - assert(flags.size()>0); - assert(values.size()>0); - - if(vnl_math_isnan((int)flags[0])) - return true; - - - if(flags[0]) - { - return (pixel == values[0]); - } - else - { - return false; - } -} -/** - * Specialization of IsNoData function to handle itk::VariableLengthVector - */ -template <typename T> bool IsNoData(const itk::VariableLengthVector<T> & pixel, const std::vector<bool> & flags, const std::vector<double> & values) -{ - assert(flags.size()>=pixel.Size()); - assert(values.size()>=pixel.Size()); - - for(unsigned int i = 0; i < pixel.Size();++i) - { - if(vnl_math_isnan(pixel[i]) || (flags[i] && (pixel[i] == values[i]))) - { - return true; - } - } - return false; -} - - -} // End namespace otb - -#endif diff --git a/Modules/Core/ImageBase/test/CMakeLists.txt b/Modules/Core/ImageBase/test/CMakeLists.txt index dd4ecc9d09b0a5477f4d0e66786ffeda21dab34c..46ff70cf251e17e8a4bd2be04073930a7dec7978 100644 --- a/Modules/Core/ImageBase/test/CMakeLists.txt +++ b/Modules/Core/ImageBase/test/CMakeLists.txt @@ -28,7 +28,7 @@ set(OTBImageBaseTests otbImageFunctionAdaptor.cxx otbMultiChannelExtractROINew.cxx otbMetaImageFunction.cxx - otbNoDataHelperTest.cxx + ) add_executable(otbImageBaseTestDriver ${OTBImageBaseTests}) @@ -825,6 +825,3 @@ otb_add_test(NAME ioTvOtbVectorImageTestRadarsat COMMAND otbImageBaseTestDriver otbVectorImageLegacyTest LARGEINPUT{/RADARSAT1/GOMA/SCENE01/} ${TEMP}/ioOtbVectorImageTestRadarsat.txt) - -otb_add_test(NAME coreImageBaseNoDataHelperTest COMMAND otbImageBaseTestDriver - otbNoDataHelperTest) diff --git a/Modules/Core/ImageBase/test/otbFlexibleDistanceWithMissingValue.cxx b/Modules/Core/ImageBase/test/otbFlexibleDistanceWithMissingValue.cxx index ed2a12c0257798f51ca7bf487d189c3f6b4a87cc..8d468f33dcf494d93733375596c7353a031e9513 100644 --- a/Modules/Core/ImageBase/test/otbFlexibleDistanceWithMissingValue.cxx +++ b/Modules/Core/ImageBase/test/otbFlexibleDistanceWithMissingValue.cxx @@ -10,7 +10,7 @@ See OTBCopyright.txt for details. Copyright (c) Institut Telecom; Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Core/ImageBase/test/otbFlexibleDistanceWithMissingValueNew.cxx b/Modules/Core/ImageBase/test/otbFlexibleDistanceWithMissingValueNew.cxx index d4a76c8923e8bf8d33375e2e4e1d2240510f4411..d6983430adbcdf6683d9e0e22118c631637d3dac 100644 --- a/Modules/Core/ImageBase/test/otbFlexibleDistanceWithMissingValueNew.cxx +++ b/Modules/Core/ImageBase/test/otbFlexibleDistanceWithMissingValueNew.cxx @@ -10,7 +10,7 @@ See OTBCopyright.txt for details. Copyright (c) Institut Telecom; Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Core/ImageBase/test/otbImageBaseTestDriver.cxx b/Modules/Core/ImageBase/test/otbImageBaseTestDriver.cxx index dcf63d236ebad2c066389989da824836833ab7d9..fc275609cb19c75305902543f926fc37e3cb3f83 100644 --- a/Modules/Core/ImageBase/test/otbImageBaseTestDriver.cxx +++ b/Modules/Core/ImageBase/test/otbImageBaseTestDriver.cxx @@ -31,5 +31,4 @@ void RegisterTests() REGISTER_TEST(otbMultiChannelExtractROINew); REGISTER_TEST(otbMetaImageFunction); REGISTER_TEST(otbMetaImageFunctionNew); - REGISTER_TEST(otbNoDataHelperTest); } diff --git a/Modules/Core/Metadata/include/otbImageMetadataInterfaceBase.h b/Modules/Core/Metadata/include/otbImageMetadataInterfaceBase.h index d9209574b68c59c32b82e7c7894e3855e988a28c..8340cedac73674309f124cc4c8b24499dc3c34b3 100644 --- a/Modules/Core/Metadata/include/otbImageMetadataInterfaceBase.h +++ b/Modules/Core/Metadata/include/otbImageMetadataInterfaceBase.h @@ -107,6 +107,12 @@ public: double GetGCPZ(unsigned int GCPnum) const; // otbMetadataGetGCPnumMacro(GCPZ, double, GCPnum, unsigned int); + /** + * Get The no data flags if existing + * return False otherwise + */ + bool GetNoDataFlags(std::vector<bool> & flags, std::vector<double> & values) const; + /** Get the six coefficients of affine geoTtransform. */ VectorType GetGeoTransform() const; diff --git a/Modules/Core/Metadata/include/otbNoDataHelper.h b/Modules/Core/Metadata/include/otbNoDataHelper.h new file mode 100644 index 0000000000000000000000000000000000000000..57d927c78fb7bf737e11e3d6663b3f60cd52d828 --- /dev/null +++ b/Modules/Core/Metadata/include/otbNoDataHelper.h @@ -0,0 +1,165 @@ +/*========================================================================= + + Program: ORFEO Toolbox + Language: C++ + Date: $Date$ + Version: $Revision$ + + + Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. + See OTBCopyright.txt for details. + + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __otbNoDataHelper_h +#define __otbNoDataHelper_h +#include <vector> +#include <cassert> +#include "vnl/vnl_math.h" +#include <itkVariableLengthVector.h> + +namespace itk +{ +class MetaDataDictionary; +} + +namespace otb +{ + +/** + * Reads no data flag from the MetaDataDictionnary dict to flags and values + * vectors. Returns true upon success. + */ +bool ReadNoDataFlags(const itk::MetaDataDictionary& dict, std::vector<bool> & flags, std::vector<double> & values); + +/** + * Write no data flags to the MetaDataDictionnary dict from flags and values + * vectors. Returns true upon success. + */ +void WriteNoDataFlags(const std::vector<bool> & flags, const std::vector<double> & values, itk::MetaDataDictionary& dict); + +/** +* Test if the pixel corresponds to a no data pixel according to a +* vector of no data flags, and a vector of no data values. +* \param pixel The pixel to test +* \param flags A vector of size > 1 containing a flag per band to +* indicate if a no data value is available for this band +* \param values A vector of size > 1 corresponding to the no data +* value for each band. If flag is 0, the value will be ignored. +* \param nanIsNoData If true, NaN values will be reported as no-data. +*/ +template<typename T> bool IsNoData(const T & pixel, const + std::vector<bool> & flags, const std::vector<double> & values, bool nanIsNoData = false) { + assert(flags.size()>0); + assert(values.size()>0); + + if(nanIsNoData && vnl_math_isnan(values[0])) + return true; + + + if(flags[0]) + { + return (pixel == values[0]); + } + else + { + return false; + } +} + +/** +* Reads a pixel and change the no data value if it is found. No data +* value is changed either if the pixel value is NaN or if the pixel +* value equals the no data value and flag is true. +* +* \param pixel The pixel to process \param flags A vector of size > 1 +* containing a flag per band to indicate if a no data value is +* available for this band +* \param values A vector of size > 1 corresponding to the current no data +* value for each band. If flag is 0, the value will be ignored. +* \param newValues A vector of size > 1 corresponding to the new no data +* value for each band. If flag is 0, the value will be ignored +* \param nanIsNoData If true, NaN values will be considered as no-data +* and changed as well. +* +*/ +template<typename T> T ChangeNoData(const T & pixel, const + std::vector<bool> & flags, + const std::vector<double> & values, + const std::vector<double> & newValues, + bool nanIsNoData = false) { + assert(flags.size()>0); + assert(values.size()>0); + assert(newValues.size()>0); + + if(nanIsNoData && vnl_math_isnan(pixel)) + { + return static_cast<T>(newValues[0]); + } + + if(flags[0] && pixel == values[0]) + { + return static_cast<T>(newValues[0]); + } + return pixel; +} + + +/** + * Specialization of IsNoData function to handle itk::VariableLengthVector + */ +template <typename T> bool IsNoData(const itk::VariableLengthVector<T> & pixel, const std::vector<bool> & flags, const std::vector<double> & values, bool nanIsNoData = false) +{ + assert(flags.size()>=pixel.Size()); + assert(values.size()>=pixel.Size()); + + for(unsigned int i = 0; i < pixel.Size();++i) + { + if((nanIsNoData && vnl_math_isnan(pixel[i])) || (flags[i] && (pixel[i] == values[i]))) + { + return true; + } + } + return false; +} + + +/** + * Specialization of ChangeNoData function to handle itk::VariableLengthVector + */ +template <typename T> itk::VariableLengthVector<T> ChangeNoData(const itk::VariableLengthVector<T> & pixel, + const std::vector<bool> & flags, + const std::vector<double> & values, + const std::vector<double> & newValues, + bool nanIsNoData = false) +{ + assert(flags.size()>=pixel.Size()); + assert(values.size()>=pixel.Size()); + assert(newValues.size()>=pixel.Size()); + + itk::VariableLengthVector<T> outPixel(pixel.Size()); + + for(unsigned int i = 0; i < pixel.Size();++i) + { + if((nanIsNoData && vnl_math_isnan(pixel[i])) || (flags[i] && (pixel[i] == values[i]))) + { + outPixel[i] = newValues[i]; + } + else + { + outPixel[i] = pixel[i]; + } + } + + return outPixel; +} + + + +} // End namespace otb + +#endif diff --git a/Modules/Core/Metadata/otb-module.cmake b/Modules/Core/Metadata/otb-module.cmake index afaff0b86e39f5762ddb10689628e7ebf1be6e61..240e6a3ee1cec76586a97c0078a34861dfb410ee 100644 --- a/Modules/Core/Metadata/otb-module.cmake +++ b/Modules/Core/Metadata/otb-module.cmake @@ -9,12 +9,12 @@ otb_module(OTBMetadata OTBITK OTBOSSIMAdapters OTBCommon - + TEST_DEPENDS OTBTestKernel OTBImageIO OTBImageBase - + DESCRIPTION "${DOCUMENTATION}" ) diff --git a/Modules/Core/Metadata/src/CMakeLists.txt b/Modules/Core/Metadata/src/CMakeLists.txt index bc3c9900f779896fc9396b52c4e36f60c0d77b57..458188d5246599d101d8cfa68384704f8e7929ae 100644 --- a/Modules/Core/Metadata/src/CMakeLists.txt +++ b/Modules/Core/Metadata/src/CMakeLists.txt @@ -24,6 +24,7 @@ set(OTBMetadata_SRC otbSarImageMetadataInterface.cxx otbPleiadesImageMetadataInterfaceFactory.cxx otbTerraSarImageMetadataInterfaceFactory.cxx + otbNoDataHelper.cxx ) add_library(OTBMetadata ${OTBMetadata_SRC}) diff --git a/Modules/Core/Metadata/src/otbImageMetadataInterfaceBase.cxx b/Modules/Core/Metadata/src/otbImageMetadataInterfaceBase.cxx index 784f5847bca5369f0077f9b6441443aae5a35550..013e4f9c77d4932f351b2c17acfd04f4e3d2944e 100644 --- a/Modules/Core/Metadata/src/otbImageMetadataInterfaceBase.cxx +++ b/Modules/Core/Metadata/src/otbImageMetadataInterfaceBase.cxx @@ -18,9 +18,11 @@ #include "otbImageMetadataInterfaceBase.h" +#include "otbNoDataHelper.h" #include "itkMetaDataObject.h" #include "itksys/SystemTools.hxx" + namespace otb { @@ -222,6 +224,12 @@ ImageMetadataInterfaceBase::GetGCPZ(unsigned int GCPnum) const else return (0); } +bool +ImageMetadataInterfaceBase::GetNoDataFlags(std::vector<bool> & flags, std::vector<double> & values) const +{ + return ReadNoDataFlags(this->GetMetaDataDictionary(),flags,values); +} + ImageMetadataInterfaceBase::VectorType ImageMetadataInterfaceBase::GetGeoTransform() const { diff --git a/Modules/Core/Metadata/src/otbNoDataHelper.cxx b/Modules/Core/Metadata/src/otbNoDataHelper.cxx new file mode 100644 index 0000000000000000000000000000000000000000..b5edf9dc49145ba6aae8e5089cc7a11335bf7037 --- /dev/null +++ b/Modules/Core/Metadata/src/otbNoDataHelper.cxx @@ -0,0 +1,43 @@ +/*========================================================================= + + Program: ORFEO Toolbox + Language: C++ + Date: $Date$ + Version: $Revision$ + + + Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. + See OTBCopyright.txt for details. + + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#include "otbNoDataHelper.h" + +#include "itkMetaDataDictionary.h" +#include "itkMetaDataObject.h" +#include "otbMetaDataKey.h" + +namespace otb +{ + +bool ReadNoDataFlags(const itk::MetaDataDictionary& dict, std::vector<bool> & flags, std::vector<double> & values) +{ + bool ret = itk::ExposeMetaData<std::vector<bool> >(dict,MetaDataKey::NoDataValueAvailable,flags); + + if (ret) + ret = itk::ExposeMetaData<std::vector<double> >(dict,MetaDataKey::NoDataValue,values); + + return ret; +} + +void WriteNoDataFlags(const std::vector<bool> & flags, const std::vector<double> & values, itk::MetaDataDictionary& dict) +{ + itk::EncapsulateMetaData<std::vector<bool> >(dict,MetaDataKey::NoDataValueAvailable,flags); + itk::EncapsulateMetaData<std::vector<double> >(dict,MetaDataKey::NoDataValue,values); +} + +} // End namespace otb diff --git a/Modules/Core/Metadata/test/CMakeLists.txt b/Modules/Core/Metadata/test/CMakeLists.txt index 340324421e76181795985d0e7fea068ddb2fab43..b48fbffaef79197293daba9fec698e7fe0581bfb 100644 --- a/Modules/Core/Metadata/test/CMakeLists.txt +++ b/Modules/Core/Metadata/test/CMakeLists.txt @@ -22,6 +22,7 @@ otbTerraSarImageMetadataInterfaceNew.cxx otbWorldView2ImageMetadataInterfaceNew.cxx otbDefaultImageMetadataInterface.cxx otbImageMetadataInterfaceTest2.cxx +otbNoDataHelperTest.cxx ) add_executable(otbMetadataTestDriver ${OTBMetadataTests}) @@ -351,3 +352,7 @@ foreach( current_file ${GenericTestSPOT6_DATA_INPUTS} ) ${TEMP}/ioTvOpticalImageMetadataInterface_${current_type}_OUT.txt ) endforeach() + + +otb_add_test(NAME coreMetaDataNoDataHelperTest COMMAND otbMetadataTestDriver + otbNoDataHelperTest) diff --git a/Modules/Core/Metadata/test/otbMetadataTestDriver.cxx b/Modules/Core/Metadata/test/otbMetadataTestDriver.cxx index d2dfb191518574ccf1829046d59c2ebb5b2550c0..cd06f2f46e9f46fb412b1f30a278374070ac7405 100644 --- a/Modules/Core/Metadata/test/otbMetadataTestDriver.cxx +++ b/Modules/Core/Metadata/test/otbMetadataTestDriver.cxx @@ -21,4 +21,5 @@ void RegisterTests() REGISTER_TEST(otbWorldView2ImageMetadataInterfaceNew); REGISTER_TEST(otbDefaultImageMetadataInterface); REGISTER_TEST(otbImageMetadataInterfaceTest2); + REGISTER_TEST(otbNoDataHelperTest); } diff --git a/Modules/Core/ImageBase/test/otbNoDataHelperTest.cxx b/Modules/Core/Metadata/test/otbNoDataHelperTest.cxx similarity index 91% rename from Modules/Core/ImageBase/test/otbNoDataHelperTest.cxx rename to Modules/Core/Metadata/test/otbNoDataHelperTest.cxx index 5b32ec74768b446b80c18c3e2d4a643971e5246d..4db9ba0ab9f1bd23ff180ca3edf7577476895d13 100644 --- a/Modules/Core/ImageBase/test/otbNoDataHelperTest.cxx +++ b/Modules/Core/Metadata/test/otbNoDataHelperTest.cxx @@ -17,6 +17,7 @@ =========================================================================*/ #include "otbNoDataHelper.h" +#include "itkMetaDataDictionary.h" #include "otbMacro.h" int otbNoDataHelperTest(int itkNotUsed(argc),char * itkNotUsed(argv) []) @@ -24,6 +25,11 @@ int otbNoDataHelperTest(int itkNotUsed(argc),char * itkNotUsed(argv) []) std::vector<bool> b1(1,true); std::vector<double> v1(1,0); + itk::MetaDataDictionary dict; + + otb::WriteNoDataFlags(b1,v1,dict); + otb::ReadNoDataFlags(dict,b1,v1); + otbControlConditionTestMacro(otb::IsNoData(10,b1,v1)," wrong output of IsNoData function"); otbControlConditionTestMacro(!otb::IsNoData(0,b1,v1)," wrong output of IsNoData function"); b1[0]=false; diff --git a/Modules/Feature/Edge/test/otbHorizontalSobelVectorImageFilter.cxx b/Modules/Feature/Edge/test/otbHorizontalSobelVectorImageFilter.cxx index 8f77718c38ddbddfd875a63c9a5a321a5d0928f1..a1464ebb8ff2a56b038b8bebc1468e2672d1b028 100644 --- a/Modules/Feature/Edge/test/otbHorizontalSobelVectorImageFilter.cxx +++ b/Modules/Feature/Edge/test/otbHorizontalSobelVectorImageFilter.cxx @@ -10,7 +10,7 @@ See OTBCopyright.txt for details. Copyright (c) Institut Telecom; Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Feature/Edge/test/otbSobelVectorImageFilter.cxx b/Modules/Feature/Edge/test/otbSobelVectorImageFilter.cxx index e7f0ff418e62447e8930906de208bc73e5f0d3b3..23cad002fa12a3bd9b914e55a30dbf3f3fa2c61f 100644 --- a/Modules/Feature/Edge/test/otbSobelVectorImageFilter.cxx +++ b/Modules/Feature/Edge/test/otbSobelVectorImageFilter.cxx @@ -10,7 +10,7 @@ See OTBCopyright.txt for details. Copyright (c) Institut Telecom; Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Feature/Edge/test/otbVerticalSobelVectorImageFilter.cxx b/Modules/Feature/Edge/test/otbVerticalSobelVectorImageFilter.cxx index 5a8fffaa3fcd91285a508a38a0b5c7c7d4df5e95..a8439b128914ce180f4be2235d232c1f0116e3e5 100644 --- a/Modules/Feature/Edge/test/otbVerticalSobelVectorImageFilter.cxx +++ b/Modules/Feature/Edge/test/otbVerticalSobelVectorImageFilter.cxx @@ -10,7 +10,7 @@ See OTBCopyright.txt for details. Copyright (c) Institut Telecom; Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Filtering/ChangeDetection/include/otbKullbackLeiblerDistanceImageFilter.h b/Modules/Filtering/ChangeDetection/include/otbKullbackLeiblerDistanceImageFilter.h index 84ea1ceee6564a4e24529b3d7fc922e9693d6915..cba75ee655fa111f68e62e2583aa81c98a471a20 100644 --- a/Modules/Filtering/ChangeDetection/include/otbKullbackLeiblerDistanceImageFilter.h +++ b/Modules/Filtering/ChangeDetection/include/otbKullbackLeiblerDistanceImageFilter.h @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. - See GETCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Filtering/ChangeDetection/include/otbKullbackLeiblerDistanceImageFilter.txx b/Modules/Filtering/ChangeDetection/include/otbKullbackLeiblerDistanceImageFilter.txx index 809e374422d982e0f414a4b5e3fc771fe320e676..b309f580dd3a8f64474af61c138c8931bfbc27c7 100644 --- a/Modules/Filtering/ChangeDetection/include/otbKullbackLeiblerDistanceImageFilter.txx +++ b/Modules/Filtering/ChangeDetection/include/otbKullbackLeiblerDistanceImageFilter.txx @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. - See GETCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Filtering/ChangeDetection/include/otbKullbackLeiblerProfileImageFilter.h b/Modules/Filtering/ChangeDetection/include/otbKullbackLeiblerProfileImageFilter.h index 370a0384a24c9032b34934963fa3d2613ddc8087..d4a5e93c7fbd588e8837e1e98b9d5a924ae9c44c 100644 --- a/Modules/Filtering/ChangeDetection/include/otbKullbackLeiblerProfileImageFilter.h +++ b/Modules/Filtering/ChangeDetection/include/otbKullbackLeiblerProfileImageFilter.h @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Some parts of this code are covered by the GET copyright. - See GETCopyright.txt for details. + Some parts of this code are covered by the IMT copyright. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even diff --git a/Modules/Filtering/ChangeDetection/include/otbKullbackLeiblerProfileImageFilter.txx b/Modules/Filtering/ChangeDetection/include/otbKullbackLeiblerProfileImageFilter.txx index d49f78abc37746079834cd246f39ee281b70761f..1620df7cd64f5851eb1d7a7c8f4e1aee8976738e 100644 --- a/Modules/Filtering/ChangeDetection/include/otbKullbackLeiblerProfileImageFilter.txx +++ b/Modules/Filtering/ChangeDetection/include/otbKullbackLeiblerProfileImageFilter.txx @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Some parts of this code are covered by the GET copyright. - See GETCopyright.txt for details. + Some parts of this code are covered by the IMT copyright. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even diff --git a/Modules/Filtering/ChangeDetection/include/otbKullbackLeiblerSupervizedDistanceImageFilter.h b/Modules/Filtering/ChangeDetection/include/otbKullbackLeiblerSupervizedDistanceImageFilter.h index 511f219c2b421bf6772c7d10a885c4d8d52d1ac8..5498cc9cac67f24a45db362f15a7db469054ac5d 100644 --- a/Modules/Filtering/ChangeDetection/include/otbKullbackLeiblerSupervizedDistanceImageFilter.h +++ b/Modules/Filtering/ChangeDetection/include/otbKullbackLeiblerSupervizedDistanceImageFilter.h @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. - See GETCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Filtering/ChangeDetection/include/otbKullbackLeiblerSupervizedDistanceImageFilter.txx b/Modules/Filtering/ChangeDetection/include/otbKullbackLeiblerSupervizedDistanceImageFilter.txx index f0454a6b8031c808b050294bb1cf7bc3906bbcdc..ab78083eda84b40169395d8e0dcb78958260fa76 100644 --- a/Modules/Filtering/ChangeDetection/include/otbKullbackLeiblerSupervizedDistanceImageFilter.txx +++ b/Modules/Filtering/ChangeDetection/include/otbKullbackLeiblerSupervizedDistanceImageFilter.txx @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. - See GETCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Filtering/DimensionalityReduction/test/otbAngularProjectionBinaryImageFilter.cxx b/Modules/Filtering/DimensionalityReduction/test/otbAngularProjectionBinaryImageFilter.cxx index 8a4e4698fcbaee9db714a62a32c95e03cc2f5088..3fa0231e66b61b5145d5126b6c05163ee7d1acc2 100644 --- a/Modules/Filtering/DimensionalityReduction/test/otbAngularProjectionBinaryImageFilter.cxx +++ b/Modules/Filtering/DimensionalityReduction/test/otbAngularProjectionBinaryImageFilter.cxx @@ -10,7 +10,7 @@ See OTBCopyright.txt for details. Copyright (c) Institut Telecom; Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Filtering/DimensionalityReduction/test/otbLocalActivityVectorImageFilter.cxx b/Modules/Filtering/DimensionalityReduction/test/otbLocalActivityVectorImageFilter.cxx index 52c300533c90bd92c8f6b03636519e4a63f51b8a..c5ff2f8d53f45cdcda76815b82a286884d50fecc 100644 --- a/Modules/Filtering/DimensionalityReduction/test/otbLocalActivityVectorImageFilter.cxx +++ b/Modules/Filtering/DimensionalityReduction/test/otbLocalActivityVectorImageFilter.cxx @@ -10,7 +10,7 @@ See OTBCopyright.txt for details. Copyright (c) Institut Telecom; Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Filtering/ImageManipulation/include/otbBoxAndWhiskerImageFilter.h b/Modules/Filtering/ImageManipulation/include/otbBoxAndWhiskerImageFilter.h index 8197ec2e66992e6b22caf9c1df006398735b0dd0..7836509dd106b9d7a231c641c08946bb8bae2fe9 100644 --- a/Modules/Filtering/ImageManipulation/include/otbBoxAndWhiskerImageFilter.h +++ b/Modules/Filtering/ImageManipulation/include/otbBoxAndWhiskerImageFilter.h @@ -10,7 +10,7 @@ See OTBCopyright.txt for details. Copyright (c) Institut Telecom; Telecom bretagne. All rights reserved. - See ITCopyright.txt for details. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even diff --git a/Modules/Filtering/ImageManipulation/include/otbBoxAndWhiskerImageFilter.txx b/Modules/Filtering/ImageManipulation/include/otbBoxAndWhiskerImageFilter.txx index 9863ae1b2f68d9d0838c05e58fd6e516311c65c9..f15af8aef16fbf0764a3f9d9b561276898ddadf6 100644 --- a/Modules/Filtering/ImageManipulation/include/otbBoxAndWhiskerImageFilter.txx +++ b/Modules/Filtering/ImageManipulation/include/otbBoxAndWhiskerImageFilter.txx @@ -10,7 +10,7 @@ See OTBCopyright.txt for details. Copyright (c) Institut Telecom; Telecom bretagne. All rights reserved. - See ITCopyright.txt for details. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even diff --git a/Modules/Filtering/ImageManipulation/include/otbChangeNoDataValueFilter.h b/Modules/Filtering/ImageManipulation/include/otbChangeNoDataValueFilter.h new file mode 100644 index 0000000000000000000000000000000000000000..59d4fca6e387e8dae4588678c76a479b91c5ed01 --- /dev/null +++ b/Modules/Filtering/ImageManipulation/include/otbChangeNoDataValueFilter.h @@ -0,0 +1,178 @@ +/*========================================================================= + + Program: ORFEO Toolbox + Language: C++ + Date: $Date$ + Version: $Revision$ + + + Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. + See OTBCopyright.txt for details. + + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __otbChangeNoDataValueFilter_h +#define __otbChangeNoDataValueFilter_h + +#include "itkUnaryFunctorImageFilter.h" +#include "itkMetaDataObject.h" +#include "otbMetaDataKey.h" +#include "otbNoDataHelper.h" + +namespace otb +{ +namespace Functor +{ +/** \class ChangeNoDataFunctor + * \brief Functor used by ChangeNoDataValueFilter + * + * See ChangeNoDataValueFilter for complete documentation. + * \ingroup OTBImageManipulation + */ +template <typename TInputPixel, typename TOutputPixel> +class ChangeNoDataFunctor +{ +public: + ChangeNoDataFunctor(): + m_Flags(), + m_Values(), + m_NewValues(), + m_NaNIsNoData(false) + {} + virtual ~ChangeNoDataFunctor(){} + + inline TOutputPixel operator()(const TInputPixel& in) const + { + return otb::ChangeNoData(in,m_Flags,m_Values,m_NewValues,m_NaNIsNoData); + } + + std::vector<bool> m_Flags; + std::vector<double> m_Values; + std::vector<double> m_NewValues; + bool m_NaNIsNoData; +}; + +} // End namespace Functor + +/** \class ChangeNoDataValueFilter + * \brief Change no-data flags and values and replace them in image + * + * This filter reads the no-data flags (a boolean vector indicating + * for each band if a no-data value exists) and values (the actual + * value to be used as no-data for each band) from + * MetaDataDictionary, and allows to change this value. + * + * The algorithm is the following: for each pixel, for each channel + * in the pixel, if there is a no-data value for this channel + * (according to no-data flags) and the current channel value equals + * to the no-data value set for this channel, then the value is + * changed for the new no-data value specified by the + * users. Otherwise, value remains untouched. + * + * If NaNIsNoData is true: + * - NaN values will be considered as no data and replaced as well + * - Output image will have no-data flags and values for all bands + * + * If NaNIsNoData is false: + * - Band for which input no-data flags is false will remain + * untouched + * - Output image will have no-data flags and values only for bands + * for which input no-data flag is true. + * + * \ingroup Streamed + * \ingroup MultiThreaded + * \ingroup OTBImageManipulation + */ +template <typename TInputImage, typename TOutputImage> +class ChangeNoDataValueFilter + : public itk::UnaryFunctorImageFilter<TInputImage, + TOutputImage, + Functor::ChangeNoDataFunctor<typename TInputImage::PixelType, + typename TOutputImage::PixelType> > +{ +public: + typedef Functor::ChangeNoDataFunctor<typename TInputImage::PixelType,typename TOutputImage::PixelType> FunctorType; + + typedef ChangeNoDataValueFilter Self; + typedef itk::UnaryFunctorImageFilter<TInputImage, + TOutputImage, + FunctorType> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** Type macro */ + itkNewMacro(Self); + + /** Creation through object factory macro */ + itkTypeMacro(ChangeNoDataValueFilter, itk::ImageToImageFilter); + + /** + * Set the new no-data values + * \param newValues The vector of new no-data values (size should be + * >= to number of bands) + */ + void SetNewNoDataValues(std::vector<double> & newValues) + { + this->GetFunctor().m_NewValues = newValues; + } + + /** + * Set the NaN is no data flags + * \param nanIsNoData If true, NaN values will be considered as + * no-data as well (default is false) + */ + void SetNaNIsNoData(bool nanIsNoData) + { + this->GetFunctor().m_NaNIsNoData = nanIsNoData; + } + +protected: + ChangeNoDataValueFilter() + {} + + virtual ~ChangeNoDataValueFilter() + {} + + virtual void GenerateOutputInformation() + { + Superclass::GenerateOutputInformation(); + + std::vector<bool> noDataValueAvailable; + std::vector<double> noDataValues; + + bool ret = ReadNoDataFlags(this->GetInput()->GetMetaDataDictionary(),noDataValueAvailable,noDataValues); + + if(!ret) + { + noDataValueAvailable.resize(this->GetInput()->GetNumberOfComponentsPerPixel(),false); + noDataValues.resize(this->GetInput()->GetNumberOfComponentsPerPixel(),0); + } + + this->GetFunctor().m_Flags = noDataValueAvailable; + this->GetFunctor().m_Values = noDataValues; + + std::vector<bool> flags = noDataValueAvailable; + + if(this->GetFunctor().m_NaNIsNoData) + { + flags = std::vector<bool>(flags.size(),true); + } + + WriteNoDataFlags(flags,this->GetFunctor().m_NewValues,this->GetOutput()->GetMetaDataDictionary()); + } + +private: + ChangeNoDataValueFilter(const Self&); // purposely not implemented + void operator =(const Self&); // purposely not implemented + +}; + +} // End namespace otb + + + +#endif diff --git a/Modules/Filtering/ImageManipulation/include/otbEuclideanDistanceMetricWithMissingValue.h b/Modules/Filtering/ImageManipulation/include/otbEuclideanDistanceMetricWithMissingValue.h index e92979c13ae23dc503c4a7a85338f9d5b3018c00..62bbeff2bb2ac17fbce7c6c4f1b7b9a5597f2189 100644 --- a/Modules/Filtering/ImageManipulation/include/otbEuclideanDistanceMetricWithMissingValue.h +++ b/Modules/Filtering/ImageManipulation/include/otbEuclideanDistanceMetricWithMissingValue.h @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Filtering/ImageManipulation/include/otbEuclideanDistanceMetricWithMissingValuePow2.h b/Modules/Filtering/ImageManipulation/include/otbEuclideanDistanceMetricWithMissingValuePow2.h index 6b0d7f4431a4343e990889f1a0686723e4301d0f..6aa3b2e47cc44848247961a76f5844ff5965643b 100644 --- a/Modules/Filtering/ImageManipulation/include/otbEuclideanDistanceMetricWithMissingValuePow2.h +++ b/Modules/Filtering/ImageManipulation/include/otbEuclideanDistanceMetricWithMissingValuePow2.h @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Filtering/ImageManipulation/include/otbEuclideanDistanceMetricWithMissingValuePow2.txx b/Modules/Filtering/ImageManipulation/include/otbEuclideanDistanceMetricWithMissingValuePow2.txx index f83dcc3e59ce9ae73c267aaf521a845b2b9da12e..37c2115f0f2869d4b26bc0490875db58a67eb551 100644 --- a/Modules/Filtering/ImageManipulation/include/otbEuclideanDistanceMetricWithMissingValuePow2.txx +++ b/Modules/Filtering/ImageManipulation/include/otbEuclideanDistanceMetricWithMissingValuePow2.txx @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Filtering/ImageManipulation/include/otbFlexibleDistanceWithMissingValue.h b/Modules/Filtering/ImageManipulation/include/otbFlexibleDistanceWithMissingValue.h index 0df9e91ab920e2263f7cc9c8568d4d84f0d094da..2c948872edaced2683511424babdae1b35ab8d41 100644 --- a/Modules/Filtering/ImageManipulation/include/otbFlexibleDistanceWithMissingValue.h +++ b/Modules/Filtering/ImageManipulation/include/otbFlexibleDistanceWithMissingValue.h @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Filtering/ImageManipulation/include/otbFlexibleDistanceWithMissingValue.txx b/Modules/Filtering/ImageManipulation/include/otbFlexibleDistanceWithMissingValue.txx index c8b77afd3556a93a00f381bea23ea3d97e6a8d39..9bdb74433f09aa97e0fbd201a90b5b30f3861676 100644 --- a/Modules/Filtering/ImageManipulation/include/otbFlexibleDistanceWithMissingValue.txx +++ b/Modules/Filtering/ImageManipulation/include/otbFlexibleDistanceWithMissingValue.txx @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Filtering/ImageManipulation/include/otbImageToNoDataMaskFilter.h b/Modules/Filtering/ImageManipulation/include/otbImageToNoDataMaskFilter.h index 02e09dd22ec43533330cf59a4a41345d5aaa7570..a790b37a0ea031c3695ac7fcb8058d313f51e0ea 100644 --- a/Modules/Filtering/ImageManipulation/include/otbImageToNoDataMaskFilter.h +++ b/Modules/Filtering/ImageManipulation/include/otbImageToNoDataMaskFilter.h @@ -27,6 +27,12 @@ namespace otb { namespace Functor { +/** \class NoDataFunctor + * \brief Functor used by ImageToNoDataMaskFilter + * + * See ImageToNoDataMaskFilter for complete documentation. + * \ingroup OTBImageManipulation + */ template <typename TInputPixel, typename TOutputPixel> class NoDataFunctor { @@ -35,25 +41,42 @@ public: m_Flags(), m_Values(), m_OutsideValue(0), - m_InsideValue(1) + m_InsideValue(1), + m_NaNIsNoData(false) {} virtual ~NoDataFunctor(){} inline TOutputPixel operator()(const TInputPixel& in) const { - return otb::IsNoData(in,m_Flags,m_Values)?m_OutsideValue:m_InsideValue; + return otb::IsNoData(in,m_Flags,m_Values,m_NaNIsNoData)?m_OutsideValue:m_InsideValue; } std::vector<bool> m_Flags; std::vector<double> m_Values; TOutputPixel m_OutsideValue; TOutputPixel m_InsideValue; + bool m_NaNIsNoData; }; } // End namespace Functor - +/** \class ImageToNoDataMaskFilter + * \brief Builds a no-data mask image from no-data flags and values + * + * This filter reads the no-data flags (a boolean vector indicating + * for each band if a no-data value exists) and values (the actual + * value to be used as no-data for each band) from + * MetaDataDictionary, and builds a binary mask indicating presence + * or absence of no-data for each pixel. + * + * If NaNIsNoData is true, NaN pixels will also be considered as + * no-data pixels. + * + * \ingroup Streamed + * \ingroup MultiThreaded + * \ingroup OTBImageManipulation + */ template <typename TInputImage, typename TOutputImage> class ImageToNoDataMaskFilter : public itk::UnaryFunctorImageFilter<TInputImage, @@ -77,15 +100,31 @@ public: /** Creation through object factory macro */ itkTypeMacro(SpectralAngleDistanceImageFilter, itk::ImageToImageFilter); + /** + * Set inside value of output mask. This value will be used to + * indicate absence of no-data for the pixel in the output mask + */ void SetInsideValue(const typename TOutputImage::PixelType & value) { this->GetFunctor().m_InsideValue = value; } - + /** + * Set outside value of output mask. This value will be used to + * indicate presence of no-data for the pixel in the output mask + */ void SetOutsideValue(const typename TOutputImage::PixelType & value) { this->GetFunctor().m_OutsideValue = value; } + /** + * Set the NaN is no data flags + * \param nanIsNoData If true, NaN values will be considered as + * no-data as well (default is false) + */ + void SetNaNIsNoData(bool nanIsNoData) + { + this->GetFunctor().m_NaNIsNoData=nanIsNoData; + } protected: ImageToNoDataMaskFilter() @@ -97,23 +136,11 @@ protected: virtual void BeforeThreadedGenerateData() { std::vector<bool> noDataValueAvailable; - bool ret = itk::ExposeMetaData<std::vector<bool> >(this->GetInput()->GetMetaDataDictionary(),MetaDataKey::NoDataValueAvailable,noDataValueAvailable); - - if(!ret) - { - noDataValueAvailable.resize(this->GetInput()->GetNumberOfComponentsPerPixel(),false); - } - - this->GetFunctor().m_Flags = noDataValueAvailable; - std::vector<double> noDataValues; - ret = itk::ExposeMetaData<std::vector<double> >(this->GetInput()->GetMetaDataDictionary(),MetaDataKey::NoDataValue,noDataValues); - - if(!ret) - { - noDataValues.resize(this->GetInput()->GetNumberOfComponentsPerPixel(),0); - } + ReadNoDataFlags(this->GetInput()->GetMetaDataDictionary(),noDataValueAvailable,noDataValues); + + this->GetFunctor().m_Flags = noDataValueAvailable; this->GetFunctor().m_Values = noDataValues; } diff --git a/Modules/Filtering/ImageManipulation/include/otbNRIBandImagesToOneNComplexBandsImage.h b/Modules/Filtering/ImageManipulation/include/otbNRIBandImagesToOneNComplexBandsImage.h new file mode 100644 index 0000000000000000000000000000000000000000..18f1465b0941b453bd5c9330dda92e2873f69d4f --- /dev/null +++ b/Modules/Filtering/ImageManipulation/include/otbNRIBandImagesToOneNComplexBandsImage.h @@ -0,0 +1,92 @@ +/*========================================================================= + + Program: ORFEO Toolbox + Language: C++ + Date: $Date$ + Version: $Revision$ + + + Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. + See OTBCopyright.txt for details. + + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __otbNRIBandImagesToOneNComplexBandsImage_h +#define __otbNRIBandImagesToOneNComplexBandsImage_h + +#include "itkImageToImageFilter.h" +#include "itkImage.h" +#include "itkNumericTraits.h" + +/* + * Inputs : N images made of two real bands + * Output : one single image made of N complex bands + * + * */ + + +namespace otb +{ + + +template <class TInputImage, class TOutputImage> +class ITK_EXPORT NRIBandImagesToOneNComplexBandsImage : public itk::ImageToImageFilter<TInputImage, TOutputImage> +{ +public: + /** Extract input and output image dimension */ + itkStaticConstMacro(InputImageDimension, + unsigned int, + TInputImage::ImageDimension); + itkStaticConstMacro(OutputImageDimension, + unsigned int, + TOutputImage::ImageDimension); + + typedef TInputImage InputImageType; + typedef TOutputImage OutputImageType; + + /** standard class typedefs */ + typedef NRIBandImagesToOneNComplexBandsImage Self; + typedef itk::ImageToImageFilter<InputImageType, OutputImageType> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** Object factory management */ + itkNewMacro(Self); + + /** typemacro */ + itkTypeMacro(NRIBandImagesToOneNComplexBandsImage, ImageToImageFilter); + + typedef typename InputImageType::PixelType InputPixelType; + typedef typename OutputImageType::PixelType OutputPixelType; + typedef typename itk::NumericTraits<InputPixelType>::RealType InputRealType; + typedef typename InputImageType::RegionType InputImageRegionType; + typedef typename OutputImageType::RegionType OutputImageRegionType; + + +protected: + NRIBandImagesToOneNComplexBandsImage(); + virtual ~NRIBandImagesToOneNComplexBandsImage() {} + void PrintSelf(std::ostream& os, itk::Indent indent) const; + + void GenerateOutputInformation(void); + void BeforeThreadedGenerateData(void); + void ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, + itk::ThreadIdType threadId); + +private: + NRIBandImagesToOneNComplexBandsImage(const Self &); //purposely not implemented + void operator =(const Self&); //purposely not implemented + + +}; +} // end namespace otb + +#ifndef OTB_MANUAL_INSTANTIATION +#include "otbNRIBandImagesToOneNComplexBandsImage.txx" +#endif + +#endif diff --git a/Modules/Filtering/ImageManipulation/include/otbNRIBandImagesToOneNComplexBandsImage.txx b/Modules/Filtering/ImageManipulation/include/otbNRIBandImagesToOneNComplexBandsImage.txx new file mode 100644 index 0000000000000000000000000000000000000000..46abbf79efee49136fe17fc0be5d36e9e6ae13cf --- /dev/null +++ b/Modules/Filtering/ImageManipulation/include/otbNRIBandImagesToOneNComplexBandsImage.txx @@ -0,0 +1,139 @@ +/*========================================================================= + + Program: ORFEO Toolbox + Language: C++ + Date: $Date$ + Version: $Revision$ + + + Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. + See OTBCopyright.txt for details. + + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __otbNRIBandImagesToOneNComplexBandsImage_txx +#define __otbNRIBandImagesToOneNComplexBandsImage_txx + +#include "otbNRIBandImagesToOneNComplexBandsImage.h" + +#include "itkImageRegionIterator.h" +#include "itkImageRegionConstIterator.h" +#include "itkProgressReporter.h" +#include "itkVariableLengthVector.h" + + + + +namespace otb +{ + +/** + * + */ +template <class TInputImage, class TOutputImage> +NRIBandImagesToOneNComplexBandsImage<TInputImage, TOutputImage>::NRIBandImagesToOneNComplexBandsImage() +{ + //this->SetNumberOfThreads(1); +} + +/** + * GenerateOutputInformation + */ +template<class TInputImage, class TOutputImage> +void +NRIBandImagesToOneNComplexBandsImage<TInputImage, TOutputImage> +::GenerateOutputInformation(void) +{ + Superclass::GenerateOutputInformation(); + + unsigned int nbInputs = this->GetNumberOfInputs(); + this->GetOutput()->SetNumberOfComponentsPerPixel(nbInputs); + +} + +/** + * BeforeThreadedGenerateData + */ +template <class TInputImage, class TOutputImage> +void +NRIBandImagesToOneNComplexBandsImage<TInputImage, TOutputImage> +::BeforeThreadedGenerateData(void) +{ + unsigned int nbInputs = this->GetNumberOfInputs(); + + for (unsigned int i=0; i<nbInputs; i++) + if (this->GetInput(i)->GetNumberOfComponentsPerPixel() != 2 ) + itkExceptionMacro("Input images must be made of two bands and only two (see input #" << i << ")."); + +} + +/** + * ThreadedGenerateData + */ +template<class TInputImage, class TOutputImage> +void NRIBandImagesToOneNComplexBandsImage<TInputImage, TOutputImage>::ThreadedGenerateData( + const OutputImageRegionType& outputRegionForThread, + itk::ThreadIdType threadId + ) +{ + + // support progress methods/callbacks + itk::ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels()); + + unsigned int nbInputs = this->GetNumberOfInputs(); + + itk::VariableLengthVector< std::complex< typename InputPixelType::ValueType > > vlv(nbInputs); + + std::vector< typename itk::ImageRegionConstIterator<TInputImage> > vInIt; + for (unsigned int i=0; i<nbInputs; i++) + vInIt.push_back( itk::ImageRegionConstIterator<TInputImage>(this->GetInput(i), outputRegionForThread) ); + + + itk::ImageRegionIterator<OutputImageType> outIt; + outIt = itk::ImageRegionIterator<OutputImageType>(this->GetOutput(), outputRegionForThread); + + for (unsigned int i=0; i<nbInputs; i++) + vInIt[i].GoToBegin(); + outIt.GoToBegin(); + + while (!outIt.IsAtEnd()) + { + + + for (unsigned int i=0; i<nbInputs; i++) + { + vlv[i] = std::complex< typename InputPixelType::ValueType >(vInIt[i].Get()[0],vInIt[i].Get()[1]); + //std::cout << "i = " << i << " " << vInIt[i].Get()[0] << " " << vInIt[i].Get()[1] << std::endl; + } + + + outIt.Set(vlv); + + //std::cout << "outIt.Get() = " << outIt.Get() << std::endl; + + for (unsigned int i=0; i<nbInputs; i++) + ++vInIt[i]; + ++outIt; + + progress.CompletedPixel(); + } + +} + +/** + * Standard "PrintSelf" method + */ +template <class TInputImage, class TOutput> +void +NRIBandImagesToOneNComplexBandsImage<TInputImage, TOutput>::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf(os, indent); +} + +} // end namespace otb + +#endif diff --git a/Modules/Filtering/ImageManipulation/include/otbOneRIBandImageToOneComplexBandImage.h b/Modules/Filtering/ImageManipulation/include/otbOneRIBandImageToOneComplexBandImage.h new file mode 100644 index 0000000000000000000000000000000000000000..745199721496ff2f6b9797cfa5e031ab3ec4ebde --- /dev/null +++ b/Modules/Filtering/ImageManipulation/include/otbOneRIBandImageToOneComplexBandImage.h @@ -0,0 +1,91 @@ +/*========================================================================= + + Program: ORFEO Toolbox + Language: C++ + Date: $Date$ + Version: $Revision$ + + + Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. + See OTBCopyright.txt for details. + + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __otbOneRIBandImageToOneComplexBandImage_h +#define __otbOneRIBandImageToOneComplexBandImage_h + +#include "itkImageToImageFilter.h" +#include "itkImage.h" +#include "itkNumericTraits.h" + + +/* + * Inputs : one image made of two real bands + * Output : one image made of one complex band + * + * */ + +namespace otb +{ + + +template <class TInputImage, class TOutputImage> +class ITK_EXPORT OneRIBandImageToOneComplexBandImage : public itk::ImageToImageFilter<TInputImage, TOutputImage> +{ +public: + /** Extract input and output image dimension */ + itkStaticConstMacro(InputImageDimension, + unsigned int, + TInputImage::ImageDimension); + itkStaticConstMacro(OutputImageDimension, + unsigned int, + TOutputImage::ImageDimension); + + typedef TInputImage InputImageType; + typedef TOutputImage OutputImageType; + + /** standard class typedefs */ + typedef OneRIBandImageToOneComplexBandImage Self; + typedef itk::ImageToImageFilter<InputImageType, OutputImageType> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** Object factory management */ + itkNewMacro(Self); + + /** typemacro */ + itkTypeMacro(OneRIBandImageToOneComplexBandImage, ImageToImageFilter); + + typedef typename InputImageType::PixelType InputPixelType; + typedef typename OutputImageType::PixelType OutputPixelType; + typedef typename itk::NumericTraits<InputPixelType>::RealType InputRealType; + typedef typename InputImageType::RegionType InputImageRegionType; + typedef typename OutputImageType::RegionType OutputImageRegionType; + + +protected: + OneRIBandImageToOneComplexBandImage(); + virtual ~OneRIBandImageToOneComplexBandImage() {} + void PrintSelf(std::ostream& os, itk::Indent indent) const; + + void BeforeThreadedGenerateData(void); + void ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, + itk::ThreadIdType threadId); + +private: + OneRIBandImageToOneComplexBandImage(const Self &); //purposely not implemented + void operator =(const Self&); //purposely not implemented + + +}; +} // end namespace otb + +#ifndef OTB_MANUAL_INSTANTIATION +#include "otbOneRIBandImageToOneComplexBandImage.txx" +#endif + +#endif diff --git a/Modules/Filtering/ImageManipulation/include/otbOneRIBandImageToOneComplexBandImage.txx b/Modules/Filtering/ImageManipulation/include/otbOneRIBandImageToOneComplexBandImage.txx new file mode 100644 index 0000000000000000000000000000000000000000..8a7003a8eec8066ed212245a9ff0162310f38499 --- /dev/null +++ b/Modules/Filtering/ImageManipulation/include/otbOneRIBandImageToOneComplexBandImage.txx @@ -0,0 +1,100 @@ +/*========================================================================= + + Program: ORFEO Toolbox + Language: C++ + Date: $Date$ + Version: $Revision$ + + + Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. + See OTBCopyright.txt for details. + + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __otbOneRIBandImageToOneComplexBandImage_txx +#define __otbOneRIBandImageToOneComplexBandImage_txx + +#include "otbOneRIBandImageToOneComplexBandImage.h" + +#include "itkImageRegionIterator.h" +#include "itkImageRegionConstIterator.h" +#include "itkProgressReporter.h" + +namespace otb +{ + +/** + * + */ +template <class TInputImage, class TOutputImage> +OneRIBandImageToOneComplexBandImage<TInputImage, TOutputImage>::OneRIBandImageToOneComplexBandImage() +{ + //this->SetNumberOfThreads(1); +} + +/** + * BeforeThreadedGenerateData + */ +template <class TInputImage, class TOutputImage> +void +OneRIBandImageToOneComplexBandImage<TInputImage, TOutputImage> +::BeforeThreadedGenerateData(void) +{ + if (this->GetInput()->GetNumberOfComponentsPerPixel() != 2 ) + itkExceptionMacro("Input image must be made of two bands and only two."); + +} + +/** + * ThreadedGenerateData + */ +template<class TInputImage, class TOutputImage> +void OneRIBandImageToOneComplexBandImage<TInputImage, TOutputImage>::ThreadedGenerateData( + const OutputImageRegionType& outputRegionForThread, + itk::ThreadIdType threadId + ) +{ + + // support progress methods/callbacks + itk::ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels()); + + typename OutputImageType::Pointer output = this->GetOutput(); + typename InputImageType::ConstPointer input = this->GetInput(); + + itk::ImageRegionIterator<OutputImageType> it; + itk::ImageRegionConstIterator<TInputImage> itIn; + + itIn = itk::ImageRegionConstIterator<TInputImage>(input, outputRegionForThread); + it = itk::ImageRegionIterator<OutputImageType>(output, outputRegionForThread); + + it.GoToBegin(); + itIn.GoToBegin(); + while (!it.IsAtEnd()) + { + + it.Set(static_cast<OutputPixelType>( std::complex< typename InputPixelType::ValueType >(itIn.Get()[0],itIn.Get()[1]) )); + + ++it; + ++itIn; + progress.CompletedPixel(); + } + +} + +/** + * Standard "PrintSelf" method + */ +template <class TInputImage, class TOutput> +void +OneRIBandImageToOneComplexBandImage<TInputImage, TOutput>::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf(os, indent); +} + +} // end namespace otb + +#endif diff --git a/Modules/Filtering/ImageManipulation/include/otbTwoNRIBandsImageToNComplexBandsImage.h b/Modules/Filtering/ImageManipulation/include/otbTwoNRIBandsImageToNComplexBandsImage.h new file mode 100644 index 0000000000000000000000000000000000000000..e60a091176e80ff21ba52c3156aa2ba0413b3a13 --- /dev/null +++ b/Modules/Filtering/ImageManipulation/include/otbTwoNRIBandsImageToNComplexBandsImage.h @@ -0,0 +1,92 @@ +/*========================================================================= + + Program: ORFEO Toolbox + Language: C++ + Date: $Date$ + Version: $Revision$ + + + Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. + See OTBCopyright.txt for details. + + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __otbTwoNRIBandsImageToNComplexBandsImage_h +#define __otbTwoNRIBandsImageToNComplexBandsImage_h + +#include "itkImageToImageFilter.h" +#include "itkImage.h" +#include "itkNumericTraits.h" + +/* + * Inputs : one single image made of 2N real bands + * Output : one single image made of N complex bands + * + * */ + + +namespace otb +{ + + +template <class TInputImage, class TOutputImage> +class ITK_EXPORT TwoNRIBandsImageToNComplexBandsImage : public itk::ImageToImageFilter<TInputImage, TOutputImage> +{ +public: + /** Extract input and output image dimension */ + itkStaticConstMacro(InputImageDimension, + unsigned int, + TInputImage::ImageDimension); + itkStaticConstMacro(OutputImageDimension, + unsigned int, + TOutputImage::ImageDimension); + + typedef TInputImage InputImageType; + typedef TOutputImage OutputImageType; + + /** standard class typedefs */ + typedef TwoNRIBandsImageToNComplexBandsImage Self; + typedef itk::ImageToImageFilter<InputImageType, OutputImageType> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** Object factory management */ + itkNewMacro(Self); + + /** typemacro */ + itkTypeMacro(TwoNRIBandsImageToNComplexBandsImage, ImageToImageFilter); + + typedef typename InputImageType::PixelType InputPixelType; + typedef typename OutputImageType::PixelType OutputPixelType; + typedef typename itk::NumericTraits<InputPixelType>::RealType InputRealType; + typedef typename InputImageType::RegionType InputImageRegionType; + typedef typename OutputImageType::RegionType OutputImageRegionType; + + +protected: + TwoNRIBandsImageToNComplexBandsImage(); + virtual ~TwoNRIBandsImageToNComplexBandsImage() {} + void PrintSelf(std::ostream& os, itk::Indent indent) const; + + void GenerateOutputInformation(void); + void BeforeThreadedGenerateData(void); + void ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, + itk::ThreadIdType threadId); + +private: + TwoNRIBandsImageToNComplexBandsImage(const Self &); //purposely not implemented + void operator =(const Self&); //purposely not implemented + + +}; +} // end namespace otb + +#ifndef OTB_MANUAL_INSTANTIATION +#include "otbTwoNRIBandsImageToNComplexBandsImage.txx" +#endif + +#endif diff --git a/Modules/Filtering/ImageManipulation/include/otbTwoNRIBandsImageToNComplexBandsImage.txx b/Modules/Filtering/ImageManipulation/include/otbTwoNRIBandsImageToNComplexBandsImage.txx new file mode 100644 index 0000000000000000000000000000000000000000..c61f07a9009b4fe2365f926e55c1a9c4111b27fa --- /dev/null +++ b/Modules/Filtering/ImageManipulation/include/otbTwoNRIBandsImageToNComplexBandsImage.txx @@ -0,0 +1,143 @@ +/*========================================================================= + + Program: ORFEO Toolbox + Language: C++ + Date: $Date$ + Version: $Revision$ + + + Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. + See OTBCopyright.txt for details. + + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __otbTwoNRIBandsImageToNComplexBandsImage_txx +#define __otbTwoNRIBandsImageToNComplexBandsImage_txx + +#include "otbTwoNRIBandsImageToNComplexBandsImage.h" + +#include "itkImageRegionIterator.h" +#include "itkImageRegionConstIterator.h" +#include "itkProgressReporter.h" +#include "itkVariableLengthVector.h" + + + + +namespace otb +{ + +/** + * + */ +template <class TInputImage, class TOutputImage> +TwoNRIBandsImageToNComplexBandsImage<TInputImage, TOutputImage>::TwoNRIBandsImageToNComplexBandsImage() +{ + //this->SetNumberOfThreads(1); +} + +/** + * GenerateOutputInformation + */ +template<class TInputImage, class TOutputImage> +void +TwoNRIBandsImageToNComplexBandsImage<TInputImage, TOutputImage> +::GenerateOutputInformation(void) +{ + Superclass::GenerateOutputInformation(); + + unsigned int nbCompo = this->GetInput()->GetNumberOfComponentsPerPixel(); + + if ( (nbCompo % 2) != 0 ) + { + itkExceptionMacro("Number of bands of the input images must be an even number"); + } + else + this->GetOutput()->SetNumberOfComponentsPerPixel(nbCompo/2); + + std::cout << "GenerateOutputInformation : " << this->GetOutput()->GetNumberOfComponentsPerPixel() << std::endl; + +} + +/** + * BeforeThreadedGenerateData + */ +template <class TInputImage, class TOutputImage> +void +TwoNRIBandsImageToNComplexBandsImage<TInputImage, TOutputImage> +::BeforeThreadedGenerateData(void) +{ + unsigned int nbCompo = this->GetInput()->GetNumberOfComponentsPerPixel(); + + if ( (nbCompo % 2) != 0 ) + itkExceptionMacro("Number of bands of the input images must be an even number"); + +} + +/** + * ThreadedGenerateData + */ +template<class TInputImage, class TOutputImage> +void TwoNRIBandsImageToNComplexBandsImage<TInputImage, TOutputImage>::ThreadedGenerateData( + const OutputImageRegionType& outputRegionForThread, + itk::ThreadIdType threadId + ) +{ + + unsigned int nbCompo = this->GetInput()->GetNumberOfComponentsPerPixel(); + + itk::VariableLengthVector< std::complex< typename InputPixelType::ValueType > > vlv(nbCompo/2); + + + // support progress methods/callbacks + itk::ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels()); + + itk::ImageRegionConstIterator<TInputImage> inIt; + inIt = itk::ImageRegionConstIterator<TInputImage>(this->GetInput(), outputRegionForThread); + + itk::ImageRegionIterator<OutputImageType> outIt; + outIt = itk::ImageRegionIterator<OutputImageType>(this->GetOutput(), outputRegionForThread); + + + inIt.GoToBegin(); + outIt.GoToBegin(); + + while (!outIt.IsAtEnd()) + { + + unsigned int k=0; + for (unsigned int i=0; i<nbCompo-1; i=i+2) + { + vlv[k] = std::complex< typename InputPixelType::ValueType >(inIt.Get()[i],inIt.Get()[i+1]); + k++; + } + + + outIt.Set(vlv); + + + ++inIt; + ++outIt; + + progress.CompletedPixel(); + } + +} + +/** + * Standard "PrintSelf" method + */ +template <class TInputImage, class TOutput> +void +TwoNRIBandsImageToNComplexBandsImage<TInputImage, TOutput>::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf(os, indent); +} + +} // end namespace otb + +#endif diff --git a/Modules/Filtering/ImageManipulation/otb-module.cmake b/Modules/Filtering/ImageManipulation/otb-module.cmake index ca49464420ecf8215c1d36eacf45005fdcabc6c7..6a141566a1a1453663ce78f55c6ccf0f1742b5c8 100644 --- a/Modules/Filtering/ImageManipulation/otb-module.cmake +++ b/Modules/Filtering/ImageManipulation/otb-module.cmake @@ -10,6 +10,7 @@ otb_module(OTBImageManipulation OTBCommon OTBITK OTBImageBase + OTBMetadata OTBInterpolation OTBObjectList OTBStreaming diff --git a/Modules/Filtering/ImageManipulation/test/CMakeLists.txt b/Modules/Filtering/ImageManipulation/test/CMakeLists.txt index a167f9c62b9244001dddfbc4c2d215ee88fcc9bb..86e9cd72c67dca156fc4fd293c9b220ff186fc21 100644 --- a/Modules/Filtering/ImageManipulation/test/CMakeLists.txt +++ b/Modules/Filtering/ImageManipulation/test/CMakeLists.txt @@ -70,6 +70,11 @@ otbSpectralAngleDistanceImageFilter.cxx otbFunctionWithNeighborhoodToImageFilterNew.cxx otbEuclideanDistanceMetricWithMissingValue.cxx otbEuclideanDistanceMetricWithMissingValueNew.cxx +otbNRIBandImagesToOneNComplexBandsImage.cxx +otbOneRIBandImageToOneComplexBandImage.cxx +otbTwoNRIBandsImageToNComplexBandsImage.cxx +otbChangeNoDataValueFilter.cxx +otbImageToNoDataMaskFilter.cxx ) add_executable(otbImageManipulationTestDriver ${OTBImageManipulationTests}) @@ -669,3 +674,39 @@ otb_add_test(NAME bfTvEuclideanDistanceMetricWithMissingValue COMMAND otbImageMa otbEuclideanDistanceMetricWithMissingValue) otb_add_test(NAME bfTuEuclideanDistanceMetricWithMissingValueNew COMMAND otbImageManipulationTestDriver otbEuclideanDistanceMetricWithMissingValueNew) + +otb_add_test(NAME bfTvTwoNRIBandsImageToNComplexBandsImage COMMAND otbImageManipulationTestDriver + --compare-image ${EPSILON_7} + ${BASELINE}/bfTvNRIBandImagesToOneNComplexBandsImage.tif + ${TEMP}/bfTvTwoNRIBandsImageToNComplexBandsImage.tif + otbTwoNRIBandsImageToNComplexBandsImage + ${INPUTDATA}/RSAT_imagery_HH_HV_VV.tif + ${TEMP}/bfTvTwoNRIBandsImageToNComplexBandsImage.tif + ) + + +otb_add_test(NAME bfTvNRIBandImagesToOneNComplexBandsImage COMMAND otbImageManipulationTestDriver + --compare-image ${EPSILON_7} + ${BASELINE}/bfTvNRIBandImagesToOneNComplexBandsImage.tif + ${TEMP}/bfTvNRIBandImagesToOneNComplexBandsImage.tif + otbNRIBandImagesToOneNComplexBandsImage + ${INPUTDATA}/RSAT_imagery_HH.tif + ${INPUTDATA}/RSAT_imagery_HV.tif + ${INPUTDATA}/RSAT_imagery_VV.tif + ${TEMP}/bfTvNRIBandImagesToOneNComplexBandsImage.tif + ) + +otb_add_test(NAME bfTvOneRIBandImageToOneComplexBandImage COMMAND otbImageManipulationTestDriver + --compare-image ${EPSILON_3} + ${INPUTDATA}/RSAT_imageryC_HH.tif + ${TEMP}/bfTvOneRIBandImageToOneComplexBandImage.tif + otbOneRIBandImageToOneComplexBandImage + ${INPUTDATA}/RSAT_imagery_HH.tif + ${TEMP}/bfTvOneRIBandImageToOneComplexBandImage.tif + ) + +otb_add_test(NAME filteringImageManipulationChangeNoDataValueFilter COMMAND otbImageManipulationTestDriver + otbChangeNoDataValueFilter) + +otb_add_test(NAME filteringImageManipulationImageToNoDataMaskFilter COMMAND otbImageManipulationTestDriver + otbImageToNoDataMaskFilter) diff --git a/Modules/Filtering/ImageManipulation/test/otbBoxAndWhiskerImageFilterNew.cxx b/Modules/Filtering/ImageManipulation/test/otbBoxAndWhiskerImageFilterNew.cxx index bace7cb8f528de698a4f949720ee62708eb1edf9..827e79d2191b0babc59220b1ddced3af32253ce9 100644 --- a/Modules/Filtering/ImageManipulation/test/otbBoxAndWhiskerImageFilterNew.cxx +++ b/Modules/Filtering/ImageManipulation/test/otbBoxAndWhiskerImageFilterNew.cxx @@ -10,7 +10,7 @@ See OTBCopyright.txt for details. Copyright (c) Institut Telecom; Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Filtering/ImageManipulation/test/otbChangeNoDataValueFilter.cxx b/Modules/Filtering/ImageManipulation/test/otbChangeNoDataValueFilter.cxx new file mode 100644 index 0000000000000000000000000000000000000000..db371582435603f927fdd60004275ee41ed9e28e --- /dev/null +++ b/Modules/Filtering/ImageManipulation/test/otbChangeNoDataValueFilter.cxx @@ -0,0 +1,103 @@ +/*========================================================================= + + Program: ORFEO Toolbox + Language: C++ + Date: $Date$ + Version: $Revision$ + + + Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. + See OTBCopyright.txt for details. + + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#include "otbImage.h" +#include "otbChangeNoDataValueFilter.h" +#include "itkImageRegionIterator.h" + +int otbChangeNoDataValueFilter(int itkNotUsed(argc),char * itkNotUsed(argv) []) +{ + + // Build an image + typedef otb::Image<double> ImageType; + ImageType::Pointer img = ImageType::New(); + + ImageType::SizeType size; + size.Fill(20); + + ImageType::RegionType region; + region.SetSize(size); + + // Fill it with a default value + img->SetRegions(region); + img->Allocate(); + img->FillBuffer(10); + + // Write no-data flags to it + std::vector<bool> flags(1,true); + std::vector<double> values(1,-10.); + otb::WriteNoDataFlags(flags,values,img->GetMetaDataDictionary()); + + // Fill half of the pixels with no-data values + itk::ImageRegionIterator<ImageType> it(img,region); + unsigned int count = 0; + for(it.GoToBegin();!it.IsAtEnd();++it,++count) + { + if (count%2 == 0) + it.Set(-10.); + } + + // Instanciate filter + typedef otb::ChangeNoDataValueFilter<ImageType,ImageType> FilterType; + FilterType::Pointer filter = FilterType::New(); + + std::vector<double> newValues(1,-20.); + + filter->SetInput(img); + filter->SetNewNoDataValues(newValues); + filter->Update(); + + // Check output + it = itk::ImageRegionIterator<ImageType>(filter->GetOutput(),region); + count = 0; + + bool failed = false; + + for(it.GoToBegin();!it.IsAtEnd();++it,++count) + { + if (count%2 == 0 && it.Get()!=-20.) + { + std::cerr<<"Pixel should have new no-data value"<<std::endl; + failed = true; + } + else if(count%2 == 1 && it.Get()!=10.) + { + std::cerr<<"Pixel value should be unchanged"<<std::endl; + failed = true; + } + } + + otb::ReadNoDataFlags(filter->GetOutput()->GetMetaDataDictionary(),flags,values); + + if(flags.empty() || !flags[0]) + { + std::cerr<<"Output no-data flag should be [1] "<<std::endl; + failed = true; + } + + if(values.empty() || values[0]!=-20) + { + std::cerr<<"Output no-data value should be [-20.]"<<std::endl; + failed = true; + } + + if(failed) + return EXIT_FAILURE; + + return EXIT_SUCCESS; +} diff --git a/Modules/Filtering/ImageManipulation/test/otbEuclideanDistanceMetricWithMissingValue.cxx b/Modules/Filtering/ImageManipulation/test/otbEuclideanDistanceMetricWithMissingValue.cxx index 6fbf120df973a0f5fb2cf629bfddfac334d29c5e..735ab4835d4c91c4def31ba82a2ccac86676333c 100644 --- a/Modules/Filtering/ImageManipulation/test/otbEuclideanDistanceMetricWithMissingValue.cxx +++ b/Modules/Filtering/ImageManipulation/test/otbEuclideanDistanceMetricWithMissingValue.cxx @@ -10,7 +10,7 @@ See OTBCopyright.txt for details. Copyright (c) Institut Telecom; Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Filtering/ImageManipulation/test/otbEuclideanDistanceMetricWithMissingValueNew.cxx b/Modules/Filtering/ImageManipulation/test/otbEuclideanDistanceMetricWithMissingValueNew.cxx index ce7620111e718a0d3d1fcc5ea7ecf5593c224180..2b2961961acf065b69dc6b47f8a26e51766f949f 100644 --- a/Modules/Filtering/ImageManipulation/test/otbEuclideanDistanceMetricWithMissingValueNew.cxx +++ b/Modules/Filtering/ImageManipulation/test/otbEuclideanDistanceMetricWithMissingValueNew.cxx @@ -10,7 +10,7 @@ See OTBCopyright.txt for details. Copyright (c) Institut Telecom; Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Filtering/ImageManipulation/test/otbImageManipulationTestDriver.cxx b/Modules/Filtering/ImageManipulation/test/otbImageManipulationTestDriver.cxx index 361248a4fcbb5551d81813d644053459597fe768..f732d0d2a493a927ccfd34f1f5633d85b3508cf3 100644 --- a/Modules/Filtering/ImageManipulation/test/otbImageManipulationTestDriver.cxx +++ b/Modules/Filtering/ImageManipulation/test/otbImageManipulationTestDriver.cxx @@ -76,4 +76,9 @@ void RegisterTests() REGISTER_TEST(otbFunctionWithNeighborhoodToImageFilterNew); REGISTER_TEST(otbEuclideanDistanceMetricWithMissingValue); REGISTER_TEST(otbEuclideanDistanceMetricWithMissingValueNew); + REGISTER_TEST(otbNRIBandImagesToOneNComplexBandsImage); + REGISTER_TEST(otbOneRIBandImageToOneComplexBandImage); + REGISTER_TEST(otbTwoNRIBandsImageToNComplexBandsImage); + REGISTER_TEST(otbChangeNoDataValueFilter); + REGISTER_TEST(otbImageToNoDataMaskFilter); } diff --git a/Modules/Filtering/ImageManipulation/test/otbImageToNoDataMaskFilter.cxx b/Modules/Filtering/ImageManipulation/test/otbImageToNoDataMaskFilter.cxx new file mode 100644 index 0000000000000000000000000000000000000000..d5c2b4283635847be4947e15791e785ec1924d9d --- /dev/null +++ b/Modules/Filtering/ImageManipulation/test/otbImageToNoDataMaskFilter.cxx @@ -0,0 +1,88 @@ +/*========================================================================= + + Program: ORFEO Toolbox + Language: C++ + Date: $Date$ + Version: $Revision$ + + + Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. + See OTBCopyright.txt for details. + + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#include "otbImage.h" +#include "otbImageToNoDataMaskFilter.h" +#include "itkImageRegionIterator.h" + +int otbImageToNoDataMaskFilter(int itkNotUsed(argc),char * itkNotUsed(argv) []) +{ + + // Build an image + typedef otb::Image<double> ImageType; + ImageType::Pointer img = ImageType::New(); + + ImageType::SizeType size; + size.Fill(20); + + ImageType::RegionType region; + region.SetSize(size); + + // Fill it with a default value + img->SetRegions(region); + img->Allocate(); + img->FillBuffer(10); + + // Write no-data flags to it + std::vector<bool> flags(1,true); + std::vector<double> values(1,-10.); + otb::WriteNoDataFlags(flags,values,img->GetMetaDataDictionary()); + + // Fill half of the pixels with no-data values + itk::ImageRegionIterator<ImageType> it(img,region); + unsigned int count = 0; + for(it.GoToBegin();!it.IsAtEnd();++it,++count) + { + if (count%2 == 0) + it.Set(-10.); + } + + // Instanciate filter + typedef otb::ImageToNoDataMaskFilter<ImageType,ImageType> FilterType; + FilterType::Pointer filter = FilterType::New(); + + filter->SetInput(img); + filter->SetInsideValue(255); + filter->SetOutsideValue(0); + filter->Update(); + + // Check output + it = itk::ImageRegionIterator<ImageType>(filter->GetOutput(),region); + count = 0; + + bool failed = false; + + for(it.GoToBegin();!it.IsAtEnd();++it,++count) + { + if (count%2 == 0 && it.Get()!=0) + { + std::cerr<<"Pixel should be masked"<<std::endl; + failed = true; + } + else if(count%2 == 1 && it.Get()!=255) + { + std::cerr<<"Pixel should not be masked"<<std::endl; + failed = true; + } + } + + if(failed) + return EXIT_FAILURE; + + return EXIT_SUCCESS; +} diff --git a/Modules/Filtering/ImageManipulation/test/otbLocalGradientVectorImageFilter.cxx b/Modules/Filtering/ImageManipulation/test/otbLocalGradientVectorImageFilter.cxx index 82de2de31555e30681d946c6177759f632920b0e..9d16be65e81184ea3bdb5c7539b866b9e4529661 100644 --- a/Modules/Filtering/ImageManipulation/test/otbLocalGradientVectorImageFilter.cxx +++ b/Modules/Filtering/ImageManipulation/test/otbLocalGradientVectorImageFilter.cxx @@ -10,7 +10,7 @@ See OTBCopyright.txt for details. Copyright (c) Institut Telecom; Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Filtering/ImageManipulation/test/otbNRIBandImagesToOneNComplexBandsImage.cxx b/Modules/Filtering/ImageManipulation/test/otbNRIBandImagesToOneNComplexBandsImage.cxx new file mode 100644 index 0000000000000000000000000000000000000000..778f42146ea0b8ddd85ef72a63e121cf245d15c1 --- /dev/null +++ b/Modules/Filtering/ImageManipulation/test/otbNRIBandImagesToOneNComplexBandsImage.cxx @@ -0,0 +1,62 @@ +/*========================================================================= + + Program: ORFEO Toolbox + Language: C++ + Date: $Date$ + Version: $Revision$ + + + Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. + See OTBCopyright.txt for details. + + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#include "itkMacro.h" + +#include "otbNRIBandImagesToOneNComplexBandsImage.h" + +#include "otbImage.h" +#include "otbVectorImage.h" +#include "otbImageFileReader.h" +#include "otbImageFileWriter.h" + +int otbNRIBandImagesToOneNComplexBandsImage(int itkNotUsed(argc), char * argv[]) +{ + + typedef double PixelType; + typedef otb::VectorImage<PixelType, 2> InputImageType; + + typedef std::complex<double> OutputPixelType; + typedef otb::VectorImage<OutputPixelType, 2> OutputImageType; + + + typedef otb::NRIBandImagesToOneNComplexBandsImage<InputImageType, OutputImageType> FilterType; + typedef otb::ImageFileReader<InputImageType> ReaderType; + typedef otb::ImageFileWriter<OutputImageType> WriterType; + + ReaderType::Pointer readerA = ReaderType::New(); + ReaderType::Pointer readerB = ReaderType::New(); + ReaderType::Pointer readerC = ReaderType::New(); + FilterType::Pointer filter = FilterType::New(); + WriterType::Pointer writer = WriterType::New(); + + + readerA->SetFileName(argv[1]); + readerB->SetFileName(argv[2]); + readerC->SetFileName(argv[3]); + writer->SetFileName(argv[4]); + + filter->SetInput(0,readerA->GetOutput()); + filter->SetInput(1,readerB->GetOutput()); + filter->SetInput(2,readerC->GetOutput()); + writer->SetInput(filter->GetOutput()); + writer->Update(); + + + + return EXIT_SUCCESS; +} diff --git a/Modules/Filtering/ImageManipulation/test/otbOneRIBandImageToOneComplexBandImage.cxx b/Modules/Filtering/ImageManipulation/test/otbOneRIBandImageToOneComplexBandImage.cxx new file mode 100644 index 0000000000000000000000000000000000000000..bbc4682269f0f3b7ea6f3bc3243810dd80d3099f --- /dev/null +++ b/Modules/Filtering/ImageManipulation/test/otbOneRIBandImageToOneComplexBandImage.cxx @@ -0,0 +1,56 @@ +/*========================================================================= + + Program: ORFEO Toolbox + Language: C++ + Date: $Date$ + Version: $Revision$ + + + Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. + See OTBCopyright.txt for details. + + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#include "itkMacro.h" + +#include "otbOneRIBandImageToOneComplexBandImage.h" + +#include "otbImage.h" +#include "otbVectorImage.h" +#include "otbImageFileReader.h" +#include "otbImageFileWriter.h" + +int otbOneRIBandImageToOneComplexBandImage(int itkNotUsed(argc), char * argv[]) +{ + + typedef double PixelType; + typedef otb::VectorImage<PixelType, 2> InputImageType; + + typedef std::complex<double> OutputPixelType; + typedef otb::Image<OutputPixelType, 2> OutputImageType; + + + typedef otb::OneRIBandImageToOneComplexBandImage<InputImageType, OutputImageType> FilterType; + typedef otb::ImageFileReader<InputImageType> ReaderType; + typedef otb::ImageFileWriter<OutputImageType> WriterType; + + ReaderType::Pointer reader = ReaderType::New(); + FilterType::Pointer filter = FilterType::New(); + WriterType::Pointer writer = WriterType::New(); + + + reader->SetFileName(argv[1]); + writer->SetFileName(argv[2]); + + filter->SetInput(reader->GetOutput()); + writer->SetInput(filter->GetOutput()); + writer->Update(); + + + + return EXIT_SUCCESS; +} diff --git a/Modules/Filtering/ImageManipulation/test/otbTwoNRIBandsImageToNComplexBandsImage.cxx b/Modules/Filtering/ImageManipulation/test/otbTwoNRIBandsImageToNComplexBandsImage.cxx new file mode 100644 index 0000000000000000000000000000000000000000..b4fed1963178ae79497fcdc18161b99261205dbc --- /dev/null +++ b/Modules/Filtering/ImageManipulation/test/otbTwoNRIBandsImageToNComplexBandsImage.cxx @@ -0,0 +1,56 @@ +/*========================================================================= + + Program: ORFEO Toolbox + Language: C++ + Date: $Date$ + Version: $Revision$ + + + Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. + See OTBCopyright.txt for details. + + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#include "itkMacro.h" + +#include "otbTwoNRIBandsImageToNComplexBandsImage.h" + +#include "otbImage.h" +#include "otbVectorImage.h" +#include "otbImageFileReader.h" +#include "otbImageFileWriter.h" + +int otbTwoNRIBandsImageToNComplexBandsImage(int itkNotUsed(argc), char * argv[]) +{ + + typedef double PixelType; + typedef otb::VectorImage<PixelType, 2> InputImageType; + + typedef std::complex<double> OutputPixelType; + typedef otb::VectorImage<OutputPixelType, 2> OutputImageType; + + + typedef otb::TwoNRIBandsImageToNComplexBandsImage<InputImageType, OutputImageType> FilterType; + typedef otb::ImageFileReader<InputImageType> ReaderType; + typedef otb::ImageFileWriter<OutputImageType> WriterType; + + ReaderType::Pointer reader = ReaderType::New(); + FilterType::Pointer filter = FilterType::New(); + WriterType::Pointer writer = WriterType::New(); + + + reader->SetFileName(argv[1]); + writer->SetFileName(argv[2]); + + filter->SetInput(0,reader->GetOutput()); + writer->SetInput(filter->GetOutput()); + writer->Update(); + + + + return EXIT_SUCCESS; +} diff --git a/Modules/Filtering/Polarimetry/include/otbReciprocalHAlphaImageFilter.h b/Modules/Filtering/Polarimetry/include/otbReciprocalHAlphaImageFilter.h index 00ec3ff8106defb30c088b4e38e6000a9c0caf61..0967d1747196fa2632a926d3eedfe26692a92927 100644 --- a/Modules/Filtering/Polarimetry/include/otbReciprocalHAlphaImageFilter.h +++ b/Modules/Filtering/Polarimetry/include/otbReciprocalHAlphaImageFilter.h @@ -136,7 +136,8 @@ public: if (p[k]<m_Epsilon) //n=log(n)-->0 when n-->0 plog[k]=0.0; else - plog[k]=-p[k]*log(p[k])/log(3); + plog[k]=-p[k]*log(p[k])/log(3.0); + } entropy = 0.0; diff --git a/Modules/Filtering/Polarimetry/include/otbSinclairToCircularCovarianceMatrixFunctor.h b/Modules/Filtering/Polarimetry/include/otbSinclairToCircularCovarianceMatrixFunctor.h index c3d4f81404863d17f6b9bcd8ae54354d2b35d4eb..08e10da87a53b51cbd79ae565c598240911c4965 100644 --- a/Modules/Filtering/Polarimetry/include/otbSinclairToCircularCovarianceMatrixFunctor.h +++ b/Modules/Filtering/Polarimetry/include/otbSinclairToCircularCovarianceMatrixFunctor.h @@ -42,9 +42,9 @@ namespace Functor * - channel #9 : \f$ S_{rr}.S_{rr}^{*} \f$ * * With: - * - \f$ S_{ll} = 0.5 * (-S_{hh}-i*S_{hv}-i*S_{vh}+S_{vv}) \f$ - * - \f$ S_{lr} = 0.5 * (-S_{hh}+i*S_{hv}-i*S_{vh}+S_{vv}) \f$ - * - \f$ S_{rl} = 0.5 * (-S_{hh}-i*S_{hv}+i*S_{vh}-S_{vv}) \f$ + * - \f$ S_{ll} = 0.5 * (S_{hh}+i*S_{hv}+i*S_{vh}-S_{vv}) \f$ + * - \f$ S_{lr} = 0.5 * (i*S_{hh}+S_{hv}-S_{vh}+i*S_{vv}) \f$ + * - \f$ S_{rl} = 0.5 * (i*S_{hh}-S_{hv}+S_{vh}+i*S_{vv}) \f$ * - \f$ S_{rr} = 0.5 * (-S_{hh}+i*S_{hv}+i*S_{vh}+S_{vv}) \f$ * * Extract from Antennas for radar and communications Harold Mott p 317. @@ -89,12 +89,14 @@ public: result.SetSize(m_NumberOfComponentsPerPixel); const ComplexType jS_hv = S_hv * ComplexType(0., 1.); const ComplexType jS_vh = S_vh * ComplexType(0., 1.); - + const ComplexType jS_hh = S_hh * ComplexType(0., 1.); + const ComplexType jS_vv = S_vv * ComplexType(0., 1.); + const ComplexType coef(0.5); - const ComplexType Sll = coef*( -S_hh-jS_hv-jS_vh+S_vv ); - const ComplexType Slr = coef*( -S_hh+jS_hv-jS_vh-S_vv ); - const ComplexType Srl = coef*( -S_hh-jS_hv+jS_vh-S_vv ); + const ComplexType Sll = coef*( S_hh+jS_hv+jS_vh-S_vv ); + const ComplexType Slr = coef*( jS_hh+S_hv-S_vh+jS_vv ); + const ComplexType Srl = coef*( jS_hh-S_hv+S_vh+jS_vv ); const ComplexType Srr = coef*( -S_hh+jS_hv+jS_vh+S_vv ); //const ComplexType conjSll = vcl_conj(Sll); diff --git a/Modules/Filtering/Polarimetry/test/otbSinclairToCircularCovarianceMatrixFunctor.cxx b/Modules/Filtering/Polarimetry/test/otbSinclairToCircularCovarianceMatrixFunctor.cxx index c883bdef933ac1ec90774d660e887c80d54bf66a..030cc9b5d4fdcecd6a6bacd7530423a2cde0baed 100644 --- a/Modules/Filtering/Polarimetry/test/otbSinclairToCircularCovarianceMatrixFunctor.cxx +++ b/Modules/Filtering/Polarimetry/test/otbSinclairToCircularCovarianceMatrixFunctor.cxx @@ -31,14 +31,14 @@ int otbSinclairToCircularCovarianceMatrixFunctor(int itkNotUsed(argc), char * it OutputType outputFunct; result[0] = ComplexType( 32., 0. ); - result[1] = ComplexType( 0., 24. ); - result[2] = ComplexType( 0., 16.); - result[3] = ComplexType( -8., 0 ); + result[1] = ComplexType( 24., 0. ); + result[2] = ComplexType( 16., 0.); + result[3] = ComplexType( 8., 0 ); result[4] = ComplexType( 18., 0. ); result[5] = ComplexType( 12. , 0. ); - result[6] = ComplexType( 0. , 6. ); + result[6] = ComplexType( 6. , 0. ); result[7] = ComplexType( 8, 0. ); - result[8] = ComplexType( 0, 4. ); + result[8] = ComplexType( 4., 0. ); result[9] = ComplexType( 2, 0. ); outputFunct = funct.operator ()( ComplexType(1., 4.), ComplexType(2., 3.), ComplexType(3., 2.), ComplexType(4., 1.) ); diff --git a/Modules/Filtering/Projection/include/otbGenericRSResampleImageFilter.txx b/Modules/Filtering/Projection/include/otbGenericRSResampleImageFilter.txx index a18dabf09aa8fb846a47750566db9bc813af35b7..590688a4212bf79c15184c2c87b6b861fb5dce76 100644 --- a/Modules/Filtering/Projection/include/otbGenericRSResampleImageFilter.txx +++ b/Modules/Filtering/Projection/include/otbGenericRSResampleImageFilter.txx @@ -101,6 +101,15 @@ GenericRSResampleImageFilter<TInputImage, TOutputImage> if (m_EstimateOutputRpcModel) this->EstimateOutputRpcModel(); + // Estimate the input rpc model if it is needed + if (m_EstimateInputRpcModel && !m_RpcEstimationUpdated) + { + this->EstimateInputRpcModel(); + } + + // Instanciate the RS transform + this->UpdateTransform(); + m_Resampler->SetInput(this->GetInput()); m_Resampler->SetTransform(m_Transform); m_Resampler->SetDisplacementFieldSpacing(this->GetDisplacementFieldSpacing()); @@ -177,15 +186,6 @@ GenericRSResampleImageFilter<TInputImage, TOutputImage> { if (this->m_Updating) return; - // Estimate the input rpc model if it is needed - if (m_EstimateInputRpcModel && !m_RpcEstimationUpdated) - { - this->EstimateInputRpcModel(); - } - - // Instanciate the RS transform - this->UpdateTransform(); - // Retrieve output requested region m_Resampler->GetOutput()->SetRequestedRegion(output); m_Resampler->GetOutput()->PropagateRequestedRegion(); diff --git a/Modules/Filtering/Projection/include/otbOrthoRectificationFilter.txx b/Modules/Filtering/Projection/include/otbOrthoRectificationFilter.txx index d3e16f52d87338e2542f1223ae94434761ae8830..51bdfecb491266a1054ad32a3c8098aceab67cbd 100644 --- a/Modules/Filtering/Projection/include/otbOrthoRectificationFilter.txx +++ b/Modules/Filtering/Projection/include/otbOrthoRectificationFilter.txx @@ -67,6 +67,7 @@ OrthoRectificationFilter<TInputImage, TOutputImage, TMapProjection, TInterpolato // Fill the GenericRSTransform with those information this->SetOutputProjectionRef(projectionRef); + this->UpdateTransform(); } } diff --git a/Modules/Filtering/Projection/include/otbROIdataConversion.h b/Modules/Filtering/Projection/include/otbROIdataConversion.h index 247f61cad56187e7c870c1ec009ca19abc0bcae0..541eddb93cfd3faa230885c507e29ad4ef1f490c 100644 --- a/Modules/Filtering/Projection/include/otbROIdataConversion.h +++ b/Modules/Filtering/Projection/include/otbROIdataConversion.h @@ -9,8 +9,6 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) GET / ENST Bretagne. All rights reserved. - See GETCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Filtering/Projection/include/otbROIdataConversion.txx b/Modules/Filtering/Projection/include/otbROIdataConversion.txx index 142bb6fe1b5af7e244c917f896fa4dcc7fe4ef04..b8513a07a84af131eefb692c87db89760c83542f 100644 --- a/Modules/Filtering/Projection/include/otbROIdataConversion.txx +++ b/Modules/Filtering/Projection/include/otbROIdataConversion.txx @@ -9,8 +9,6 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) GET / ENST Bretagne. All rights reserved. - See GETCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Filtering/Wavelet/include/otbSubsampleImageFilter.h b/Modules/Filtering/Wavelet/include/otbSubsampleImageFilter.h index 0e900decd7f2a71623a1c0842ad4e34b8535c397..92ac96137241a4c65253bfd74c2d6ee6e916b92c 100644 --- a/Modules/Filtering/Wavelet/include/otbSubsampleImageFilter.h +++ b/Modules/Filtering/Wavelet/include/otbSubsampleImageFilter.h @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Filtering/Wavelet/include/otbSubsampleImageFilter.txx b/Modules/Filtering/Wavelet/include/otbSubsampleImageFilter.txx index 2474aca2bcb8e27a38ff4e5d7d1a2dd18b7c8705..0375f3956aad96d52f20f24967927a424ea2ab8f 100644 --- a/Modules/Filtering/Wavelet/include/otbSubsampleImageFilter.txx +++ b/Modules/Filtering/Wavelet/include/otbSubsampleImageFilter.txx @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Filtering/Wavelet/include/otbWaveletFilterBank.h b/Modules/Filtering/Wavelet/include/otbWaveletFilterBank.h index 68b477bffde7552699753dba51bceb4bec214a4b..c219f717e9ae02e2ffbd2ec831b2c8c15c86e1bf 100644 --- a/Modules/Filtering/Wavelet/include/otbWaveletFilterBank.h +++ b/Modules/Filtering/Wavelet/include/otbWaveletFilterBank.h @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Filtering/Wavelet/include/otbWaveletFilterBank.txx b/Modules/Filtering/Wavelet/include/otbWaveletFilterBank.txx index 35ff142ec52b1761702a67f563999ffceb7ef077..21ba8cdf9f7ce65529c33adbe3b6c94a1ad29e85 100644 --- a/Modules/Filtering/Wavelet/include/otbWaveletFilterBank.txx +++ b/Modules/Filtering/Wavelet/include/otbWaveletFilterBank.txx @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Filtering/Wavelet/include/otbWaveletGenerator.h b/Modules/Filtering/Wavelet/include/otbWaveletGenerator.h index ae8a87bb2d336d4433c8b6241f4372390d7dddef..68be4ad16b6f185059b8b7ba14a3f061f9940de6 100644 --- a/Modules/Filtering/Wavelet/include/otbWaveletGenerator.h +++ b/Modules/Filtering/Wavelet/include/otbWaveletGenerator.h @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Filtering/Wavelet/include/otbWaveletHighPassOperator.h b/Modules/Filtering/Wavelet/include/otbWaveletHighPassOperator.h index 1f51a4d287c0f05f0d4f4685b4a08a05d3207a5b..f680eea930fbc073ae371036d74f83c6c21bb9d4 100644 --- a/Modules/Filtering/Wavelet/include/otbWaveletHighPassOperator.h +++ b/Modules/Filtering/Wavelet/include/otbWaveletHighPassOperator.h @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Filtering/Wavelet/include/otbWaveletLowPassOperator.h b/Modules/Filtering/Wavelet/include/otbWaveletLowPassOperator.h index 0742709e72d1b6d1dc942b7deb93bd8cc08533a5..2b612a2099f4c459f089be132c245c2a53466fc8 100644 --- a/Modules/Filtering/Wavelet/include/otbWaveletLowPassOperator.h +++ b/Modules/Filtering/Wavelet/include/otbWaveletLowPassOperator.h @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Filtering/Wavelet/include/otbWaveletOperator.h b/Modules/Filtering/Wavelet/include/otbWaveletOperator.h index c512f906827f3a6cd10d744d7e4019dea083b5a9..a6d9394d3ebfedf3d520f6e904f9510ca392693e 100644 --- a/Modules/Filtering/Wavelet/include/otbWaveletOperator.h +++ b/Modules/Filtering/Wavelet/include/otbWaveletOperator.h @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Filtering/Wavelet/include/otbWaveletOperatorBase.h b/Modules/Filtering/Wavelet/include/otbWaveletOperatorBase.h index c3598d325966ab10cb6887c1075f4472f41c93c3..d17c1dfd9be33fb83d151e7d70b87793ef8b5429 100644 --- a/Modules/Filtering/Wavelet/include/otbWaveletOperatorBase.h +++ b/Modules/Filtering/Wavelet/include/otbWaveletOperatorBase.h @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Filtering/Wavelet/include/otbWaveletOperatorBase.txx b/Modules/Filtering/Wavelet/include/otbWaveletOperatorBase.txx index 2270f2300c3d2eccd98573aa9abae05813798718..8b76a313d3f1b23fbf5970ade6a13c863e91c6ac 100644 --- a/Modules/Filtering/Wavelet/include/otbWaveletOperatorBase.txx +++ b/Modules/Filtering/Wavelet/include/otbWaveletOperatorBase.txx @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Filtering/Wavelet/include/otbWaveletPacketDecompositionCosts.h b/Modules/Filtering/Wavelet/include/otbWaveletPacketDecompositionCosts.h index c07570b9d45e5e3a3193b2d578aabae0e6ecd24e..e87374c43d274f0c3f5ce6777bfb48ceaa472e5f 100644 --- a/Modules/Filtering/Wavelet/include/otbWaveletPacketDecompositionCosts.h +++ b/Modules/Filtering/Wavelet/include/otbWaveletPacketDecompositionCosts.h @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Filtering/Wavelet/include/otbWaveletPacketTransform.h b/Modules/Filtering/Wavelet/include/otbWaveletPacketTransform.h index 76449b94c45ffa32173819f7611ad39e54b471e4..24e4028a5760b819520be49b8e857fb5749f83dd 100644 --- a/Modules/Filtering/Wavelet/include/otbWaveletPacketTransform.h +++ b/Modules/Filtering/Wavelet/include/otbWaveletPacketTransform.h @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Filtering/Wavelet/include/otbWaveletPacketTransform.txx b/Modules/Filtering/Wavelet/include/otbWaveletPacketTransform.txx index dea2820740652abfe27680390e7d041486844882..2d0e628e7261313511f99fee398179cb28bf8844 100644 --- a/Modules/Filtering/Wavelet/include/otbWaveletPacketTransform.txx +++ b/Modules/Filtering/Wavelet/include/otbWaveletPacketTransform.txx @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Filtering/Wavelet/include/otbWaveletTransform.h b/Modules/Filtering/Wavelet/include/otbWaveletTransform.h index 1c16dffe0b8efea7dc1926b7c4c85265b3e59e4c..c80ea8050986d413fceadc1f1e8091ef1480dd1b 100644 --- a/Modules/Filtering/Wavelet/include/otbWaveletTransform.h +++ b/Modules/Filtering/Wavelet/include/otbWaveletTransform.h @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Filtering/Wavelet/include/otbWaveletTransform.txx b/Modules/Filtering/Wavelet/include/otbWaveletTransform.txx index fcccb78421cad5365c80cdd76590c19cd82da81f..93eac94b95f2dfeeba0b94a6c25f0c04af34f475 100644 --- a/Modules/Filtering/Wavelet/include/otbWaveletTransform.txx +++ b/Modules/Filtering/Wavelet/include/otbWaveletTransform.txx @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Filtering/Wavelet/src/otbWaveletGenerator.cxx b/Modules/Filtering/Wavelet/src/otbWaveletGenerator.cxx index 04b4ee18244c3cfcff43bab20434d8319d4df319..9de9df6d6520844cf78db9a6a217897dcf8382e6 100644 --- a/Modules/Filtering/Wavelet/src/otbWaveletGenerator.cxx +++ b/Modules/Filtering/Wavelet/src/otbWaveletGenerator.cxx @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Filtering/Wavelet/test/otbSubsampleImageFilter.cxx b/Modules/Filtering/Wavelet/test/otbSubsampleImageFilter.cxx index a5f08b759b0697062a6d9265804d5fb4712ebc14..10721eedae3fe555851e5252746d3962a13306d6 100644 --- a/Modules/Filtering/Wavelet/test/otbSubsampleImageFilter.cxx +++ b/Modules/Filtering/Wavelet/test/otbSubsampleImageFilter.cxx @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Filtering/Wavelet/test/otbSubsampleImageFilterNew.cxx b/Modules/Filtering/Wavelet/test/otbSubsampleImageFilterNew.cxx index e3ccf387069f3c759f43dcf4d93be5d8e2cf7cae..538cdfed2470e975e65a0cfd8cb2e75eacead012 100644 --- a/Modules/Filtering/Wavelet/test/otbSubsampleImageFilterNew.cxx +++ b/Modules/Filtering/Wavelet/test/otbSubsampleImageFilterNew.cxx @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Filtering/Wavelet/test/otbWaveletFilterBank.cxx b/Modules/Filtering/Wavelet/test/otbWaveletFilterBank.cxx index b90dfbd642ad090ea0303db82811e3efae51d7fd..3878fb7620a0ad9441c922e0a5cded3c925ed6e2 100644 --- a/Modules/Filtering/Wavelet/test/otbWaveletFilterBank.cxx +++ b/Modules/Filtering/Wavelet/test/otbWaveletFilterBank.cxx @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Filtering/Wavelet/test/otbWaveletInverseTransformNew.cxx b/Modules/Filtering/Wavelet/test/otbWaveletInverseTransformNew.cxx index 34ecd1545e8550292b6df8fbc906a04604f996aa..ff27846f6da7852531236e5e37e654be4f0c716a 100644 --- a/Modules/Filtering/Wavelet/test/otbWaveletInverseTransformNew.cxx +++ b/Modules/Filtering/Wavelet/test/otbWaveletInverseTransformNew.cxx @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Filtering/Wavelet/test/otbWaveletOperator.cxx b/Modules/Filtering/Wavelet/test/otbWaveletOperator.cxx index 9b2baa47b05ec857e51de6705d641347a67417d9..a1c215042c39872b115fd6d4257ce1b6d73eedd9 100644 --- a/Modules/Filtering/Wavelet/test/otbWaveletOperator.cxx +++ b/Modules/Filtering/Wavelet/test/otbWaveletOperator.cxx @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Filtering/Wavelet/test/otbWaveletOperatorNew.cxx b/Modules/Filtering/Wavelet/test/otbWaveletOperatorNew.cxx index 866104bb4214c436a392595522ab908794f58c91..712a7a868fcdfc1f6447ab75581dc2b03cfc2002 100644 --- a/Modules/Filtering/Wavelet/test/otbWaveletOperatorNew.cxx +++ b/Modules/Filtering/Wavelet/test/otbWaveletOperatorNew.cxx @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Filtering/Wavelet/test/otbWaveletPacketInverseTransformNew.cxx b/Modules/Filtering/Wavelet/test/otbWaveletPacketInverseTransformNew.cxx index 8735db6bd7c2db507785c62c2ab1e439eb8c8867..b89cc7d40089dff2bcdc2ae8938646b891c56207 100644 --- a/Modules/Filtering/Wavelet/test/otbWaveletPacketInverseTransformNew.cxx +++ b/Modules/Filtering/Wavelet/test/otbWaveletPacketInverseTransformNew.cxx @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Filtering/Wavelet/test/otbWaveletPacketTransform.cxx b/Modules/Filtering/Wavelet/test/otbWaveletPacketTransform.cxx index 5726576a4f779aee308b800f1e3b8b8c774ac825..b7e6d00990606b2b3f9f7abe5d269b3254f8e64a 100644 --- a/Modules/Filtering/Wavelet/test/otbWaveletPacketTransform.cxx +++ b/Modules/Filtering/Wavelet/test/otbWaveletPacketTransform.cxx @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Filtering/Wavelet/test/otbWaveletTransform.cxx b/Modules/Filtering/Wavelet/test/otbWaveletTransform.cxx index 053f5fe52fb11401ee3bca5453484489013b7547..4774374c69fa364f6dbf96b6f76ba93b272f16cf 100644 --- a/Modules/Filtering/Wavelet/test/otbWaveletTransform.cxx +++ b/Modules/Filtering/Wavelet/test/otbWaveletTransform.cxx @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/IO/ImageIO/include/otbImageSeriesFileReader.h b/Modules/IO/ImageIO/include/otbImageSeriesFileReader.h index ada4080d51ca7e55d129ef5be21a42d1a0b0fb8f..75089a2e311d97b571d3344acb7c5b69b8d8ba1e 100644 --- a/Modules/IO/ImageIO/include/otbImageSeriesFileReader.h +++ b/Modules/IO/ImageIO/include/otbImageSeriesFileReader.h @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/IO/ImageIO/include/otbImageSeriesFileReader.txx b/Modules/IO/ImageIO/include/otbImageSeriesFileReader.txx index eaed4aa022564773cef8f2a29129985c93d4cd98..51ad2f02f9ced9ef74f23316fdf339806cd89b78 100644 --- a/Modules/IO/ImageIO/include/otbImageSeriesFileReader.txx +++ b/Modules/IO/ImageIO/include/otbImageSeriesFileReader.txx @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/IO/ImageIO/include/otbImageSeriesFileReaderBase.h b/Modules/IO/ImageIO/include/otbImageSeriesFileReaderBase.h index cb1aa3ae4afe7819a318f306b325df768490cb68..06ce1a68187096b4dd5a12c65551dc6f8f30f70b 100644 --- a/Modules/IO/ImageIO/include/otbImageSeriesFileReaderBase.h +++ b/Modules/IO/ImageIO/include/otbImageSeriesFileReaderBase.h @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/IO/ImageIO/include/otbImageSeriesFileReaderBase.txx b/Modules/IO/ImageIO/include/otbImageSeriesFileReaderBase.txx index 5d355b4d2940c0f9cb10b17cfe3bed46305f78f5..60ddc4d1c5d7986289de9e861a75fd0eab185093 100644 --- a/Modules/IO/ImageIO/include/otbImageSeriesFileReaderBase.txx +++ b/Modules/IO/ImageIO/include/otbImageSeriesFileReaderBase.txx @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/IO/ImageIO/test/otbImageSeriesFileReader.cxx b/Modules/IO/ImageIO/test/otbImageSeriesFileReader.cxx index 47bf8c64c53d0b81819e4c567cd317559dc7f799..aea4736ae9de996593ef4ce78c8c987e84cce103 100644 --- a/Modules/IO/ImageIO/test/otbImageSeriesFileReader.cxx +++ b/Modules/IO/ImageIO/test/otbImageSeriesFileReader.cxx @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. + Copyright (c) Institut Mines-Telecom. All rights reserved. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Learning/LearningBase/include/otbGaussianModelComponent.h b/Modules/Learning/LearningBase/include/otbGaussianModelComponent.h index 6937b06d517f6d1e3642c6d6512ba33207442b85..ecc4cb26515708e2408e3d0948bf60c511f56d4b 100644 --- a/Modules/Learning/LearningBase/include/otbGaussianModelComponent.h +++ b/Modules/Learning/LearningBase/include/otbGaussianModelComponent.h @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Some parts of this code are covered by the GET copyright. - See GETCopyright.txt for details. + Some parts of this code are covered by the IMT copyright. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Learning/LearningBase/include/otbGaussianModelComponent.txx b/Modules/Learning/LearningBase/include/otbGaussianModelComponent.txx index a1edbe7085a8429dcb27968a199a5aeafed54328..d420d84070ee859167619653435c97ff3c093c9c 100644 --- a/Modules/Learning/LearningBase/include/otbGaussianModelComponent.txx +++ b/Modules/Learning/LearningBase/include/otbGaussianModelComponent.txx @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Some parts of this code are covered by the GET copyright. - See GETCopyright.txt for details. + Some parts of this code are covered by the IMT copyright. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Learning/LearningBase/include/otbSEMClassifier.h b/Modules/Learning/LearningBase/include/otbSEMClassifier.h index 6f7e5e76946750ca587dd819963166a0f51e26b6..e23db49440f1168fa424d2a7e8665b09c770aec7 100644 --- a/Modules/Learning/LearningBase/include/otbSEMClassifier.h +++ b/Modules/Learning/LearningBase/include/otbSEMClassifier.h @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Some parts of this code are covered by the GET copyright. - See GETCopyright.txt for details. + Some parts of this code are covered by the IMT copyright. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Learning/LearningBase/include/otbSEMClassifier.txx b/Modules/Learning/LearningBase/include/otbSEMClassifier.txx index b4ef42b3e8423882433e97aa0c13ad60311989c5..9222684ae6399ff6e5c4c3440b045934b800dc0e 100644 --- a/Modules/Learning/LearningBase/include/otbSEMClassifier.txx +++ b/Modules/Learning/LearningBase/include/otbSEMClassifier.txx @@ -9,8 +9,8 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Some parts of this code are covered by the GET copyright. - See GETCopyright.txt for details. + Some parts of this code are covered by the IMT copyright. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Learning/SOM/include/otbCzihoSOMLearningBehaviorFunctor.h b/Modules/Learning/SOM/include/otbCzihoSOMLearningBehaviorFunctor.h index 7a68fa6476b91bcec72b558fbacd5ce993e590ea..19fdf31beb0bc714980a6edc086894887b3afd6c 100644 --- a/Modules/Learning/SOM/include/otbCzihoSOMLearningBehaviorFunctor.h +++ b/Modules/Learning/SOM/include/otbCzihoSOMLearningBehaviorFunctor.h @@ -10,7 +10,7 @@ See OTBCopyright.txt for details. Copyright (c) Institut Telecom; Telecom bretagne. All rights reserved. - See ITCopyright.txt for details. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Learning/SOM/include/otbCzihoSOMNeighborhoodBehaviorFunctor.h b/Modules/Learning/SOM/include/otbCzihoSOMNeighborhoodBehaviorFunctor.h index a81df3e33962587b325e28fcc1ae3b5b0de7b3e4..a364d57dc905d8a07259df1891503966f5d0760f 100644 --- a/Modules/Learning/SOM/include/otbCzihoSOMNeighborhoodBehaviorFunctor.h +++ b/Modules/Learning/SOM/include/otbCzihoSOMNeighborhoodBehaviorFunctor.h @@ -10,7 +10,7 @@ See OTBCopyright.txt for details. Copyright (c) Institut Telecom; Telecom bretagne. All rights reserved. - See ITCopyright.txt for details. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Learning/SOM/include/otbPeriodicSOM.h b/Modules/Learning/SOM/include/otbPeriodicSOM.h index 7bc01e4abba9524fabbddc3b6ab46993a3e004d2..835aeff7523fa33e2d75655f72be337d9cfe3143 100644 --- a/Modules/Learning/SOM/include/otbPeriodicSOM.h +++ b/Modules/Learning/SOM/include/otbPeriodicSOM.h @@ -10,7 +10,7 @@ See OTBCopyright.txt for details. Copyright (c) Institut Telecom; Telecom bretagne. All rights reserved. - See ITCopyright.txt for details. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Learning/SOM/include/otbPeriodicSOM.txx b/Modules/Learning/SOM/include/otbPeriodicSOM.txx index 1618b77c550d3837d9b93a97cf0338d5f6be0bb0..352817bbd576b63b19a942cfb1b9d128137a7305 100644 --- a/Modules/Learning/SOM/include/otbPeriodicSOM.txx +++ b/Modules/Learning/SOM/include/otbPeriodicSOM.txx @@ -10,7 +10,7 @@ See OTBCopyright.txt for details. Copyright (c) Institut Telecom; Telecom bretagne. All rights reserved. - See ITCopyright.txt for details. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Learning/SOM/include/otbSOM.h b/Modules/Learning/SOM/include/otbSOM.h index 7205dc75b77a478467cdb83f378fb9a986c10a2d..ff020cd4465b7f993dab49c1dd103fb5f95944de 100644 --- a/Modules/Learning/SOM/include/otbSOM.h +++ b/Modules/Learning/SOM/include/otbSOM.h @@ -10,7 +10,7 @@ See OTBCopyright.txt for details. Copyright (c) Institut Telecom; Telecom bretagne. All rights reserved. - See ITCopyright.txt for details. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Learning/SOM/include/otbSOM.txx b/Modules/Learning/SOM/include/otbSOM.txx index f30b97c1d0d66619149bb13d9ae9b7c82333b5ac..cdc5066cfd1197122946331dd6bc69ee369c0a45 100644 --- a/Modules/Learning/SOM/include/otbSOM.txx +++ b/Modules/Learning/SOM/include/otbSOM.txx @@ -10,7 +10,7 @@ See OTBCopyright.txt for details. Copyright (c) Institut Telecom; Telecom bretagne. All rights reserved. - See ITCopyright.txt for details. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even diff --git a/Modules/Learning/SOM/include/otbSOMLearningBehaviorFunctor.h b/Modules/Learning/SOM/include/otbSOMLearningBehaviorFunctor.h index 3db9aec74fbd8b55739c9a0f0af6891cf602bef6..4e38167100cdf4fca1e5a3ed7c441d99186a2698 100644 --- a/Modules/Learning/SOM/include/otbSOMLearningBehaviorFunctor.h +++ b/Modules/Learning/SOM/include/otbSOMLearningBehaviorFunctor.h @@ -10,7 +10,7 @@ See OTBCopyright.txt for details. Copyright (c) Institut Telecom; Telecom bretagne. All rights reserved. - See ITCopyright.txt for details. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Learning/SOM/include/otbSOMMap.h b/Modules/Learning/SOM/include/otbSOMMap.h index 00276472de2b5328775d3f2f410ce88560a09572..9135f1c731a44dbed499458b7e3a3730444e75d3 100644 --- a/Modules/Learning/SOM/include/otbSOMMap.h +++ b/Modules/Learning/SOM/include/otbSOMMap.h @@ -10,7 +10,7 @@ See OTBCopyright.txt for details. Copyright (c) Institut Telecom; Telecom Bretagne. All right reserved. -See GETCopyright.txt for details. +See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even diff --git a/Modules/Learning/SOM/include/otbSOMMap.txx b/Modules/Learning/SOM/include/otbSOMMap.txx index 9f027e61dfb6954ca67728a23f8df3b5954d83d9..e36e4d6a66a045afd7ea6f04e1662572b840c9d2 100644 --- a/Modules/Learning/SOM/include/otbSOMMap.txx +++ b/Modules/Learning/SOM/include/otbSOMMap.txx @@ -10,7 +10,7 @@ See OTBCopyright.txt for details. Copyright (c) Institut Telecom; Telecom Bretagne. All right reserved. -See GETCopyright.txt for details. +See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even diff --git a/Modules/Learning/SOM/include/otbSOMWithMissingValue.h b/Modules/Learning/SOM/include/otbSOMWithMissingValue.h index 94219310f6d267a00b238c2f9a5774ca9adf7fa7..51aef377d0d4d00c8bd9cacb129177066e0a28b6 100644 --- a/Modules/Learning/SOM/include/otbSOMWithMissingValue.h +++ b/Modules/Learning/SOM/include/otbSOMWithMissingValue.h @@ -10,7 +10,7 @@ See OTBCopyright.txt for details. Copyright (c) Institut Telecom; Telecom bretagne. All rights reserved. - See ITCopyright.txt for details. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Learning/SOM/include/otbSOMWithMissingValue.txx b/Modules/Learning/SOM/include/otbSOMWithMissingValue.txx index 0e62e477129589a5f23b97bdcc65fc1abbba3aef..fdb01dd57090beb4dbca8471925b5b014af2fb05 100644 --- a/Modules/Learning/SOM/include/otbSOMWithMissingValue.txx +++ b/Modules/Learning/SOM/include/otbSOMWithMissingValue.txx @@ -10,7 +10,7 @@ See OTBCopyright.txt for details. Copyright (c) Institut Telecom; Telecom bretagne. All rights reserved. - See ITCopyright.txt for details. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Learning/SOM/include/otbSOMbasedImageFilter.h b/Modules/Learning/SOM/include/otbSOMbasedImageFilter.h index 47b1fb2bb5689192d242c8c5948827fc4ed7b7e0..5935f10ec167d5d27698a3592f8ecfeb415d302c 100644 --- a/Modules/Learning/SOM/include/otbSOMbasedImageFilter.h +++ b/Modules/Learning/SOM/include/otbSOMbasedImageFilter.h @@ -10,7 +10,7 @@ See OTBCopyright.txt for details. Copyright (c) Institut Telecom; Telecom bretagne. All rights reserved. - See ITCopyright.txt for details. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even diff --git a/Modules/Learning/SOM/include/otbSOMbasedImageFilter.txx b/Modules/Learning/SOM/include/otbSOMbasedImageFilter.txx index a5f9b4639ca46236ec63a0e35a38c990eb476626..6e6e4f1a625514aefec8cdb02c4758f89982b936 100644 --- a/Modules/Learning/SOM/include/otbSOMbasedImageFilter.txx +++ b/Modules/Learning/SOM/include/otbSOMbasedImageFilter.txx @@ -10,7 +10,7 @@ See OTBCopyright.txt for details. Copyright (c) Institut Telecom; Telecom bretagne. All rights reserved. - See ITCopyright.txt for details. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even diff --git a/Modules/Learning/SOM/test/otbSOMWithMissingValueNew.cxx b/Modules/Learning/SOM/test/otbSOMWithMissingValueNew.cxx index 75b8fab15896c21ac45617c1d97880bc77fe0a20..3720430043eca83820bc270b0f4fecb0798d3b83 100644 --- a/Modules/Learning/SOM/test/otbSOMWithMissingValueNew.cxx +++ b/Modules/Learning/SOM/test/otbSOMWithMissingValueNew.cxx @@ -10,7 +10,7 @@ See OTBCopyright.txt for details. Copyright (c) Institut Telecom; Telecom bretagne. All rights reserved. - See ITCopyright.txt for details. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even diff --git a/Modules/Learning/SOM/test/otbSOMbasedImageFilterNew.cxx b/Modules/Learning/SOM/test/otbSOMbasedImageFilterNew.cxx index 8e8bbfc1fe48397ba4c0c07d6ca3268413d4327b..a47be5f4e438ca6b6ca69b0d8c8cf05280a73979 100644 --- a/Modules/Learning/SOM/test/otbSOMbasedImageFilterNew.cxx +++ b/Modules/Learning/SOM/test/otbSOMbasedImageFilterNew.cxx @@ -10,7 +10,7 @@ See OTBCopyright.txt for details. Copyright (c) Institut Telecom; Telecom bretagne. All rights reserved. - See ITCopyright.txt for details. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even diff --git a/Modules/Learning/SVMLearning/include/otbSVMImageClassificationWithRuleFilter.h b/Modules/Learning/SVMLearning/include/otbSVMImageClassificationWithRuleFilter.h index 55c06dba46c3fee96df10cb48f18247017981abe..e66afd9c497e81ec7f2a8fd78a72a91c7062fe98 100644 --- a/Modules/Learning/SVMLearning/include/otbSVMImageClassificationWithRuleFilter.h +++ b/Modules/Learning/SVMLearning/include/otbSVMImageClassificationWithRuleFilter.h @@ -10,7 +10,7 @@ See OTBCopyright.txt for details. Copyright (c) Institut Telecom; Telecom bretagne. All rights reserved. - See ITCopyright.txt for details. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Learning/SVMLearning/include/otbSVMImageClassificationWithRuleFilter.txx b/Modules/Learning/SVMLearning/include/otbSVMImageClassificationWithRuleFilter.txx index a10c5ad2f0e2b011ed9a15ce9282be9fc269dcde..cc7ad7f23fe526b3054fdf791783192cc1d412ce 100644 --- a/Modules/Learning/SVMLearning/include/otbSVMImageClassificationWithRuleFilter.txx +++ b/Modules/Learning/SVMLearning/include/otbSVMImageClassificationWithRuleFilter.txx @@ -10,7 +10,7 @@ See OTBCopyright.txt for details. Copyright (c) Institut Telecom; Telecom bretagne. All rights reserved. - See ITCopyright.txt for details. + See IMTCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Learning/Supervised/include/otbBoostMachineLearningModel.h b/Modules/Learning/Supervised/include/otbBoostMachineLearningModel.h index 185d10ba44bf26db0a9444c5eb61025ef4f2899a..a812eca2b8f36708b19e186d7221a0a23cc07f4f 100644 --- a/Modules/Learning/Supervised/include/otbBoostMachineLearningModel.h +++ b/Modules/Learning/Supervised/include/otbBoostMachineLearningModel.h @@ -92,6 +92,11 @@ public: itkGetMacro(MaxDepth, int); itkSetMacro(MaxDepth, int); + /** Train the machine learning model */ + virtual void Train(); + /** Predict values using the model */ + virtual TargetSampleType Predict(const InputSampleType& input, ConfidenceValueType *quality=NULL) const; + /** Save the model to file */ virtual void Save(const std::string & filename, const std::string & name=""); @@ -117,11 +122,6 @@ protected: /** PrintSelf method */ void PrintSelf(std::ostream& os, itk::Indent indent) const; - /** Train the machine learning model */ - virtual void TrainClassification(); - /** Predict values using the model */ - virtual TargetSampleType PredictClassification(const InputSampleType& input, ConfidenceValueType *quality=NULL) const; - private: BoostMachineLearningModel(const Self &); //purposely not implemented void operator =(const Self&); //purposely not implemented diff --git a/Modules/Learning/Supervised/include/otbBoostMachineLearningModel.txx b/Modules/Learning/Supervised/include/otbBoostMachineLearningModel.txx index 493107f9ff2b8da6c652fc67bc31376664eed1cc..15a9d5c293b8fa61a87b2f714aef15d0379a0686 100644 --- a/Modules/Learning/Supervised/include/otbBoostMachineLearningModel.txx +++ b/Modules/Learning/Supervised/include/otbBoostMachineLearningModel.txx @@ -52,7 +52,7 @@ BoostMachineLearningModel<TInputValue,TOutputValue> template <class TInputValue, class TOutputValue> void BoostMachineLearningModel<TInputValue,TOutputValue> -::TrainClassification() +::Train() { //convert listsample to opencv matrix cv::Mat samples; @@ -77,7 +77,7 @@ template <class TInputValue, class TOutputValue> typename BoostMachineLearningModel<TInputValue,TOutputValue> ::TargetSampleType BoostMachineLearningModel<TInputValue,TOutputValue> -::PredictClassification(const InputSampleType & input, ConfidenceValueType *quality) const +::Predict(const InputSampleType & input, ConfidenceValueType *quality) const { //convert listsample to Mat cv::Mat sample; diff --git a/Modules/Learning/Supervised/include/otbDecisionTreeMachineLearningModel.h b/Modules/Learning/Supervised/include/otbDecisionTreeMachineLearningModel.h index 6415fa940e273e5d9074a130ba95a8d8105a4978..651a48f6ee319e2c4171f15741df7e9615205c2d 100644 --- a/Modules/Learning/Supervised/include/otbDecisionTreeMachineLearningModel.h +++ b/Modules/Learning/Supervised/include/otbDecisionTreeMachineLearningModel.h @@ -147,11 +147,10 @@ public: return m_Priors; } - /** Setters/Getters to IsRegression flag - * Default is False - */ - itkGetMacro(IsRegression, bool); - itkSetMacro(IsRegression, bool); + /** Train the machine learning model */ + virtual void Train(); + /** Predict values using the model */ + virtual TargetSampleType Predict(const InputSampleType& input, ConfidenceValueType *quality=NULL) const; /** Save the model to file */ virtual void Save(const std::string & filename, const std::string & name=""); @@ -178,11 +177,6 @@ protected: /** PrintSelf method */ void PrintSelf(std::ostream& os, itk::Indent indent) const; - /** Train the machine learning model */ - virtual void TrainClassification(); - /** Predict values using the model */ - virtual TargetSampleType PredictClassification(const InputSampleType& input, ConfidenceValueType *quality=NULL) const; - private: DecisionTreeMachineLearningModel(const Self &); //purposely not implemented void operator =(const Self&); //purposely not implemented @@ -196,7 +190,6 @@ private: int m_MaxCategories; int m_CVFolds; bool m_Use1seRule; - bool m_IsRegression; bool m_TruncatePrunedTree; std::vector<float> m_Priors; diff --git a/Modules/Learning/Supervised/include/otbDecisionTreeMachineLearningModel.txx b/Modules/Learning/Supervised/include/otbDecisionTreeMachineLearningModel.txx index ada456e94c35ff1467e97b8301a5e4a315fa35f6..283fb039c35fd04aea4cc2a63c580ee665014ab4 100644 --- a/Modules/Learning/Supervised/include/otbDecisionTreeMachineLearningModel.txx +++ b/Modules/Learning/Supervised/include/otbDecisionTreeMachineLearningModel.txx @@ -38,9 +38,9 @@ DecisionTreeMachineLearningModel<TInputValue,TOutputValue> m_MaxCategories(10), m_CVFolds(10), m_Use1seRule(true), - m_IsRegression(false), m_TruncatePrunedTree(true) { + this->m_IsRegressionSupported = true; } @@ -55,7 +55,7 @@ DecisionTreeMachineLearningModel<TInputValue,TOutputValue> template <class TInputValue, class TOutputValue> void DecisionTreeMachineLearningModel<TInputValue,TOutputValue> -::TrainClassification() +::Train() { //convert listsample to opencv matrix cv::Mat samples; @@ -73,7 +73,7 @@ DecisionTreeMachineLearningModel<TInputValue,TOutputValue> cv::Mat var_type = cv::Mat(this->GetInputListSample()->GetMeasurementVectorSize() + 1, 1, CV_8U ); var_type.setTo(cv::Scalar(CV_VAR_NUMERICAL) ); // all inputs are numerical - if (!m_IsRegression) //Classification + if (!this->m_RegressionMode) //Classification var_type.at<uchar>(this->GetInputListSample()->GetMeasurementVectorSize(), 0) = CV_VAR_CATEGORICAL; m_DTreeModel->train(samples,CV_ROW_SAMPLE,labels,cv::Mat(),cv::Mat(),var_type,cv::Mat(),params); @@ -83,7 +83,7 @@ template <class TInputValue, class TOutputValue> typename DecisionTreeMachineLearningModel<TInputValue,TOutputValue> ::TargetSampleType DecisionTreeMachineLearningModel<TInputValue,TOutputValue> -::PredictClassification(const InputSampleType & input, ConfidenceValueType *quality) const +::Predict(const InputSampleType & input, ConfidenceValueType *quality) const { //convert listsample to Mat cv::Mat sample; diff --git a/Modules/Learning/Supervised/include/otbGradientBoostedTreeMachineLearningModel.h b/Modules/Learning/Supervised/include/otbGradientBoostedTreeMachineLearningModel.h index 3126f44c0ff7073def41f025df615e74013b590b..f10a89c68066f8ee6bbacc252b4088fa057157be 100644 --- a/Modules/Learning/Supervised/include/otbGradientBoostedTreeMachineLearningModel.h +++ b/Modules/Learning/Supervised/include/otbGradientBoostedTreeMachineLearningModel.h @@ -100,6 +100,11 @@ public: itkGetMacro(UseSurrogates, bool); itkSetMacro(UseSurrogates, bool); + /** Train the machine learning model */ + virtual void Train(); + /** Predict values using the model */ + virtual TargetSampleType Predict(const InputSampleType& input, ConfidenceValueType *quality=NULL) const; + /** Save the model to file */ virtual void Save(const std::string & filename, const std::string & name=""); @@ -125,11 +130,6 @@ protected: /** PrintSelf method */ void PrintSelf(std::ostream& os, itk::Indent indent) const; - /** Train the machine learning model */ - virtual void TrainClassification(); - /** Predict values using the model */ - virtual TargetSampleType PredictClassification(const InputSampleType& input, ConfidenceValueType *quality=NULL) const; - private: GradientBoostedTreeMachineLearningModel(const Self &); //purposely not implemented void operator =(const Self&); //purposely not implemented @@ -142,7 +142,6 @@ private: double m_SubSamplePortion; int m_MaxDepth; bool m_UseSurrogates; - bool m_IsRegression; }; diff --git a/Modules/Learning/Supervised/include/otbGradientBoostedTreeMachineLearningModel.txx b/Modules/Learning/Supervised/include/otbGradientBoostedTreeMachineLearningModel.txx index 595f1bb060b8ffbcb533352915f41b69c2bd1458..d08abec0290776a5d6a7ddfd3df27e6b5216d620 100644 --- a/Modules/Learning/Supervised/include/otbGradientBoostedTreeMachineLearningModel.txx +++ b/Modules/Learning/Supervised/include/otbGradientBoostedTreeMachineLearningModel.txx @@ -36,9 +36,9 @@ GradientBoostedTreeMachineLearningModel<TInputValue,TOutputValue> m_Shrinkage(0.01), m_SubSamplePortion(0.8), m_MaxDepth(3), - m_UseSurrogates(false), - m_IsRegression(false) + m_UseSurrogates(false) { + this->m_IsRegressionSupported = true; } @@ -53,7 +53,7 @@ GradientBoostedTreeMachineLearningModel<TInputValue,TOutputValue> template <class TInputValue, class TOutputValue> void GradientBoostedTreeMachineLearningModel<TInputValue,TOutputValue> -::TrainClassification() +::Train() { //convert listsample to opencv matrix cv::Mat samples; @@ -62,7 +62,6 @@ GradientBoostedTreeMachineLearningModel<TInputValue,TOutputValue> cv::Mat labels; otb::ListSampleToMat<TargetListSampleType>(this->GetTargetListSample(),labels); - CvGBTreesParams params = CvGBTreesParams(m_LossFunctionType, m_WeakCount, m_Shrinkage, m_SubSamplePortion, m_MaxDepth, m_UseSurrogates); @@ -70,7 +69,7 @@ GradientBoostedTreeMachineLearningModel<TInputValue,TOutputValue> cv::Mat var_type = cv::Mat(this->GetInputListSample()->GetMeasurementVectorSize() + 1, 1, CV_8U ); var_type.setTo(cv::Scalar(CV_VAR_NUMERICAL) ); // all inputs are numerical - if (!m_IsRegression) //Classification + if (!this->m_RegressionMode) //Classification var_type.at<uchar>(this->GetInputListSample()->GetMeasurementVectorSize(), 0) = CV_VAR_CATEGORICAL; m_GBTreeModel->train(samples,CV_ROW_SAMPLE,labels,cv::Mat(),cv::Mat(),var_type,cv::Mat(),params, false); @@ -80,7 +79,7 @@ template <class TInputValue, class TOutputValue> typename GradientBoostedTreeMachineLearningModel<TInputValue,TOutputValue> ::TargetSampleType GradientBoostedTreeMachineLearningModel<TInputValue,TOutputValue> -::PredictClassification(const InputSampleType & input, ConfidenceValueType *quality) const +::Predict(const InputSampleType & input, ConfidenceValueType *quality) const { //convert listsample to Mat cv::Mat sample; diff --git a/Modules/Learning/Supervised/include/otbImageClassificationFilter.txx b/Modules/Learning/Supervised/include/otbImageClassificationFilter.txx index 88d2ad012441455cc2c2d221e79e175731b3e31f..b0a5d5e3e842ec986dfc2400736b84e2a405bb53 100644 --- a/Modules/Learning/Supervised/include/otbImageClassificationFilter.txx +++ b/Modules/Learning/Supervised/include/otbImageClassificationFilter.txx @@ -118,7 +118,7 @@ ImageClassificationFilter<TInputImage, TOutputImage, TMaskImage> } // setup iterator for confidence map - bool computeConfidenceMap(m_UseConfidenceMap && m_Model->HasConfidenceIndex()); + bool computeConfidenceMap(m_UseConfidenceMap && m_Model->HasConfidenceIndex() && !m_Model->GetRegressionMode()); ConfidenceMapIteratorType confidenceIt; if (computeConfidenceMap) { diff --git a/Modules/Learning/Supervised/include/otbKNearestNeighborsMachineLearningModel.h b/Modules/Learning/Supervised/include/otbKNearestNeighborsMachineLearningModel.h index b8524b7fb677aff35b706a54b87b6a917251754b..3f29a10af3ed6b46d700684eddeab80a5076c17a 100644 --- a/Modules/Learning/Supervised/include/otbKNearestNeighborsMachineLearningModel.h +++ b/Modules/Learning/Supervised/include/otbKNearestNeighborsMachineLearningModel.h @@ -58,12 +58,23 @@ public: itkGetMacro(K, int); itkSetMacro(K, int); - /** Setters/Getters to IsRegression flag - * Default is False - * \see http://docs.opencv.org/modules/ml/doc/k_nearest_neighbors.html + /** Decision rule once the KNN are found : + * [for classification] + * - KNN_VOTING : output value with maximum occurences (for classification) + * [for regression] + * - KNN_MEAN : output mean value of neighbors + * - KNN_MEDIAN : output median value of neighbors */ - itkGetMacro(IsRegression, bool); - itkSetMacro(IsRegression, bool); + enum {KNN_VOTING, KNN_MEAN, KNN_MEDIAN}; + + /** Setters/Getters to the decision rule */ + itkGetMacro(DecisionRule, int); + itkSetMacro(DecisionRule, int); + + /** Train the machine learning model */ + virtual void Train(); + /** Predict values using the model */ + virtual TargetSampleType Predict(const InputSampleType& input, ConfidenceValueType *quality=NULL) const; /** Save the model to file */ virtual void Save(const std::string & filename, const std::string & name=""); @@ -90,18 +101,14 @@ protected: /** PrintSelf method */ void PrintSelf(std::ostream& os, itk::Indent indent) const; - /** Train the machine learning model */ - virtual void TrainClassification(); - /** Predict values using the model */ - virtual TargetSampleType PredictClassification(const InputSampleType& input, ConfidenceValueType *quality=NULL) const; - private: KNearestNeighborsMachineLearningModel(const Self &); //purposely not implemented void operator =(const Self&); //purposely not implemented CvKNearest * m_KNearestModel; int m_K; - bool m_IsRegression; + + int m_DecisionRule; }; } // end namespace otb diff --git a/Modules/Learning/Supervised/include/otbKNearestNeighborsMachineLearningModel.txx b/Modules/Learning/Supervised/include/otbKNearestNeighborsMachineLearningModel.txx index e890b9137ac284848eda3c10885bfd736a4c28ac..fd33b7c9061fc3ce66c70cf9ea5c4c7780c42dc8 100644 --- a/Modules/Learning/Supervised/include/otbKNearestNeighborsMachineLearningModel.txx +++ b/Modules/Learning/Supervised/include/otbKNearestNeighborsMachineLearningModel.txx @@ -23,6 +23,7 @@ #include "otbOpenCVUtils.h" #include <fstream> +#include <set> #include "itkMacro.h" namespace otb @@ -33,9 +34,10 @@ KNearestNeighborsMachineLearningModel<TInputValue,TTargetValue> ::KNearestNeighborsMachineLearningModel() : m_KNearestModel (new CvKNearest), m_K(32), - m_IsRegression(false) + m_DecisionRule(KNN_VOTING) { this->m_ConfidenceIndex = true; + this->m_IsRegressionSupported = true; } @@ -50,7 +52,7 @@ KNearestNeighborsMachineLearningModel<TInputValue,TTargetValue> template <class TInputValue, class TTargetValue> void KNearestNeighborsMachineLearningModel<TInputValue,TTargetValue> -::TrainClassification() +::Train() { //convert listsample to opencv matrix cv::Mat samples; @@ -59,26 +61,44 @@ KNearestNeighborsMachineLearningModel<TInputValue,TTargetValue> cv::Mat labels; otb::ListSampleToMat<TargetListSampleType>(this->GetTargetListSample(), labels); + // update decision rule if needed + if (this->m_RegressionMode) + { + if (this->m_DecisionRule == KNN_VOTING) + { + this->SetDecisionRule(KNN_MEAN); + } + } + else + { + if (this->m_DecisionRule != KNN_VOTING) + { + this->SetDecisionRule(KNN_VOTING); + } + } + //train the KNN model - m_KNearestModel->train(samples, labels, cv::Mat(), m_IsRegression, m_K, false); + m_KNearestModel->train(samples, labels, cv::Mat(), this->m_RegressionMode, m_K, false); } template <class TInputValue, class TTargetValue> typename KNearestNeighborsMachineLearningModel<TInputValue,TTargetValue> ::TargetSampleType KNearestNeighborsMachineLearningModel<TInputValue,TTargetValue> -::PredictClassification(const InputSampleType & input, ConfidenceValueType *quality) const +::Predict(const InputSampleType & input, ConfidenceValueType *quality) const { //convert listsample to Mat cv::Mat sample; otb::SampleToMat<InputSampleType>(input, sample); float result; + cv::Mat nearest(1,m_K,CV_32FC1); + result = m_KNearestModel->find_nearest(sample, m_K,0,0,&nearest,0); + // compute quality if asked (only happens in classification mode) if (quality != NULL) { - cv::Mat nearest(1,m_K,CV_32FC1); - result = m_KNearestModel->find_nearest(sample, m_K,0,0,&nearest,0); + assert(!this->m_RegressionMode); unsigned int accuracy = 0; for (int k=0 ; k < m_K ; ++k) { @@ -89,9 +109,22 @@ KNearestNeighborsMachineLearningModel<TInputValue,TTargetValue> } (*quality) = static_cast<ConfidenceValueType>(accuracy); } - else + + // Decision rule : + // VOTING is OpenCV default behaviour for classification + // MEAN is OpenCV default behaviour for regression + // MEDIAN : only case that must be handled here + if (this->m_DecisionRule == KNN_MEDIAN) { - result = m_KNearestModel->find_nearest(sample, m_K); + std::multiset<float> values; + for (int k=0 ; k < m_K ; ++k) + { + values.insert(nearest.at<float>(0,k)); + } + std::multiset<float>::iterator median = values.begin(); + int pos = (m_K >> 1); + for (int k=0 ; k < pos ; ++k , ++median) {} + result = *median; } TargetSampleType target; @@ -106,12 +139,17 @@ KNearestNeighborsMachineLearningModel<TInputValue,TTargetValue> ::Save(const std::string & filename, const std::string & itkNotUsed(name)) { //there is no m_KNearestModel->save(filename.c_str(), name.c_str()). - //We need to save the K parameter and IsRegression flag used and the samples. + //We need to save the K parameter, IsRegression flag, DecisionRule and the samples. std::ofstream ofs(filename.c_str()); //Save K parameter and IsRegression flag. ofs << "K=" << m_K << "\n"; - ofs << "IsRegression=" << m_IsRegression << "\n"; + ofs << "IsRegression=" << this->m_RegressionMode << "\n"; + // Save the DecisionRule if regression + if (this->m_RegressionMode) + { + ofs << "DecisionRule=" << m_DecisionRule << "\n"; + } //Save the samples. First column is the Label and other columns are the sample data. typename InputListSampleType::ConstIterator sampleIt = this->GetInputListSample()->Begin(); @@ -154,8 +192,15 @@ KNearestNeighborsMachineLearningModel<TInputValue,TTargetValue> std::getline(ifs, line); pos = line.find_first_of("=", 0); nextpos = line.find_first_of(" \n\r", pos+1); - this->SetIsRegression(boost::lexical_cast<bool>(line.substr(pos+1, nextpos-pos-1))); - + this->SetRegressionMode(boost::lexical_cast<bool>(line.substr(pos+1, nextpos-pos-1))); + //third line is the DecisionRule parameter (only for regression) + if (this->m_RegressionMode) + { + std::getline(ifs, line); + pos = line.find_first_of("=", 0); + nextpos = line.find_first_of(" \n\r", pos+1); + this->SetDecisionRule(boost::lexical_cast<int>(line.substr(pos+1, nextpos-pos-1))); + } //Clear previous listSample (if any) typename InputListSampleType::Pointer samples = InputListSampleType::New(); typename TargetListSampleType::Pointer labels = TargetListSampleType::New(); diff --git a/Modules/Learning/Supervised/include/otbLibSVMMachineLearningModel.h b/Modules/Learning/Supervised/include/otbLibSVMMachineLearningModel.h index 18eba7fbb28d336967ac669d05cda51bc5ebdc4c..622923753e37d1216de669a9724c72b979015f83 100644 --- a/Modules/Learning/Supervised/include/otbLibSVMMachineLearningModel.h +++ b/Modules/Learning/Supervised/include/otbLibSVMMachineLearningModel.h @@ -59,6 +59,11 @@ public: itkNewMacro(Self); itkTypeMacro(SVMMachineLearningModel, MachineLearningModel); + /** Train the machine learning model */ + virtual void Train(); + /** Predict values using the model */ + virtual TargetSampleType Predict(const InputSampleType& input, ConfidenceValueType *quality=NULL) const; + /** Save the model to file */ virtual void Save(const std::string &filename, const std::string & name=""); @@ -75,23 +80,40 @@ public: //@} //Setters/Getters to SVM model - // itkGetMacro(SVMType, int); - // itkSetMacro(SVMType, int); + otbGetObjectMemberMacro(SVMestimator, SVMType, int); + otbSetObjectMemberMacro(SVMestimator, SVMType, int); + + otbGetObjectMemberMacro(SVMestimator, KernelType, int); + otbSetObjectMemberMacro(SVMestimator, KernelType, int); + + otbGetObjectMemberMacro(SVMestimator, C, double); + otbSetObjectMemberMacro(SVMestimator, C, double); - itkGetMacro(KernelType, int); - itkSetMacro(KernelType, int); + // TODO : we should harmonize this parameter name : ParameterOptimization -> ParametersOptimization + bool GetParameterOptimization() + { + return this->m_SVMestimator->GetParametersOptimization(); + } + void SetParameterOptimization(bool value) + { + this->m_SVMestimator->SetParametersOptimization(value); + this->Modified(); + } - itkGetMacro(C, float); - itkSetMacro(C, float); + otbGetObjectMemberMacro(SVMestimator, DoProbabilityEstimates, bool); + void SetDoProbabilityEstimates(bool value) + { + this->m_SVMestimator->DoProbabilityEstimates(value); + } - itkGetMacro(ParameterOptimization, bool); - itkSetMacro(ParameterOptimization, bool); - - itkGetMacro(DoProbabilityEstimates, bool); - itkSetMacro(DoProbabilityEstimates, bool); + otbGetObjectMemberMacro(SVMestimator, Epsilon, double); + otbSetObjectMemberMacro(SVMestimator, Epsilon, double); - // itkGetMacro(Epsilon, int); - // itkSetMacro(Epsilon, int); + otbGetObjectMemberMacro(SVMestimator, P, double); + otbSetObjectMemberMacro(SVMestimator, P, double); + + otbGetObjectMemberMacro(SVMestimator, Nu, double); + otbSetObjectMemberMacro(SVMestimator, Nu, double); protected: /** Constructor */ @@ -103,19 +125,10 @@ protected: /** PrintSelf method */ void PrintSelf(std::ostream& os, itk::Indent indent) const; - /** Train the machine learning model */ - virtual void TrainClassification(); - /** Predict values using the model */ - virtual TargetSampleType PredictClassification(const InputSampleType& input, ConfidenceValueType *quality=NULL) const; - private: LibSVMMachineLearningModel(const Self &); //purposely not implemented void operator =(const Self&); //purposely not implemented - int m_KernelType; - float m_C; - bool m_ParameterOptimization; - bool m_DoProbabilityEstimates; typename SVMEstimatorType::Pointer m_SVMestimator; }; } // end namespace otb diff --git a/Modules/Learning/Supervised/include/otbLibSVMMachineLearningModel.txx b/Modules/Learning/Supervised/include/otbLibSVMMachineLearningModel.txx index 24e91e54a25406d100a8cae8f4b09741f124e80f..e95e97543d3a67537c848c8933165d5907370400 100644 --- a/Modules/Learning/Supervised/include/otbLibSVMMachineLearningModel.txx +++ b/Modules/Learning/Supervised/include/otbLibSVMMachineLearningModel.txx @@ -20,10 +20,6 @@ #include <fstream> #include "otbLibSVMMachineLearningModel.h" -//#include "otbOpenCVUtils.h" - -// SVM estimator -//#include "otbSVMSampleListModelEstimator.h" namespace otb { @@ -32,15 +28,14 @@ template <class TInputValue, class TOutputValue> LibSVMMachineLearningModel<TInputValue,TOutputValue> ::LibSVMMachineLearningModel() { - // m_SVMModel = new CvSVM; - // m_SVMType = CvSVM::C_SVC; - m_KernelType = LINEAR; - // m_TermCriteriaType = CV_TERMCRIT_ITER; - m_C = 1.0; - // m_Epsilon = 1e-6; - m_ParameterOptimization = false; - m_DoProbabilityEstimates = false; m_SVMestimator = SVMEstimatorType::New(); + m_SVMestimator->SetSVMType(C_SVC); + m_SVMestimator->SetC(1.0); + m_SVMestimator->SetKernelType(LINEAR); + m_SVMestimator->SetParametersOptimization(false); + m_SVMestimator->DoProbabilityEstimates(false); + //m_SVMestimator->SetEpsilon(1e-6); + this->m_IsRegressionSupported = true; } @@ -55,7 +50,7 @@ LibSVMMachineLearningModel<TInputValue,TOutputValue> template <class TInputValue, class TOutputValue> void LibSVMMachineLearningModel<TInputValue,TOutputValue> -::TrainClassification() +::Train() { // Set up SVM's parameters // CvSVMParams params; @@ -64,25 +59,19 @@ LibSVMMachineLearningModel<TInputValue,TOutputValue> // params.term_crit = cvTermCriteria(m_TermCriteriaType, m_MaxIter, m_Epsilon); // // Train the SVM - - m_SVMestimator->SetC(m_C); - m_SVMestimator->SetKernelType(m_KernelType); - m_SVMestimator->SetParametersOptimization(m_ParameterOptimization); - m_SVMestimator->DoProbabilityEstimates(m_DoProbabilityEstimates); - m_SVMestimator->SetInputSampleList(this->GetInputListSample()); m_SVMestimator->SetTrainingSampleList(this->GetTargetListSample()); m_SVMestimator->Update(); - this->m_ConfidenceIndex = m_DoProbabilityEstimates; + this->m_ConfidenceIndex = this->GetDoProbabilityEstimates(); } template <class TInputValue, class TOutputValue> typename LibSVMMachineLearningModel<TInputValue,TOutputValue> ::TargetSampleType LibSVMMachineLearningModel<TInputValue,TOutputValue> -::PredictClassification(const InputSampleType & input, ConfidenceValueType *quality) const +::Predict(const InputSampleType & input, ConfidenceValueType *quality) const { TargetSampleType target; diff --git a/Modules/Learning/Supervised/include/otbMachineLearningModel.h b/Modules/Learning/Supervised/include/otbMachineLearningModel.h index ba0ca60d224fa138fe5a9e8e702993555394559b..b18e39e15c89fabff9ff2c640122740e710972f5 100644 --- a/Modules/Learning/Supervised/include/otbMachineLearningModel.h +++ b/Modules/Learning/Supervised/include/otbMachineLearningModel.h @@ -97,10 +97,10 @@ public: //@} /** Train the machine learning model */ - void Train(); + virtual void Train() =0; /** Predict values using the model */ - TargetSampleType Predict(const InputSampleType& input, ConfidenceValueType *quality = NULL) const; + virtual TargetSampleType Predict(const InputSampleType& input, ConfidenceValueType *quality = NULL) const = 0; /** Classify all samples in InputListSample and fill TargetListSample with the associated label */ void PredictAll(); @@ -140,6 +140,12 @@ public: itkGetObjectMacro(TargetListSample,TargetListSampleType); //@} + /**\name Use model in regression mode */ + //@{ + itkGetMacro(RegressionMode,bool); + void SetRegressionMode(bool flag); + //@} + protected: /** Constructor */ MachineLearningModel(); @@ -156,22 +162,14 @@ protected: /** Target list sample */ typename TargetListSampleType::Pointer m_TargetListSample; - /** Train the machine learning model */ - virtual void TrainRegression() - { - itkGenericExceptionMacro(<< "Regression mode not implemented."); - } - virtual void TrainClassification() = 0; - /** Predict values using the model */ - virtual TargetSampleType PredictRegression(const InputSampleType& itkNotUsed(input)) const - { - itkGenericExceptionMacro(<< "Regression mode not implemented."); - } - - virtual TargetSampleType PredictClassification(const InputSampleType& input, ConfidenceValueType *quality = NULL) const = 0; - + /** flag to choose between classification and regression modes */ bool m_RegressionMode; + /** flag that indicates if the model supports regression, child + * classes should modify it in their constructor if they support + * regression mode */ + bool m_IsRegressionSupported; + /** flag that tells if the model support confidence index output */ bool m_ConfidenceIndex; private: diff --git a/Modules/Learning/Supervised/include/otbMachineLearningModel.txx b/Modules/Learning/Supervised/include/otbMachineLearningModel.txx index b4b6127c11c252c3d5a73d0a50716d48da6e7a49..8cc82055fe1a7a08594a01f3d9aeba6dfc12d927 100644 --- a/Modules/Learning/Supervised/include/otbMachineLearningModel.txx +++ b/Modules/Learning/Supervised/include/otbMachineLearningModel.txx @@ -25,7 +25,10 @@ namespace otb template <class TInputValue, class TOutputValue, class TConfidenceValue> MachineLearningModel<TInputValue,TOutputValue,TConfidenceValue> -::MachineLearningModel() : m_RegressionMode(false),m_ConfidenceIndex(false) +::MachineLearningModel() : + m_RegressionMode(false), + m_IsRegressionSupported(false), + m_ConfidenceIndex(false) {} @@ -37,23 +40,17 @@ MachineLearningModel<TInputValue,TOutputValue,TConfidenceValue> template <class TInputValue, class TOutputValue, class TConfidenceValue> void MachineLearningModel<TInputValue,TOutputValue,TConfidenceValue> -::Train() +::SetRegressionMode(bool flag) { - if(m_RegressionMode) - return this->TrainRegression(); - else - return this->TrainClassification(); -} - -template <class TInputValue, class TOutputValue, class TConfidenceValue> -typename MachineLearningModel<TInputValue,TOutputValue,TConfidenceValue>::TargetSampleType -MachineLearningModel<TInputValue,TOutputValue,TConfidenceValue> -::Predict(const InputSampleType& input, ConfidenceValueType *quality) const -{ - if(m_RegressionMode) - return this->PredictRegression(input); - else - return this->PredictClassification(input,quality); + if (flag && !m_IsRegressionSupported) + { + itkGenericExceptionMacro(<< "Regression mode not implemented."); + } + if (m_RegressionMode != flag) + { + m_RegressionMode = flag; + this->Modified(); + } } template <class TInputValue, class TOutputValue, class TConfidenceValue> diff --git a/Modules/Learning/Supervised/include/otbNeuralNetworkMachineLearningModel.h b/Modules/Learning/Supervised/include/otbNeuralNetworkMachineLearningModel.h index 2eab72042d9ff5b3228df2d628ee0618127b01f4..fa1abade18cce80abb493406fabbcebbe97c9ddc 100644 --- a/Modules/Learning/Supervised/include/otbNeuralNetworkMachineLearningModel.h +++ b/Modules/Learning/Supervised/include/otbNeuralNetworkMachineLearningModel.h @@ -151,6 +151,11 @@ public: itkGetMacro(Epsilon, double); itkSetMacro(Epsilon, double); + /** Train the machine learning model */ + virtual void Train(); + /** Predict values using the model */ + virtual TargetSampleType Predict(const InputSampleType& input, ConfidenceValueType *quality=NULL) const; + /** Save the model to file */ virtual void Save(const std::string & filename, const std::string & name=""); @@ -178,15 +183,14 @@ protected: /** PrintSelf method */ void PrintSelf(std::ostream& os, itk::Indent indent) const; - /** Train the machine learning model */ - virtual void TrainClassification(); - /** Predict values using the model */ - virtual TargetSampleType PredictClassification(const InputSampleType& input, ConfidenceValueType *quality=NULL) const; - private: NeuralNetworkMachineLearningModel(const Self &); //purposely not implemented void operator =(const Self&); //purposely not implemented + void CreateNetwork(); + CvANN_MLP_TrainParams SetNetworkParameters(); + void SetupNetworkAndTrain(cv::Mat& labels); + CvANN_MLP * m_ANNModel; int m_TrainMethod; int m_ActivateFunction; diff --git a/Modules/Learning/Supervised/include/otbNeuralNetworkMachineLearningModel.txx b/Modules/Learning/Supervised/include/otbNeuralNetworkMachineLearningModel.txx index 01c31811d7c793630dfcfe5f0026cc6b7be73356..b76e6dd70d3f57741ac83ef9ce448362d9e942fc 100644 --- a/Modules/Learning/Supervised/include/otbNeuralNetworkMachineLearningModel.txx +++ b/Modules/Learning/Supervised/include/otbNeuralNetworkMachineLearningModel.txx @@ -43,6 +43,7 @@ NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::NeuralNetworkMachi m_CvMatOfLabels(0) { this->m_ConfidenceIndex = true; + this->m_IsRegressionSupported = true; } template<class TInputValue, class TOutputValue> @@ -52,7 +53,7 @@ NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::~NeuralNetworkMach cvReleaseMat(&m_CvMatOfLabels); } -/** Train the machine learning model */ +/** Sets the topology of the NN */ template<class TInputValue, class TOutputValue> void NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::SetLayerSizes(const std::vector<unsigned int> layers) { @@ -72,10 +73,14 @@ template<class TInputValue, class TOutputValue> void NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::LabelsToMat(const TargetListSampleType * labels, cv::Mat & output) { - unsigned int nbSamples = labels->Size(); + unsigned int nbSamples = 0; + if (labels != NULL) + { + nbSamples = labels->Size(); + } // Check for valid listSample - if (labels != NULL && nbSamples > 0) + if (nbSamples > 0) { // Build an iterator typename TargetListSampleType::ConstIterator labelSampleIt = labels->Begin(); @@ -130,9 +135,8 @@ void NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::LabelsToMat(c } } -/** Train the machine learning model */ template<class TInputValue, class TOutputValue> -void NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::TrainClassification() +void NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::CreateNetwork() { //Create the neural network const unsigned int nbLayers = m_LayerSizes.size(); @@ -147,14 +151,11 @@ void NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::TrainClassifi } m_ANNModel->create(layers, m_ActivateFunction, m_Alpha, m_Beta); +} - //convert listsample to opencv matrix - cv::Mat samples; - otb::ListSampleToMat<InputListSampleType>(this->GetInputListSample(), samples); - - cv::Mat matOutputANN; - LabelsToMat(this->GetTargetListSample(), matOutputANN); - +template<class TInputValue, class TOutputValue> +CvANN_MLP_TrainParams NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::SetNetworkParameters() +{ CvANN_MLP_TrainParams params; params.train_method = m_TrainMethod; params.bp_dw_scale = m_BackPropDWScale; @@ -163,14 +164,43 @@ void NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::TrainClassifi params.rp_dw_min = m_RegPropDWMin; CvTermCriteria term_crit = cvTermCriteria(m_TermCriteriaType, m_MaxIter, m_Epsilon); params.term_crit = term_crit; + return params; +} +template<class TInputValue, class TOutputValue> +void NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::SetupNetworkAndTrain(cv::Mat& labels) +{ + //convert listsample to opencv matrix + cv::Mat samples; + otb::ListSampleToMat<InputListSampleType>(this->GetInputListSample(), samples); + this->CreateNetwork(); + CvANN_MLP_TrainParams params = this->SetNetworkParameters(); //train the Neural network model - m_ANNModel->train(samples, matOutputANN, cv::Mat(), cv::Mat(), params); + m_ANNModel->train(samples, labels, cv::Mat(), cv::Mat(), params); +} + +/** Train the machine learning model for classification*/ +template<class TInputValue, class TOutputValue> +void NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::Train() +{ + //Transform the targets into a matrix of labels + cv::Mat matOutputANN; + if (this->m_RegressionMode) + { + // MODE REGRESSION + otb::ListSampleToMat<TargetListSampleType>(this->GetTargetListSample(), matOutputANN); + } + else + { + // MODE CLASSIFICATION : store the map between internal labels and output labels + LabelsToMat(this->GetTargetListSample(), matOutputANN); + } + this->SetupNetworkAndTrain(matOutputANN); } template<class TInputValue, class TOutputValue> typename NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::TargetSampleType NeuralNetworkMachineLearningModel< - TInputValue, TOutputValue>::PredictClassification(const InputSampleType & input, ConfidenceValueType *quality) const + TInputValue, TOutputValue>::Predict(const InputSampleType & input, ConfidenceValueType *quality) const { //convert listsample to Mat cv::Mat sample; @@ -183,6 +213,15 @@ typename NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::TargetSam TargetSampleType target; float currentResponse = 0; float maxResponse = response.at<float> (0, 0); + + if (this->m_RegressionMode) + { + // MODE REGRESSION : only output first response + target[0] = maxResponse; + return target; + } + + // MODE CLASSIFICATION : find the highest response float secondResponse = -1e10; target[0] = m_CvMatOfLabels->data.i[0]; diff --git a/Modules/Learning/Supervised/include/otbNormalBayesMachineLearningModel.h b/Modules/Learning/Supervised/include/otbNormalBayesMachineLearningModel.h index 31b5373ce16510512aa90065e151408a764898ed..8ecfcd2b51d607169b30dcc86dd59d2096d728f4 100644 --- a/Modules/Learning/Supervised/include/otbNormalBayesMachineLearningModel.h +++ b/Modules/Learning/Supervised/include/otbNormalBayesMachineLearningModel.h @@ -52,6 +52,11 @@ public: itkNewMacro(Self); itkTypeMacro(NormalBayesMachineLearningModel, MachineLearningModel); + /** Train the machine learning model */ + virtual void Train(); + /** Predict values using the model */ + virtual TargetSampleType Predict(const InputSampleType& input, ConfidenceValueType *quality=NULL) const; + /** Save the model to file */ virtual void Save(const std::string & filename, const std::string & name=""); @@ -77,11 +82,6 @@ protected: /** PrintSelf method */ void PrintSelf(std::ostream& os, itk::Indent indent) const; - /** Train the machine learning model */ - virtual void TrainClassification(); - /** Predict values using the model */ - virtual TargetSampleType PredictClassification(const InputSampleType& input, ConfidenceValueType *quality=NULL) const; - private: NormalBayesMachineLearningModel(const Self &); //purposely not implemented void operator =(const Self&); //purposely not implemented diff --git a/Modules/Learning/Supervised/include/otbNormalBayesMachineLearningModel.txx b/Modules/Learning/Supervised/include/otbNormalBayesMachineLearningModel.txx index bfc163553ddb58eb7e3e9f2150fc9cb63dbfaca2..7538f02c8818fcd07851f26044724992d4747af5 100644 --- a/Modules/Learning/Supervised/include/otbNormalBayesMachineLearningModel.txx +++ b/Modules/Learning/Supervised/include/otbNormalBayesMachineLearningModel.txx @@ -45,7 +45,7 @@ NormalBayesMachineLearningModel<TInputValue,TOutputValue> template <class TInputValue, class TOutputValue> void NormalBayesMachineLearningModel<TInputValue,TOutputValue> -::TrainClassification() +::Train() { //convert listsample to opencv matrix cv::Mat samples; @@ -61,7 +61,7 @@ template <class TInputValue, class TOutputValue> typename NormalBayesMachineLearningModel<TInputValue,TOutputValue> ::TargetSampleType NormalBayesMachineLearningModel<TInputValue,TOutputValue> -::PredictClassification(const InputSampleType & input, ConfidenceValueType *quality) const +::Predict(const InputSampleType & input, ConfidenceValueType *quality) const { //convert listsample to Mat cv::Mat sample; diff --git a/Modules/Learning/Supervised/include/otbRandomForestsMachineLearningModel.h b/Modules/Learning/Supervised/include/otbRandomForestsMachineLearningModel.h index 20aff52a7e200f47f9127005addc442d25fd5799..ec62b761358634daa8e268c1488770bb801d3543 100644 --- a/Modules/Learning/Supervised/include/otbRandomForestsMachineLearningModel.h +++ b/Modules/Learning/Supervised/include/otbRandomForestsMachineLearningModel.h @@ -59,6 +59,11 @@ public: itkNewMacro(Self); itkTypeMacro(RandomForestsMachineLearningModel, MachineLearningModel); + /** Train the machine learning model */ + virtual void Train(); + /** Predict values using the model */ + virtual TargetSampleType Predict(const InputSampleType& input, ConfidenceValueType *quality=NULL) const; + /** Save the model to file */ virtual void Save(const std::string & filename, const std::string & name=""); @@ -115,9 +120,6 @@ public: itkGetMacro(TerminationCriteria, int); itkSetMacro(TerminationCriteria, int); - itkGetMacro(RegressionMode, bool); - itkSetMacro(RegressionMode, bool); - /** Returns a matrix containing variable importance */ VariableImportanceMatrixType GetVariableImportance(); @@ -139,11 +141,6 @@ protected: /* /\** Target list sample *\/ */ /* typename TargetListSampleType::Pointer m_TargetListSample; */ - /** Train the machine learning model */ - virtual void TrainClassification(); - /** Predict values using the model */ - virtual TargetSampleType PredictClassification(const InputSampleType& input, ConfidenceValueType *quality=NULL) const; - private: RandomForestsMachineLearningModel(const Self &); //purposely not implemented void operator =(const Self&); //purposely not implemented @@ -208,8 +205,6 @@ private: float m_ForestAccuracy; /** The type of the termination criteria */ int m_TerminationCriteria; - /** Perform regression instead of classification */ - bool m_RegressionMode; }; } // end namespace otb diff --git a/Modules/Learning/Supervised/include/otbRandomForestsMachineLearningModel.txx b/Modules/Learning/Supervised/include/otbRandomForestsMachineLearningModel.txx index 0797c2fabf18077612470b70604d8a3492a64446..78642f1212ac9d75dc75d3bd9e9482d73bc948dc 100644 --- a/Modules/Learning/Supervised/include/otbRandomForestsMachineLearningModel.txx +++ b/Modules/Learning/Supervised/include/otbRandomForestsMachineLearningModel.txx @@ -32,17 +32,17 @@ RandomForestsMachineLearningModel<TInputValue,TOutputValue> m_RFModel (new CvRTrees), m_MaxDepth(5), m_MinSampleCount(10), - m_RegressionAccuracy(0), + m_RegressionAccuracy(0.01), m_ComputeSurrogateSplit(false), m_MaxNumberOfCategories(10), m_CalculateVariableImportance(false), m_MaxNumberOfVariables(0), m_MaxNumberOfTrees(100), m_ForestAccuracy(0.01), - m_TerminationCriteria(CV_TERMCRIT_ITER | CV_TERMCRIT_EPS), - m_RegressionMode(false) + m_TerminationCriteria(CV_TERMCRIT_ITER | CV_TERMCRIT_EPS) { this->m_ConfidenceIndex = true; + this->m_IsRegressionSupported = true; } @@ -65,7 +65,7 @@ RandomForestsMachineLearningModel<TInputValue,TOutputValue> template <class TInputValue, class TOutputValue> void RandomForestsMachineLearningModel<TInputValue,TOutputValue> -::TrainClassification() +::Train() { //convert listsample to opencv matrix cv::Mat samples; @@ -96,7 +96,7 @@ RandomForestsMachineLearningModel<TInputValue,TOutputValue> cv::Mat var_type = cv::Mat(this->GetInputListSample()->GetMeasurementVectorSize() + 1, 1, CV_8U ); var_type.setTo(cv::Scalar(CV_VAR_NUMERICAL) ); // all inputs are numerical - if(m_RegressionMode) + if(this->m_RegressionMode) var_type.at<uchar>(this->GetInputListSample()->GetMeasurementVectorSize(), 0) = CV_VAR_NUMERICAL; else var_type.at<uchar>(this->GetInputListSample()->GetMeasurementVectorSize(), 0) = CV_VAR_CATEGORICAL; @@ -110,7 +110,7 @@ template <class TInputValue, class TOutputValue> typename RandomForestsMachineLearningModel<TInputValue,TOutputValue> ::TargetSampleType RandomForestsMachineLearningModel<TInputValue,TOutputValue> -::PredictClassification(const InputSampleType & value, ConfidenceValueType *quality) const +::Predict(const InputSampleType & value, ConfidenceValueType *quality) const { //convert listsample to Mat cv::Mat sample; diff --git a/Modules/Learning/Supervised/include/otbSVMMachineLearningModel.h b/Modules/Learning/Supervised/include/otbSVMMachineLearningModel.h index 406bdd10e6b04a808fbd2be168e0f7504aa79578..569ab321427925e1e662d941d2be1a398fda54cc 100644 --- a/Modules/Learning/Supervised/include/otbSVMMachineLearningModel.h +++ b/Modules/Learning/Supervised/include/otbSVMMachineLearningModel.h @@ -51,6 +51,11 @@ public: itkNewMacro(Self); itkTypeMacro(SVMMachineLearningModel, MachineLearningModel); + /** Train the machine learning model */ + virtual void Train(); + /** Predict values using the model */ + virtual TargetSampleType Predict(const InputSampleType& input, ConfidenceValueType *quality=NULL) const; + /** Save the model to file */ virtual void Save(const std::string & filename, const std::string & name=""); @@ -126,11 +131,6 @@ protected: /** PrintSelf method */ void PrintSelf(std::ostream& os, itk::Indent indent) const; - /** Train the machine learning model */ - virtual void TrainClassification(); - /** Predict values using the model */ - virtual TargetSampleType PredictClassification(const InputSampleType& input, ConfidenceValueType *quality=NULL) const; - private: SVMMachineLearningModel(const Self &); //purposely not implemented void operator =(const Self&); //purposely not implemented diff --git a/Modules/Learning/Supervised/include/otbSVMMachineLearningModel.txx b/Modules/Learning/Supervised/include/otbSVMMachineLearningModel.txx index 064db060d1670146d4b618d94fa529017475758e..9d0b7d685948ebf67b070c6a16fcc9e6f760ea34 100644 --- a/Modules/Learning/Supervised/include/otbSVMMachineLearningModel.txx +++ b/Modules/Learning/Supervised/include/otbSVMMachineLearningModel.txx @@ -50,6 +50,7 @@ SVMMachineLearningModel<TInputValue,TOutputValue> m_OutputP(0) { this->m_ConfidenceIndex = true; + this->m_IsRegressionSupported = true; } @@ -64,8 +65,16 @@ SVMMachineLearningModel<TInputValue,TOutputValue> template <class TInputValue, class TOutputValue> void SVMMachineLearningModel<TInputValue,TOutputValue> -::TrainClassification() +::Train() { + // Check that the SVM type is compatible with the chosen mode (classif/regression) + if ( bool(m_SVMType == CvSVM::NU_SVR || m_SVMType == CvSVM::EPS_SVR) != this->m_RegressionMode) + { + itkGenericExceptionMacro("SVM type incompatible with chosen mode (classification or regression." + "SVM types for classification are C_SVC, NU_SVC, ONE_CLASS. " + "SVM types for regression are NU_SVR, EPS_SVR"); + } + //convert listsample to opencv matrix cv::Mat samples; otb::ListSampleToMat<InputListSampleType>(this->GetInputListSample(), samples); @@ -109,7 +118,7 @@ template <class TInputValue, class TOutputValue> typename SVMMachineLearningModel<TInputValue,TOutputValue> ::TargetSampleType SVMMachineLearningModel<TInputValue,TOutputValue> -::PredictClassification(const InputSampleType & input, ConfidenceValueType *quality) const +::Predict(const InputSampleType & input, ConfidenceValueType *quality) const { //convert listsample to Mat cv::Mat sample; @@ -135,10 +144,10 @@ void SVMMachineLearningModel<TInputValue,TOutputValue> ::Save(const std::string & filename, const std::string & name) { - if (name == "") - m_SVMModel->save(filename.c_str(), 0); - else - m_SVMModel->save(filename.c_str(), name.c_str()); + if (name == "") + m_SVMModel->save(filename.c_str(), 0); + else + m_SVMModel->save(filename.c_str(), name.c_str()); } template <class TInputValue, class TOutputValue> @@ -147,9 +156,9 @@ SVMMachineLearningModel<TInputValue,TOutputValue> ::Load(const std::string & filename, const std::string & name) { if (name == "") - m_SVMModel->load(filename.c_str(), 0); + m_SVMModel->load(filename.c_str(), 0); else - m_SVMModel->load(filename.c_str(), name.c_str()); + m_SVMModel->load(filename.c_str(), name.c_str()); } template <class TInputValue, class TOutputValue> @@ -157,29 +166,29 @@ bool SVMMachineLearningModel<TInputValue,TOutputValue> ::CanReadFile(const std::string & file) { - std::ifstream ifs; - ifs.open(file.c_str()); - - if(!ifs) - { - std::cerr<<"Could not read file "<<file<<std::endl; - return false; - } - - while (!ifs.eof()) - { - std::string line; - std::getline(ifs, line); - - //if (line.find(m_SVMModel->getName()) != std::string::npos) - if (line.find(CV_TYPE_NAME_ML_SVM) != std::string::npos) + std::ifstream ifs; + ifs.open(file.c_str()); + + if(!ifs) + { + std::cerr<<"Could not read file "<<file<<std::endl; + return false; + } + + while (!ifs.eof()) + { + std::string line; + std::getline(ifs, line); + + //if (line.find(m_SVMModel->getName()) != std::string::npos) + if (line.find(CV_TYPE_NAME_ML_SVM) != std::string::npos) { - //std::cout<<"Reading a "<<CV_TYPE_NAME_ML_SVM<<" model"<<std::endl; - return true; + //std::cout<<"Reading a "<<CV_TYPE_NAME_ML_SVM<<" model"<<std::endl; + return true; } - } - ifs.close(); - return false; + } + ifs.close(); + return false; } template <class TInputValue, class TOutputValue> diff --git a/Modules/Learning/Supervised/test/CMakeLists.txt b/Modules/Learning/Supervised/test/CMakeLists.txt index 7ffe8757b490c64081ffb6fe424a582d382d4df5..abca168f4f7794ea1a9133370c65555593b9bf19 100644 --- a/Modules/Learning/Supervised/test/CMakeLists.txt +++ b/Modules/Learning/Supervised/test/CMakeLists.txt @@ -7,6 +7,7 @@ otbConfusionMatrixMeasurementsTest.cxx otbMachineLearningModelCanRead.cxx otbTrainMachineLearningModel.cxx otbImageClassificationFilter.cxx +otbMachineLearningRegressionTests.cxx ) add_executable(otbSupervisedTestDriver ${OTBSupervisedTests}) diff --git a/Modules/Learning/Supervised/test/otbMachineLearningRegressionTests.cxx b/Modules/Learning/Supervised/test/otbMachineLearningRegressionTests.cxx new file mode 100644 index 0000000000000000000000000000000000000000..f54a9a96adc5a60f18f2a2411ff0e078ad5aba6d --- /dev/null +++ b/Modules/Learning/Supervised/test/otbMachineLearningRegressionTests.cxx @@ -0,0 +1,669 @@ +/*========================================================================= + + Program: ORFEO Toolbox + Language: C++ + Date: $Date$ + Version: $Revision$ + + + Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. + See OTBCopyright.txt for details. + + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + + =========================================================================*/ + +#include "otbConfigure.h" + +#include "itkMersenneTwisterRandomVariateGenerator.h" + +#ifdef OTB_USE_OPENCV +#include "otbNeuralNetworkMachineLearningModel.h" +#include "otbSVMMachineLearningModel.h" +#include "otbBoostMachineLearningModel.h" +#include "otbDecisionTreeMachineLearningModel.h" +#include "otbGradientBoostedTreeMachineLearningModel.h" +#include "otbKNearestNeighborsMachineLearningModel.h" +#include "otbRandomForestsMachineLearningModel.h" +#endif + +#ifdef OTB_USE_LIBSVM +#include "otbLibSVMMachineLearningModel.h" +#endif + +typedef float PrecisionType; +typedef otb::MachineLearningModel<PrecisionType,PrecisionType> MachineLearningModelRegressionType; +typedef MachineLearningModelRegressionType::InputValueType InputValueRegressionType; +typedef MachineLearningModelRegressionType::InputSampleType InputSampleRegressionType; +typedef MachineLearningModelRegressionType::InputListSampleType InputListSampleRegressionType; +typedef MachineLearningModelRegressionType::TargetValueType TargetValueRegressionType; +typedef MachineLearningModelRegressionType::TargetSampleType TargetSampleRegressionType; +typedef MachineLearningModelRegressionType::TargetListSampleType TargetListSampleRegressionType; +typedef itk::Statistics::MersenneTwisterRandomVariateGenerator RandomGeneratorType; + +const double epsilon = 0.1; + +typedef struct RegressionTestParamStruct +{ + double vMin; + double vMax; + size_t count; + double eps; +} RegressionTestParam; + +template <typename TPrecision> +struct LinearFunctionSampleGenerator +{ + typedef TPrecision PrecisionType; + LinearFunctionSampleGenerator(TPrecision a, TPrecision b) + : m_a(a), m_b(b), m_NbInputVars(1), m_NbOutputVars(1) { + m_isl = InputListSampleRegressionType::New(); + m_tsl = TargetListSampleRegressionType::New(); + }; + void GenerateSamples(TPrecision sMin, TPrecision sMax, size_t nbSamples) + { + m_isl->Clear(); + m_tsl->Clear(); + m_isl->SetMeasurementVectorSize(m_NbInputVars); + m_tsl->SetMeasurementVectorSize(m_NbOutputVars); + + RandomGeneratorType::Pointer randomGenerator = RandomGeneratorType::GetInstance(); + InputSampleRegressionType inputSample; + inputSample.SetSize(m_NbInputVars); + TargetSampleRegressionType outputSample; + + TPrecision sampleStep = (sMax-sMin)/nbSamples; + for(size_t i=0; i<nbSamples; ++i) + { + TPrecision x = randomGenerator->GetUniformVariate(0.0, 1.0) * static_cast<TPrecision>(nbSamples); + TPrecision inputValue = sMin+ x*sampleStep; + inputSample[0] = inputValue; + outputSample[0] = m_a*inputValue+m_b; + m_isl->PushBack(inputSample); + m_tsl->PushBack(outputSample); + } + } + + TPrecision m_a; + TPrecision m_b; + const size_t m_NbInputVars; + const size_t m_NbOutputVars; + InputListSampleRegressionType::Pointer m_isl; + TargetListSampleRegressionType::Pointer m_tsl; +}; + +template <typename TPrecision> +struct BilinearFunctionSampleGenerator +{ + typedef TPrecision PrecisionType; + BilinearFunctionSampleGenerator(TPrecision a, TPrecision b, TPrecision c) + : m_a(a), m_b(b), m_c(c), m_NbInputVars(2), m_NbOutputVars(1) { + m_isl = InputListSampleRegressionType::New(); + m_tsl = TargetListSampleRegressionType::New(); + }; + void GenerateSamples(TPrecision sMin, TPrecision sMax, size_t nbSamples) + { + m_isl->Clear(); + m_tsl->Clear(); + m_isl->SetMeasurementVectorSize(m_NbInputVars); + m_tsl->SetMeasurementVectorSize(m_NbOutputVars); + + RandomGeneratorType::Pointer randomGenerator = RandomGeneratorType::GetInstance(); + InputSampleRegressionType inputSample; + inputSample.SetSize(m_NbInputVars); + TargetSampleRegressionType outputSample; + + TPrecision sampleStep = (sMax-sMin)/nbSamples; + for(size_t i=0; i<nbSamples; ++i) + { + TPrecision x = randomGenerator->GetUniformVariate(0.0, 1.0) * static_cast<TPrecision>(nbSamples); + TPrecision inputValue1 = sMin+ x*sampleStep; + x = randomGenerator->GetUniformVariate(0.0, 1.0) * static_cast<TPrecision>(nbSamples); + TPrecision inputValue2 = sMin+ x*sampleStep; + inputSample[0] = inputValue1; + inputSample[1] = inputValue2; + outputSample[0] = m_a*inputValue1+m_b*inputValue2+m_c; + m_isl->PushBack(inputSample); + m_tsl->PushBack(outputSample); + } + } + + TPrecision m_a; + TPrecision m_b; + TPrecision m_c; + const size_t m_NbInputVars; + const size_t m_NbOutputVars; + InputListSampleRegressionType::Pointer m_isl; + TargetListSampleRegressionType::Pointer m_tsl; +}; + +template <typename TPrecision> +struct PolynomialFunctionSampleGenerator +{ + typedef TPrecision PrecisionType; + PolynomialFunctionSampleGenerator(std::vector<TPrecision> c) + : m_c(c), m_NbInputVars(1), m_NbOutputVars(1) { + m_isl = InputListSampleRegressionType::New(); + m_tsl = TargetListSampleRegressionType::New(); + }; + void GenerateSamples(TPrecision sMin, TPrecision sMax, size_t nbSamples) + { + m_isl->Clear(); + m_tsl->Clear(); + m_isl->SetMeasurementVectorSize(m_NbInputVars); + m_tsl->SetMeasurementVectorSize(m_NbOutputVars); + + RandomGeneratorType::Pointer randomGenerator = RandomGeneratorType::GetInstance(); + InputSampleRegressionType inputSample; + inputSample.SetSize(m_NbInputVars); + TargetSampleRegressionType outputSample; + + TPrecision sampleStep = (sMax-sMin)/nbSamples; + for(size_t i=0; i<nbSamples; ++i) + { + TPrecision x = randomGenerator->GetUniformVariate(0.0, 1.0) * static_cast<TPrecision>(nbSamples); + TPrecision inputValue = sMin+ x*sampleStep; + inputSample[0] = inputValue; + TPrecision y = 0.0; + for (unsigned int j=0; j<m_c.size() ; ++j) + { + y += m_c[j] * pow(static_cast<double>(inputValue), static_cast<double>(j)); + } + outputSample[0] = y; + m_isl->PushBack(inputSample); + m_tsl->PushBack(outputSample); + } + } + + std::vector<TPrecision> m_c; + const size_t m_NbInputVars; + const size_t m_NbOutputVars; + InputListSampleRegressionType::Pointer m_isl; + TargetListSampleRegressionType::Pointer m_tsl; +}; + +template <typename SampleGeneratorType, typename RegressionType> +int testRegression(SampleGeneratorType& sg, RegressionType& rgrsn, RegressionTestParam param) +{ + std::cout << "Generating training samples" << std::endl; + sg.GenerateSamples(param.vMin, param.vMax, param.count); + + rgrsn->SetInputListSample(sg.m_isl); + rgrsn->SetTargetListSample(sg.m_tsl); + std::cout << "Training" << std::endl; + rgrsn->Train(); + + std::cout << "Generate validation samples"<<std::endl; + sg.GenerateSamples(param.vMin, param.vMax, param.count); + + std::cout << "Validation" << std::endl; + //Check the prediction accuracy + typename InputListSampleRegressionType::Iterator sampleIt = sg.m_isl->Begin(); + typename TargetListSampleRegressionType::Iterator resultIt = sg.m_tsl->Begin(); + typename InputListSampleRegressionType::Iterator sampleLast = sg.m_isl->End(); + typename TargetListSampleRegressionType::Iterator resultLast = sg.m_tsl->End(); + typename SampleGeneratorType::PrecisionType rmse = 0.0; + while(sampleIt != sampleLast && resultIt != resultLast) + { + //typename SampleGeneratorType::PrecisionType invalue = sampleIt.GetMeasurementVector()[0]; + typename SampleGeneratorType::PrecisionType prediction = rgrsn->Predict(sampleIt.GetMeasurementVector())[0]; + typename SampleGeneratorType::PrecisionType expected = resultIt.GetMeasurementVector()[0]; + rmse += std::pow(prediction - expected, static_cast<PrecisionType>(2.0)); + ++sampleIt; + ++resultIt; + } + + rmse = sqrt( rmse / static_cast<double>(param.count) ); + std::cout << "RMSE = "<< rmse << std::endl; + if(rmse > param.eps) + { + std::cout << "Failed : RMSE above expected precision !" << std::endl; + return EXIT_FAILURE; + } + + return EXIT_SUCCESS; +} + +#ifdef OTB_USE_LIBSVM +MachineLearningModelRegressionType::Pointer getLibSVMRegressionModel() +{ + typedef otb::LibSVMMachineLearningModel<InputValueRegressionType, + TargetValueRegressionType> + libsvmType; + libsvmType::Pointer regression = libsvmType::New(); + regression->SetRegressionMode(true); + regression->SetSVMType(EPSILON_SVR); + regression->SetKernelType(RBF); + regression->SetEpsilon(1e-5); + regression->SetParameterOptimization(true); + return regression.GetPointer(); +} + +int otbLibSVMRegressionTests(int itkNotUsed(argc), + char * itkNotUsed(argv) []) +{ + int status = EXIT_SUCCESS; + int ret; + MachineLearningModelRegressionType::Pointer regression; + + RegressionTestParam param; + param.vMin = -0.5; + param.vMax = 0.5; + param.count = 200; + param.eps = 0.1; + + std::cout << "Testing regression on a linear monovariate function" << std::endl; + LinearFunctionSampleGenerator<PrecisionType> lfsg(2.0, 1.0); + regression = getLibSVMRegressionModel(); + ret = testRegression(lfsg,regression,param); + if (ret == EXIT_FAILURE) + { + status = EXIT_FAILURE; + } + std::cout << "Testing regression on a bilinear function" << std::endl; + BilinearFunctionSampleGenerator<PrecisionType> bfsg(2.0,-1.0,1.0); + regression = getLibSVMRegressionModel(); + ret = testRegression(bfsg,regression,param); + if (ret == EXIT_FAILURE) + { + status = EXIT_FAILURE; + } + std::cout << "Testing regression on a polynomial function" << std::endl; + std::vector<PrecisionType> coeffs; + coeffs.push_back(0.0); + coeffs.push_back(-1.0); + coeffs.push_back(0.0); + coeffs.push_back(4.0); + PolynomialFunctionSampleGenerator<PrecisionType> pfsg(coeffs); + regression = getLibSVMRegressionModel(); + ret = testRegression(pfsg,regression,param); + if (ret == EXIT_FAILURE) + { + status = EXIT_FAILURE; + } + return status; +} + +#endif + +#ifdef OTB_USE_OPENCV +MachineLearningModelRegressionType::Pointer getNeuralNetworkRegressionModel(unsigned int nbInputVar) +{ + typedef otb::NeuralNetworkMachineLearningModel<InputValueRegressionType, + TargetValueRegressionType> + NeuralNetworkType; + NeuralNetworkType::Pointer regression = NeuralNetworkType::New(); + + regression->SetRegressionMode(1); + regression->SetTrainMethod(CvANN_MLP_TrainParams::BACKPROP); + std::vector<unsigned int> layerSizes; + layerSizes.push_back(nbInputVar); + layerSizes.push_back(5); + layerSizes.push_back(1); + regression->SetLayerSizes(layerSizes); + regression->SetActivateFunction(CvANN_MLP::SIGMOID_SYM); + regression->SetAlpha(1.0); + regression->SetBeta(1.0); + regression->SetBackPropDWScale(0.1); + regression->SetBackPropMomentScale(0.1); + regression->SetRegPropDW0(0.1); + regression->SetRegPropDWMin(1e-7); + regression->SetTermCriteriaType(CV_TERMCRIT_EPS); + regression->SetEpsilon(1e-5); + regression->SetMaxIter(1e4); + return regression.GetPointer(); +} + +int otbNeuralNetworkRegressionTests(int itkNotUsed(argc), + char * itkNotUsed(argv) []) +{ + int status = EXIT_SUCCESS; + int ret; + MachineLearningModelRegressionType::Pointer regression; + + RegressionTestParam param; + param.vMin = -0.5; + param.vMax = 0.5; + param.count = 20000; + param.eps = 0.1; + + std::cout << "Testing regression on a linear monovariate function" << std::endl; + LinearFunctionSampleGenerator<PrecisionType> lfsg(2.0, 1.0); + regression = getNeuralNetworkRegressionModel(1); + ret = testRegression(lfsg,regression,param); + if (ret == EXIT_FAILURE) + { + status = EXIT_FAILURE; + } + std::cout << "Testing regression on a bilinear function" << std::endl; + BilinearFunctionSampleGenerator<PrecisionType> bfsg(2.0,-1.0,1.0); + regression = getNeuralNetworkRegressionModel(2); + ret = testRegression(bfsg,regression,param); + if (ret == EXIT_FAILURE) + { + status = EXIT_FAILURE; + } + std::cout << "Testing regression on a polynomial function" << std::endl; + std::vector<PrecisionType> coeffs; + coeffs.push_back(0.0); + coeffs.push_back(-1.0); + coeffs.push_back(0.0); + coeffs.push_back(4.0); + PolynomialFunctionSampleGenerator<PrecisionType> pfsg(coeffs); + regression = getNeuralNetworkRegressionModel(1); + ret = testRegression(pfsg,regression,param); + if (ret == EXIT_FAILURE) + { + status = EXIT_FAILURE; + } + return status; +} + + +MachineLearningModelRegressionType::Pointer getSVMRegressionModel() +{ + typedef otb::SVMMachineLearningModel<InputValueRegressionType, + TargetValueRegressionType> + SVMType; + SVMType::Pointer regression = SVMType::New(); + + regression->SetRegressionMode(1); + regression->SetSVMType(CvSVM::NU_SVR); + regression->SetNu(0.5); + regression->SetKernelType(CvSVM::RBF); + regression->SetTermCriteriaType(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS); + regression->SetMaxIter(100000); + regression->SetEpsilon(1e-5); + regression->SetParameterOptimization(true); + return regression.GetPointer(); +} + +int otbSVMRegressionTests(int itkNotUsed(argc), + char * itkNotUsed(argv) []) +{ + int status = EXIT_SUCCESS; + int ret; + MachineLearningModelRegressionType::Pointer regression; + + RegressionTestParam param; + param.vMin = -0.5; + param.vMax = 0.5; + param.count = 200; + param.eps = 0.1; + + std::cout << "Testing regression on a linear monovariate function" << std::endl; + LinearFunctionSampleGenerator<PrecisionType> lfsg(2.0, 1.0); + regression = getSVMRegressionModel(); + ret = testRegression(lfsg,regression,param); + if (ret == EXIT_FAILURE) + { + status = EXIT_FAILURE; + } + std::cout << "Testing regression on a bilinear function" << std::endl; + BilinearFunctionSampleGenerator<PrecisionType> bfsg(2.0,-1.0,1.0); + regression = getSVMRegressionModel(); + ret = testRegression(bfsg,regression,param); + if (ret == EXIT_FAILURE) + { + status = EXIT_FAILURE; + } + std::cout << "Testing regression on a polynomial function" << std::endl; + std::vector<PrecisionType> coeffs; + coeffs.push_back(0.0); + coeffs.push_back(-1.0); + coeffs.push_back(0.0); + coeffs.push_back(4.0); + PolynomialFunctionSampleGenerator<PrecisionType> pfsg(coeffs); + regression = getSVMRegressionModel(); + ret = testRegression(pfsg,regression,param); + if (ret == EXIT_FAILURE) + { + status = EXIT_FAILURE; + } + return status; +} + + +MachineLearningModelRegressionType::Pointer getDecisionTreeRegressionModel() +{ + typedef otb::DecisionTreeMachineLearningModel<InputValueRegressionType, + TargetValueRegressionType> + DTreeType; + DTreeType::Pointer regression = DTreeType::New(); + regression->SetRegressionMode(true); + regression->SetRegressionAccuracy(0.005); + return regression.GetPointer(); +} + +int otbDecisionTreeRegressionTests(int itkNotUsed(argc), + char * itkNotUsed(argv) []) +{ + int status = EXIT_SUCCESS; + int ret; + MachineLearningModelRegressionType::Pointer regression; + + RegressionTestParam param; + param.vMin = -0.5; + param.vMax = 0.5; + param.count = 200; + param.eps = 0.1; + + std::cout << "Testing regression on a linear monovariate function" << std::endl; + LinearFunctionSampleGenerator<PrecisionType> lfsg(2.0, 1.0); + regression = getDecisionTreeRegressionModel(); + ret = testRegression(lfsg,regression,param); + if (ret == EXIT_FAILURE) + { + status = EXIT_FAILURE; + } + std::cout << "Testing regression on a bilinear function" << std::endl; + BilinearFunctionSampleGenerator<PrecisionType> bfsg(2.0,-1.0,1.0); + regression = getDecisionTreeRegressionModel(); + // increase the number of training samples for bilinear function + param.count = 1000; + ret = testRegression(bfsg,regression,param); + if (ret == EXIT_FAILURE) + { + status = EXIT_FAILURE; + } + std::cout << "Testing regression on a polynomial function" << std::endl; + std::vector<PrecisionType> coeffs; + coeffs.push_back(0.0); + coeffs.push_back(-1.0); + coeffs.push_back(0.0); + coeffs.push_back(4.0); + PolynomialFunctionSampleGenerator<PrecisionType> pfsg(coeffs); + param.count = 200; + regression = getDecisionTreeRegressionModel(); + ret = testRegression(pfsg,regression,param); + if (ret == EXIT_FAILURE) + { + status = EXIT_FAILURE; + } + return status; +} + + +MachineLearningModelRegressionType::Pointer getGradientBoostedTreeRegressionModel() +{ + typedef otb::GradientBoostedTreeMachineLearningModel<InputValueRegressionType, + TargetValueRegressionType> + GBTreeType; + GBTreeType::Pointer regression = GBTreeType::New(); + regression->SetRegressionMode(true); + regression->SetShrinkage(0.1); + regression->SetSubSamplePortion(0.8); + regression->SetLossFunctionType(CvGBTrees::SQUARED_LOSS); + return regression.GetPointer(); +} + +int otbGradientBoostedTreeRegressionTests(int itkNotUsed(argc), + char * itkNotUsed(argv) []) +{ + int status = EXIT_SUCCESS; + int ret; + MachineLearningModelRegressionType::Pointer regression; + + RegressionTestParam param; + param.vMin = -0.5; + param.vMax = 0.5; + param.count = 200; + param.eps = 0.1; + + std::cout << "Testing regression on a linear monovariate function" << std::endl; + LinearFunctionSampleGenerator<PrecisionType> lfsg(2.0, 1.0); + regression = getGradientBoostedTreeRegressionModel(); + ret = testRegression(lfsg,regression,param); + if (ret == EXIT_FAILURE) + { + status = EXIT_FAILURE; + } + std::cout << "Testing regression on a bilinear function" << std::endl; + BilinearFunctionSampleGenerator<PrecisionType> bfsg(2.0,-1.0,1.0); + // increase number of training samples for bilinear function + param.count = 1000; + regression = getGradientBoostedTreeRegressionModel(); + ret = testRegression(bfsg,regression,param); + if (ret == EXIT_FAILURE) + { + status = EXIT_FAILURE; + } + std::cout << "Testing regression on a polynomial function" << std::endl; + std::vector<PrecisionType> coeffs; + coeffs.push_back(0.0); + coeffs.push_back(-1.0); + coeffs.push_back(0.0); + coeffs.push_back(4.0); + PolynomialFunctionSampleGenerator<PrecisionType> pfsg(coeffs); + param.count = 200; + regression = getGradientBoostedTreeRegressionModel(); + ret = testRegression(pfsg,regression,param); + if (ret == EXIT_FAILURE) + { + status = EXIT_FAILURE; + } + return status; +} + + +MachineLearningModelRegressionType::Pointer getKNearestNeighborsRegressionModel() +{ + typedef otb::KNearestNeighborsMachineLearningModel<InputValueRegressionType, + TargetValueRegressionType> + KNNType; + KNNType::Pointer regression = KNNType::New(); + regression->SetRegressionMode(true); + regression->SetK(5); + regression->SetDecisionRule(KNNType::KNN_MEDIAN); + return regression.GetPointer(); +} + +int otbKNearestNeighborsRegressionTests(int itkNotUsed(argc), + char * itkNotUsed(argv) []) +{ + int status = EXIT_SUCCESS; + int ret; + MachineLearningModelRegressionType::Pointer regression; + + RegressionTestParam param; + param.vMin = -0.5; + param.vMax = 0.5; + param.count = 200; + param.eps = 0.1; + + std::cout << "Testing regression on a linear monovariate function" << std::endl; + LinearFunctionSampleGenerator<PrecisionType> lfsg(2.0, 1.0); + regression = getKNearestNeighborsRegressionModel(); + ret = testRegression(lfsg,regression,param); + if (ret == EXIT_FAILURE) + { + status = EXIT_FAILURE; + } + std::cout << "Testing regression on a bilinear function" << std::endl; + BilinearFunctionSampleGenerator<PrecisionType> bfsg(2.0,-1.0,1.0); + regression = getKNearestNeighborsRegressionModel(); + ret = testRegression(bfsg,regression,param); + if (ret == EXIT_FAILURE) + { + status = EXIT_FAILURE; + } + std::cout << "Testing regression on a polynomial function" << std::endl; + std::vector<PrecisionType> coeffs; + coeffs.push_back(0.0); + coeffs.push_back(-1.0); + coeffs.push_back(0.0); + coeffs.push_back(4.0); + PolynomialFunctionSampleGenerator<PrecisionType> pfsg(coeffs); + regression = getKNearestNeighborsRegressionModel(); + ret = testRegression(pfsg,regression,param); + if (ret == EXIT_FAILURE) + { + status = EXIT_FAILURE; + } + return status; +} + + +MachineLearningModelRegressionType::Pointer getRandomForestsRegressionModel() +{ + typedef otb::RandomForestsMachineLearningModel<InputValueRegressionType, + TargetValueRegressionType> + RFType; + RFType::Pointer regression = RFType::New(); + regression->SetRegressionMode(true); + regression->SetRegressionAccuracy(0.005); + return regression.GetPointer(); +} + + +int otbRandomForestsRegressionTests(int itkNotUsed(argc), + char * itkNotUsed(argv) []) +{ + int status = EXIT_SUCCESS; + int ret; + MachineLearningModelRegressionType::Pointer regression; + + RegressionTestParam param; + param.vMin = -0.5; + param.vMax = 0.5; + param.count = 200; + param.eps = 0.1; + + std::cout << "Testing regression on a linear monovariate function" << std::endl; + LinearFunctionSampleGenerator<PrecisionType> lfsg(2.0, 1.0); + regression = getRandomForestsRegressionModel(); + ret = testRegression(lfsg,regression,param); + if (ret == EXIT_FAILURE) + { + status = EXIT_FAILURE; + } + std::cout << "Testing regression on a bilinear function" << std::endl; + BilinearFunctionSampleGenerator<PrecisionType> bfsg(2.0,-1.0,1.0); + // increase number of training samples for bilinear function + param.count = 1000; + regression = getRandomForestsRegressionModel(); + ret = testRegression(bfsg,regression,param); + if (ret == EXIT_FAILURE) + { + status = EXIT_FAILURE; + } + std::cout << "Testing regression on a polynomial function" << std::endl; + std::vector<PrecisionType> coeffs; + coeffs.push_back(0.0); + coeffs.push_back(-1.0); + coeffs.push_back(0.0); + coeffs.push_back(4.0); + PolynomialFunctionSampleGenerator<PrecisionType> pfsg(coeffs); + param.count = 200; + regression = getRandomForestsRegressionModel(); + ret = testRegression(pfsg,regression,param); + if (ret == EXIT_FAILURE) + { + status = EXIT_FAILURE; + } + return status; +} +#endif diff --git a/Modules/Learning/Supervised/test/otbSupervisedTestDriver.cxx b/Modules/Learning/Supervised/test/otbSupervisedTestDriver.cxx index e498bd082ed53ec2862ea5b99913b6b7de897b38..2bf373c87f9f0579df333951b83ae818739d25c2 100644 --- a/Modules/Learning/Supervised/test/otbSupervisedTestDriver.cxx +++ b/Modules/Learning/Supervised/test/otbSupervisedTestDriver.cxx @@ -28,6 +28,7 @@ void RegisterTests() #ifdef OTB_USE_LIBSVM REGISTER_TEST(otbLibSVMMachineLearningModelNew); REGISTER_TEST(otbLibSVMMachineLearningModel); + REGISTER_TEST(otbLibSVMRegressionTests); #endif #ifdef OTB_USE_OPENCV @@ -48,8 +49,14 @@ void RegisterTests() REGISTER_TEST(otbDecisionTreeMachineLearningModel); REGISTER_TEST(otbGradientBoostedTreeMachineLearningModelNew); REGISTER_TEST(otbGradientBoostedTreeMachineLearningModel); - #endif + REGISTER_TEST(otbNeuralNetworkRegressionTests); + REGISTER_TEST(otbSVMRegressionTests); + REGISTER_TEST(otbDecisionTreeRegressionTests); + REGISTER_TEST(otbGradientBoostedTreeRegressionTests); + REGISTER_TEST(otbKNearestNeighborsRegressionTests); + REGISTER_TEST(otbRandomForestsRegressionTests); +#endif - REGISTER_TEST(otbImageClassificationFilterNew); + REGISTER_TEST(otbImageClassificationFilterNew); REGISTER_TEST(otbImageClassificationFilter); } diff --git a/Modules/Learning/Supervised/test/otbTrainMachineLearningModel.cxx b/Modules/Learning/Supervised/test/otbTrainMachineLearningModel.cxx index 39a2a2f7628c98aca338093af70d1d75d35badee..64d69a120a2dd2cd8e3418ef248ff8c12324f6ed 100644 --- a/Modules/Learning/Supervised/test/otbTrainMachineLearningModel.cxx +++ b/Modules/Learning/Supervised/test/otbTrainMachineLearningModel.cxx @@ -381,20 +381,12 @@ int otbSVMMachineLearningRegressionModel(int argc, char * argv[]) SVMType::Pointer classifier = SVMType::New(); //Init SVM type in regression mode - //Available mode for regression in openCV are eps_svr and nu_svr + classifier->SetRegressionMode(1); classifier->SetSVMType(CvSVM::EPS_SVR); - //classifier->SetSVMType(CvSVM::NU_SVR); - - //P should be >0. Increasing value give better result. Need to investigate why. classifier->SetP(10); - - //IN case you're using nu_svr you should set nu to a positive value between 0 - //and 1. - //classifier->SetNu(0.9); - - //Use RBF kernel.Don't know what is recommended in case of svm regression classifier->SetKernelType(CvSVM::RBF); + classifier->SetInputListSample(samples); classifier->SetTargetListSample(labels); classifier->Train(); @@ -432,6 +424,7 @@ int otbSVMMachineLearningRegressionModel(int argc, char * argv[]) } else { + std::cout << age << "\t" << predicted->GetMeasurementVector(0)[0] << "\n"; return EXIT_FAILURE; } } @@ -447,9 +440,9 @@ int otbKNearestNeighborsMachineLearningModel(int argc, char * argv[]) { if (argc != 3 ) { - std::cout<<"Wrong number of arguments "<<std::endl; - std::cout<<"Usage : sample file, output file"<<std::endl; - return EXIT_FAILURE; + std::cout<<"Wrong number of arguments "<<std::endl; + std::cout<<"Usage : sample file, output file"<<std::endl; + return EXIT_FAILURE; } typedef otb::KNearestNeighborsMachineLearningModel<InputValueType,TargetValueType> KNearestNeighborsType; @@ -528,11 +521,11 @@ int otbRandomForestsMachineLearningModelNew(int itkNotUsed(argc), char * itkNotU int otbRandomForestsMachineLearningModel(int argc, char * argv[]) { if (argc != 3 ) - { + { std::cout<<"Wrong number of arguments "<<std::endl; std::cout<<"Usage : sample file, output file "<<std::endl; return EXIT_FAILURE; - } + } typedef otb::RandomForestsMachineLearningModel<InputValueType,TargetValueType> RandomForestType; InputListSampleType::Pointer samples = InputListSampleType::New(); @@ -620,9 +613,9 @@ int otbBoostMachineLearningModel(int argc, char * argv[]) { if (argc != 3 ) { - std::cout<<"Wrong number of arguments "<<std::endl; - std::cout<<"Usage : sample file, output file "<<std::endl; - return EXIT_FAILURE; + std::cout<<"Wrong number of arguments "<<std::endl; + std::cout<<"Usage : sample file, output file "<<std::endl; + return EXIT_FAILURE; } typedef otb::BoostMachineLearningModel<InputValueType, TargetValueType> BoostType; diff --git a/Modules/Learning/Supervised/test/tests-libsvm.cmake b/Modules/Learning/Supervised/test/tests-libsvm.cmake index 04764df301cb2b2fa7f1951d023495ddf93b5b4b..30dc7eec130d6baa87a8fd37296ce7501548dc7c 100644 --- a/Modules/Learning/Supervised/test/tests-libsvm.cmake +++ b/Modules/Learning/Supervised/test/tests-libsvm.cmake @@ -22,3 +22,7 @@ otb_add_test(NAME leTuLibSVMMachineLearningModelCanRead COMMAND otbSupervisedTes ${TEMP}/libsvm_model.txt ) set_property(TEST leTuLibSVMMachineLearningModelCanRead PROPERTY DEPENDS leTvLibSVMMachineLearningModel) + +otb_add_test(NAME leTvLibSVMMachineLearningModelReg COMMAND otbSupervisedTestDriver + otbLibSVMRegressionTests + ) diff --git a/Modules/Learning/Supervised/test/tests-opencv.cmake b/Modules/Learning/Supervised/test/tests-opencv.cmake index 55855a4aa912a3b3497bb9b8d9f2bc69d6dccea4..3be269fe8d8e7f17f85f9e4d11c944feb2dc3e02 100644 --- a/Modules/Learning/Supervised/test/tests-opencv.cmake +++ b/Modules/Learning/Supervised/test/tests-opencv.cmake @@ -10,6 +10,32 @@ otb_add_test(NAME leTvANNMachineLearningModel COMMAND otbSupervisedTestDriver ${TEMP}/ann_model.txt ) +# ------------------ Regression tests -------------------- +otb_add_test(NAME leTvANNMachineLearningModelReg COMMAND otbSupervisedTestDriver + otbNeuralNetworkRegressionTests + ) + +otb_add_test(NAME leTvSVMMachineLearningModelReg COMMAND otbSupervisedTestDriver + otbSVMRegressionTests + ) + +otb_add_test(NAME leTvDecisionTreeMachineLearningModelReg COMMAND otbSupervisedTestDriver + otbDecisionTreeRegressionTests + ) + +otb_add_test(NAME leTvGradientBoostedTreeMachineLearningModelReg COMMAND otbSupervisedTestDriver + otbGradientBoostedTreeRegressionTests + ) + +otb_add_test(NAME leTvKNearestNeighborsMachineLearningModelReg COMMAND otbSupervisedTestDriver + otbKNearestNeighborsRegressionTests + ) + +otb_add_test(NAME leTvRandomForestsMachineLearningModelReg COMMAND otbSupervisedTestDriver + otbRandomForestsRegressionTests + ) +# -------------------------------------------------------------- + otb_add_test(NAME leTuSVMMachineLearningModelNew COMMAND otbSupervisedTestDriver otbSVMMachineLearningModelNew) diff --git a/Modules/Segmentation/Conversion/test/otbOGRDataSourceToLabelImageFilter.cxx b/Modules/Segmentation/Conversion/test/otbOGRDataSourceToLabelImageFilter.cxx index 681dbc61f6632d6c9c2bec7629c840fcdf021501..745f1b01c173852e09de0fccabe9adca795f0ffb 100644 --- a/Modules/Segmentation/Conversion/test/otbOGRDataSourceToLabelImageFilter.cxx +++ b/Modules/Segmentation/Conversion/test/otbOGRDataSourceToLabelImageFilter.cxx @@ -9,8 +9,6 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom; Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Segmentation/Conversion/test/otbPolygonizationRasterizationTest.cxx b/Modules/Segmentation/Conversion/test/otbPolygonizationRasterizationTest.cxx index df6921448a8e451d49df493344143ac7f2416e32..abb25628684c026b0a46d7159d616c708d4bde15 100644 --- a/Modules/Segmentation/Conversion/test/otbPolygonizationRasterizationTest.cxx +++ b/Modules/Segmentation/Conversion/test/otbPolygonizationRasterizationTest.cxx @@ -9,8 +9,6 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom; Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Segmentation/Conversion/test/otbVectorDataRasterizeFilter.cxx b/Modules/Segmentation/Conversion/test/otbVectorDataRasterizeFilter.cxx index 2e073dd958d0911abb49bfab8f73206e9c4bc2af..e9032ae96fbec36579f503d863cb68725287c528 100644 --- a/Modules/Segmentation/Conversion/test/otbVectorDataRasterizeFilter.cxx +++ b/Modules/Segmentation/Conversion/test/otbVectorDataRasterizeFilter.cxx @@ -9,8 +9,6 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom; Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Segmentation/Conversion/test/otbVectorDataToLabelImageFilter.cxx b/Modules/Segmentation/Conversion/test/otbVectorDataToLabelImageFilter.cxx index 04619bd5a928dc2d70f5373dc5872c36f6ea7fd6..229b5b622f7681c485f51b1a81e719ae2511d8ba 100644 --- a/Modules/Segmentation/Conversion/test/otbVectorDataToLabelImageFilter.cxx +++ b/Modules/Segmentation/Conversion/test/otbVectorDataToLabelImageFilter.cxx @@ -9,8 +9,6 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom; Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/Modules/Segmentation/Conversion/test/otbVectorDataToLabelImageFilterWithoutReader.cxx b/Modules/Segmentation/Conversion/test/otbVectorDataToLabelImageFilterWithoutReader.cxx index 4b00e88ba2ab3f103d9d629c5a064bd2c9da3e9c..8dd0bc3d5af301881a4f583a82fc306b82611a95 100644 --- a/Modules/Segmentation/Conversion/test/otbVectorDataToLabelImageFilterWithoutReader.cxx +++ b/Modules/Segmentation/Conversion/test/otbVectorDataToLabelImageFilterWithoutReader.cxx @@ -9,8 +9,6 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom; Telecom Bretagne. All rights reserved. - See ITCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/SuperBuild/CMake/External_gdal.cmake b/SuperBuild/CMake/External_gdal.cmake index a76075af1adfc2996686a606df020c750f99f151..61ce0d3b757c83b8f1755191f190832a650110ec 100644 --- a/SuperBuild/CMake/External_gdal.cmake +++ b/SuperBuild/CMake/External_gdal.cmake @@ -51,9 +51,9 @@ else() INSTALL_DIR ${SB_INSTALL_PREFIX} DOWNLOAD_DIR ${DOWNLOAD_LOCATION} DEPENDS ${${proj}_DEPENDENCIES} - UPDATE_COMMAND ${CMAKE_COMMAND} -E copy_directory ${GDAL_SB_SRC} ${GDAL_SB_BUILD_DIR} - PATCH_COMMAND ${CMAKE_COMMAND} -E touch ${GDAL_SB_SRC}/config.rpath - CONFIGURE_COMMAND + UPDATE_COMMAND ${CMAKE_COMMAND} -E copy_directory ${GDAL_SB_SRC} ${GDAL_SB_BUILD_DIR} + PATCH_COMMAND ${CMAKE_COMMAND} -E touch ${GDAL_SB_SRC}/config.rpath COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_SOURCE_DIR}/patches/GDAL/GNUmakefile ${GDAL_SB_SRC}/swig/python/GNUmakefile + CONFIGURE_COMMAND # use 'env' because CTest launcher doesn't perform shell interpretation ${SB_ENV_CONFIGURE_CMD} ${GDAL_SB_BUILD_DIR}/configure @@ -86,7 +86,7 @@ else() INSTALL_DIR ${SB_INSTALL_PREFIX} DOWNLOAD_DIR ${DOWNLOAD_LOCATION} DEPENDS ${${proj}_DEPENDENCIES} - PATCH_COMMAND ${CMAKE_COMMAND} -E copy_directory ${GDAL_SB_SRC} ${GDAL_SB_BUILD_DIR} + PATCH_COMMAND ${CMAKE_COMMAND} -E copy_directory ${GDAL_SB_SRC} ${GDAL_SB_BUILD_DIR} COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_SOURCE_DIR}/patches/GDAL/GNUmakefile ${GDAL_SB_SRC}/swig/python/GNUmakefile CONFIGURE_COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_SOURCE_DIR}/patches/${proj}/ogrsqlitevirtualogr.cpp ${GDAL_SB_BUILD_DIR}/ogr/ogrsf_frmts/sqlite/ogrsqlitevirtualogr.cpp BUILD_COMMAND nmake /f ${GDAL_SB_BUILD_DIR}/makefile.vc MSVC_VER=${MSVC_VERSION} EXT_NMAKE_OPT=${CMAKE_BINARY_DIR}/nmake_gdal_extra.opt diff --git a/SuperBuild/patches/GDAL/GNUmakefile b/SuperBuild/patches/GDAL/GNUmakefile new file mode 100644 index 0000000000000000000000000000000000000000..71f029d8726dbf9cda8644471ceee789f1e279cf --- /dev/null +++ b/SuperBuild/patches/GDAL/GNUmakefile @@ -0,0 +1,95 @@ + + +include ../../GDALmake.opt + +ifndef PYTHON + PYTHON=python +endif + +all: build + +BINDING = python +include ../SWIGmake.base + +PACKAGE_DIR=osgeo +SWIGOUTPUTDIR=extensions/ + +SCRIPTS = `ls ./scripts` +PY_COMMANDS = epsg_tr.py gdalchksum.py gdal2xyz.py gcps2wld.py \ + gdalimport.py gdal_merge.py pct2rgb.py rgb2pct.py \ + gcps2vec.py +PY_MODULES = ${PACKAGE_DIR}/gdal.py ${PACKAGE_DIR}/ogr.py ${PACKAGE_DIR}/osr.py ${PACKAGE_DIR}/gdalconst.py ${PACKAGE_DIR}/gdal_array.py + +clean: + -rm -f ${PACKAGE_DIR}/*.pyc + -rm -rf build + -rm -f *.pyc + -rm -rf *.egg-info + -rm -f *.so ./osgeo/*.so + -rm -rf dist + +SWIGARGS += -outdir "${PACKAGE_DIR}" + + +veryclean: clean + -rm -f ${WRAPPERS} ${PY_MODULES} + -rm -f ${SWIGOUTPUTDIR}/gdal_wrap.cpp + -rm -f ${SWIGOUTPUTDIR}/gdalconst_wrap.c + -rm -f ${SWIGOUTPUTDIR}/ogr_wrap.cpp + -rm -f ${SWIGOUTPUTDIR}/osr_wrap.cpp + -rm -f ${SWIGOUTPUTDIR}/gdal_array_wrap.cpp + +gdal_wrap.cpp: ../include/python/gdal_python.i + +ogr_wrap.cpp: ../include/python/ogr_python.i + +osr_wrap.cpp: ../include/python/osr_python.i + +gdal_array_wrap.cpp: ../include/gdal_array.i ../include/python/typemaps_python.i + $(SWIG) $(SWIGARGS) $(SWIGDEFINES) -I$(GDAL_ROOT) -c++ -$(BINDING) -o $(SWIGOUTPUTDIR)$@ gdal_array.i + +# A few hacks (cat, mv) : the first one for SWIG < 1.3.36 and the second one for SWIG <= 1.3.39 python 3.X on 64bit platforms +# The python3.2.patch is from https://sourceforge.net/tracker/?func=detail&aid=3057804&group_id=1645&atid=101645 +# and is no longer necessary with swig 2.0.4 +generate: ${WRAPPERS} gdal_array_wrap.cpp + for i in gdal_wrap.cpp gdalconst_wrap.c ogr_wrap.cpp osr_wrap.cpp gdal_array_wrap.cpp; do sed "s/PyErr_Format(PyExc_RuntimeError, mesg)/PyErr_SetString(PyExc_RuntimeError, mesg)/" ${SWIGOUTPUTDIR}/$$i | sed "s/int len;/Py_ssize_t len;/" > ${SWIGOUTPUTDIR}/$$i.tmp; mv -f ${SWIGOUTPUTDIR}/$$i.tmp ${SWIGOUTPUTDIR}/$$i; done + -grep "1\.3\.40" extensions/gdal_wrap.cpp >/dev/null && patch -p0 < python3.2.patch + -grep "1\.3\.40" extensions/gdal_wrap.cpp >/dev/null && cat python3.2.patch | sed "s/gdal_wrap/ogr_wrap/" | patch -p0 + -grep "1\.3\.40" extensions/gdal_wrap.cpp >/dev/null && cat python3.2.patch | sed "s/gdal_wrap/osr_wrap/" | patch -p0 + -grep "1\.3\.40" extensions/gdal_wrap.cpp >/dev/null && cat python3.2.patch | sed "s/gdal_wrap\.cpp/gdalconst_wrap\.c/" | patch -p0 + -grep "1\.3\.40" extensions/gdal_wrap.cpp >/dev/null && cat python3.2.patch | sed "s/gdal_wrap/gdal_array_wrap/" | patch -p0 + +build: + $(PYTHON) setup.py build + +egg: + $(PYTHON) setup.py bdist_egg + +install: + +ifeq ($(PY_HAVE_SETUPTOOLS),1) + $(PYTHON) setup.py install --prefix=$(DESTDIR)$(prefix) --install-purelib=$(prefix)/lib --install-scripts=$(prefix)/bin --install-platlib=$(prefix)/lib +else + $(PYTHON) setup.py install --prefix=$(DESTDIR)$(prefix) +endif + + for f in $(SCRIPTS) ; do $(INSTALL) ./scripts/$$f $(DESTDIR)$(INST_BIN) ; done + +docs: + $(PYTHON) ../include/python/docs/doxy2swig.py ../../ogr/xml/ogrlayer_8cpp.xml ../include/python/docs/ogr_layer_docs.i OGRLayerShadow OGR_L_ + + $(PYTHON) ../include/python/docs/doxy2swig.py ../../ogr/xml/ogrgeometry_8cpp.xml ../include/python/docs/ogr_geometry_docs.i OGRGeometryShadow OGR_G_ + + $(PYTHON) ../include/python/docs/doxy2swig.py ../../ogr/xml/ogrdatasource_8cpp.xml ../include/python/docs/ogr_datasource_docs.i OGRDataSourceShadow OGR_DS_ + + + $(PYTHON) ../include/python/docs/doxy2swig.py ../../ogr/xml/ogrsfdriver_8cpp.xml ../include/python/docs/ogr_driver_docs.i OGRDriverShadow OGR_Dr_ + + $(PYTHON) ../include/python/docs/doxy2swig.py ../../ogr/xml/ogrfeature_8cpp.xml ../include/python/docs/ogr_feature_docs.i OGRFeatureShadow OGR_F_ + + $(PYTHON) ../include/python/docs/doxy2swig.py ../../ogr/xml/ogrfeaturedefn_8cpp.xml ../include/python/docs/ogr_featuredef_docs.i OGRFeatureDefnShadow OGR_FD_ + + $(PYTHON) ../include/python/docs/doxy2swig.py ../../ogr/xml/ogrfielddefn_8cpp.xml ../include/python/docs/ogr_fielddef_docs.i OGRFieldDefnShadow OGR_Fld_ + +epydoc: generate + epydoc --config epydoc.conf diff --git a/Utilities/Maintenance/SuperbuildDownloadList.sh b/Utilities/Maintenance/SuperbuildDownloadList.sh index e0cc7033b1933fc5d8943747184a249d51d01f5c..2cb32210b12d8d28a5c985047956271ad4e970e2 100755 --- a/Utilities/Maintenance/SuperbuildDownloadList.sh +++ b/Utilities/Maintenance/SuperbuildDownloadList.sh @@ -1,2 +1,62 @@ #/bin/bash -grep -h -E "^[^#]*\"https?://.*(\.tar\.gz|\.tar\.bz2|\.tgz|\.tar\.xz|\.zip|export=download).*\"" ../../SuperBuild/CMake/*.cmake | grep -o -E "https?://[^\"]*" | sed "s/\/download$//" | sort | uniq + +if [ $# -eq 2 ]; then +DOWNLOAD_DIR=$(readlink -f $1) +OUTPUT_DIR=$(readlink -f $2) +else +echo 'Usage: '$0' <download_directory> <archive_output_directory>' +exit 1 +fi + +SB_CMAKE_DIR_REL=$(dirname $0)/../../SuperBuild/CMake +SB_CMAKE_DIR=$(readlink -f ${SB_CMAKE_DIR_REL}) + +DOWNLOAD_LIST=$(grep -h -E "^[^#]*\"https?://.*(\.tar\.gz|\.tar\.bz2|\.tgz|\.tar\.xz|\.zip|export=download).*\"" ${SB_CMAKE_DIR}/*.cmake | grep -o -E "https?://[^\"]*" | sed "s/\/\(download\)\?$//" | sort | uniq) + +DOWNLOAD_NAMES= + +mkdir -p ${DOWNLOAD_DIR} +cd ${DOWNLOAD_DIR} + +echo "Start downloads..." + +for url in ${DOWNLOAD_LIST}; do + # clean log file + echo "" >download.log + + file_name=$(echo "${url}" | grep -o -E "[^\/]+$") + docs_google=$(echo "${file_name}" | grep -F "export=download") + if [ "${docs_google}" = "" ]; then + echo "Download ${file_name}..." + wget -N ${url} -o download.log + else + # look into the original file for a valid download name + file_name=$(grep -h -A 3 -B 3 -F "${url}" ${SB_CMAKE_DIR}/*.cmake | grep -E "^[^#]*DOWNLOAD_NAME" | grep -o -E "[^ ]*\.(tar\.gz|tar\.bz2|tar\.xz|zip)" | uniq) + if [ -z "$file_name" ]; then + echo "Can't find correct filename for url ${url} : skip download" + else + echo "Download ${file_name}..." + wget -O ${file_name} ${url} -o download.log + fi + fi + + download_errors=$(grep "ERROR" download.log) + if [ "$download_errors" != "" ]; then + echo "=== Error downloading ${file_name} ===" + cat download.log + else + if [ "$file_name" != "" ]; then + DOWNLOAD_NAMES="${DOWNLOAD_NAMES} ${file_name}" + fi + fi +done + +rm download.log + +echo "Create archive..." + +cd ${OUTPUT_DIR} +tar -cjf SuperBuild-archives.tar.bz2 -C ${DOWNLOAD_DIR} ${DOWNLOAD_NAMES} + +echo "Compute md5sum..." +md5sum SuperBuild-archives.tar.bz2 >SuperBuild-archives.md5