diff --git a/CMake/OTBModuleRemote.cmake b/CMake/OTBModuleRemote.cmake index 74f6b170ee65cd2b86dacedf646b04d74caf27a0..c0c7aa4af230e4183fe4aed562cc19231d157c63 100644 --- a/CMake/OTBModuleRemote.cmake +++ b/CMake/OTBModuleRemote.cmake @@ -22,12 +22,17 @@ # Helper to perform the initial git clone and checkout. function(_git_clone git_executable git_repository git_tag module_dir) - execute_process( - COMMAND "${git_executable}" clone "${git_repository}" "${module_dir}" - RESULT_VARIABLE error_code - OUTPUT_QUIET - ERROR_QUIET - ) + set(retryCount 0) + set(error_code 1) + while(error_code AND (retryCount LESS 3)) + execute_process( + COMMAND "${git_executable}" clone "${git_repository}" "${module_dir}" + RESULT_VARIABLE error_code + OUTPUT_QUIET + ERROR_QUIET + ) + math(EXPR retryCount "${retryCount}+1") + endwhile() if(error_code) message(FATAL_ERROR "Failed to clone repository: '${git_repository}'") endif() diff --git a/Documentation/Cookbook/rst/recipes/pbclassif.rst b/Documentation/Cookbook/rst/recipes/pbclassif.rst index 8de90bce37a3cee246b18c9664f035268b394947..5189fd24c5f7fa1cb44dc83a648a69466ec6f6c3 100644 --- a/Documentation/Cookbook/rst/recipes/pbclassif.rst +++ b/Documentation/Cookbook/rst/recipes/pbclassif.rst @@ -4,10 +4,10 @@ Classification Pixel based classification -------------------------- -Orfeo ToolBox ships with a set of application to perform supervised -pixel-based image classification. This framework allows to learn from -multiple images, and using several machine learning method such as -SVM, Bayes, KNN, Random Forests, Artificial Neural Network, and +Orfeo ToolBox ships with a set of application to perform supervised or +unsupervised pixel-based image classification. This framework allows +to learn from multiple images, and using several machine learning method +such as SVM, Bayes, KNN, Random Forests, Artificial Neural Network, and others...(see application help of ``TrainImagesClassifier`` and ``TrainVectorClassifier`` for further details about all the available classifiers). Here is an overview of the complete workflow: @@ -235,7 +235,7 @@ image. class required) - *Mode = proportional:* For each image :math:`i` and each class :math:`c`, - :math:`N_i( c ) = \frac{M * T_i( c )}{sum_k( T_k(c)}` + :math:`N_i( c ) = \frac{M * T_i(c)}{sum_k(T_k(c))}` - *Mode = equal:* For each image :math:`i` and each class :math:`c`, :math:`N_i( c ) = \frac{M}{L}` - *Mode = custom:* For each image :math:`i` and each class :math:`c`, @@ -347,8 +347,9 @@ using the ``TrainVectorClassifier`` application. -feat band_0 band_1 band_2 band_3 band_4 band_5 band_6 The ``-classifier`` parameter allows to choose which machine learning -model algorithm to train. Please refer to the -``TrainVectorClassifier`` application reference documentation. +model algorithm to train. You have the possibility to do the unsupervised +classification,for it, you must to choose the Shark kmeans classifier. +Please refer to the ``TrainVectorClassifier`` application reference documentation. In case of multiple samples files, you can add them to the ``-io.vd`` parameter (see `Working with several images`_ section). @@ -409,6 +410,11 @@ class too, based on the `ConfusionMatrixCalculator <http://www.orfeo-toolbox.org/doxygen-current/classotb_1_1ConfusionMatrixCalculator.html>`_ class. +If you have made an unsupervised classification, it must be specified +to the ``ConputeConfusionMatrix`` application. In this case, a contingency table +have to be create rather than a confusion matrix. For further details, +see ``format`` parameter in the application help of *ConputeConfusionMatrix*. + :: otbcli_ComputeConfusionMatrix -in labeled_image.tif diff --git a/Examples/DisparityMap/FineRegistrationImageFilterExample.cxx b/Examples/DisparityMap/FineRegistrationImageFilterExample.cxx index c365bd7e8a9db3df8bf68a8b7a097ffed87bb9f1..7e730b27f26eca50f284d3ece4ff3ddd516a926d 100644 --- a/Examples/DisparityMap/FineRegistrationImageFilterExample.cxx +++ b/Examples/DisparityMap/FineRegistrationImageFilterExample.cxx @@ -45,7 +45,7 @@ #include "otbImageFileReader.h" #include "itkUnaryFunctorImageFilter.h" #include "itkRecursiveGaussianImageFilter.h" -#include "otbWarpImageFilter.h" +#include "itkWarpImageFilter.h" #include "itkMeanReciprocalSquareDifferenceImageToImageMetric.h" // Software Guide : BeginCodeSnippet @@ -255,7 +255,7 @@ int main(int argc, char** argv) dfWriter->SetFileName(argv[4]); dfWriter->Update(); - typedef otb::WarpImageFilter<InputImageType, InputImageType, + typedef itk::WarpImageFilter<InputImageType, InputImageType, DisplacementFieldType> WarperType; WarperType::Pointer warper = WarperType::New(); diff --git a/Examples/DisparityMap/NCCRegistrationFilterExample.cxx b/Examples/DisparityMap/NCCRegistrationFilterExample.cxx index 396c4b3e37d19cd49868180c6861c69c69bbb2a2..c033aeb7288476bc24419e5eb5ef23a6309a6976 100644 --- a/Examples/DisparityMap/NCCRegistrationFilterExample.cxx +++ b/Examples/DisparityMap/NCCRegistrationFilterExample.cxx @@ -42,7 +42,7 @@ // Software Guide : BeginCodeSnippet #include "otbNCCRegistrationFilter.h" #include "itkRecursiveGaussianImageFilter.h" -#include "otbWarpImageFilter.h" +#include "itkWarpImageFilter.h" // Software Guide : EndCodeSnippet #include "otbImageOfVectorsToMonoChannelExtractROI.h" @@ -211,7 +211,7 @@ int main(int argc, char** argv) dfWriter->SetFileName(argv[4]); dfWriter->Update(); - typedef otb::WarpImageFilter<MovingImageType, MovingImageType, + typedef itk::WarpImageFilter<MovingImageType, MovingImageType, DisplacementFieldType> WarperType; WarperType::Pointer warper = WarperType::New(); diff --git a/Examples/DisparityMap/SimpleDisparityMapEstimationExample.cxx b/Examples/DisparityMap/SimpleDisparityMapEstimationExample.cxx index 88708be7f320c21b1a7b1fde16a6ba7772b96ede..22d646b2318a164692edff8bdd7dc99f7b71f166 100644 --- a/Examples/DisparityMap/SimpleDisparityMapEstimationExample.cxx +++ b/Examples/DisparityMap/SimpleDisparityMapEstimationExample.cxx @@ -47,7 +47,7 @@ #include "itkWindowedSincInterpolateImageFunction.h" #include "itkGradientDescentOptimizer.h" #include "otbBSplinesInterpolateDisplacementFieldGenerator.h" -#include "otbWarpImageFilter.h" +#include "itkWarpImageFilter.h" // Software Guide : EndCodeSnippet #include "otbImageFileReader.h" @@ -414,7 +414,7 @@ int main(int argc, char* argv[]) // Software Guide : BeginCodeSnippet - typedef otb::WarpImageFilter<ImageType, ImageType, + typedef itk::WarpImageFilter<ImageType, ImageType, DisplacementFieldType> ImageWarperType; // Software Guide : EndCodeSnippet diff --git a/Examples/FeatureExtraction/AsymmetricFusionOfLineDetectorExample.cxx b/Examples/FeatureExtraction/AsymmetricFusionOfLineDetectorExample.cxx index cb2ef05f201aa7c0ee61e66213a304998640114b..c6ef8a691fa02d7f7db8d5f105f3caa0e9a84cfe 100644 --- a/Examples/FeatureExtraction/AsymmetricFusionOfLineDetectorExample.cxx +++ b/Examples/FeatureExtraction/AsymmetricFusionOfLineDetectorExample.cxx @@ -35,7 +35,7 @@ // Software Guide : EndLatex // Software Guide : BeginCodeSnippet -#include "otbAssymmetricFusionOfLineDetectorImageFilter.h" +#include "otbAsymmetricFusionOfLineDetectorImageFilter.h" // Software Guide : EndCodeSnippet #include "otbImage.h" @@ -85,7 +85,7 @@ int main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - typedef otb::AssymmetricFusionOfLineDetectorImageFilter<InternalImageType, + typedef otb::AsymmetricFusionOfLineDetectorImageFilter<InternalImageType, InternalImageType> FilterType; // Software Guide : EndCodeSnippet diff --git a/Examples/Learning/CMakeLists.txt b/Examples/Learning/CMakeLists.txt index 8d25fa6e2280808f545dda543b621b6165e55cb7..89d15d3743f07ae549c64f8f4901f4386229da47 100644 --- a/Examples/Learning/CMakeLists.txt +++ b/Examples/Learning/CMakeLists.txt @@ -33,23 +33,8 @@ 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}) - add_executable(SVMImageEstimatorClassificationMultiExample SVMImageEstimatorClassificationMultiExample.cxx) target_link_libraries(SVMImageEstimatorClassificationMultiExample ${OTB_LIBRARIES}) - -add_executable(SVMImageModelEstimatorExample SVMImageModelEstimatorExample.cxx) -target_link_libraries(SVMImageModelEstimatorExample ${OTB_LIBRARIES}) - -add_executable(SVMPointSetClassificationExample SVMPointSetClassificationExample.cxx) -target_link_libraries(SVMPointSetClassificationExample ${OTB_LIBRARIES}) - -add_executable(SVMPointSetExample SVMPointSetExample.cxx) -target_link_libraries(SVMPointSetExample ${OTB_LIBRARIES}) - -add_executable(SVMPointSetModelEstimatorExample SVMPointSetModelEstimatorExample.cxx) -target_link_libraries(SVMPointSetModelEstimatorExample ${OTB_LIBRARIES}) endif() if(OTBOpenCV_LOADED) diff --git a/Examples/Learning/SVMImageClassificationExample.cxx b/Examples/Learning/SVMImageClassificationExample.cxx deleted file mode 100644 index c73ad425c0f6491abb3414d383808cfac3ec15e5..0000000000000000000000000000000000000000 --- a/Examples/Learning/SVMImageClassificationExample.cxx +++ /dev/null @@ -1,337 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - - -#include <fstream> - -#include "otbImageFileReader.h" -#include "otbImageFileWriter.h" -#include "itkUnaryFunctorImageFilter.h" -#include "itkRescaleIntensityImageFilter.h" -#include "otbImage.h" - -// Software Guide : BeginCommandLineArgs -// INPUTS: {ROI_QB_MUL_1.png} -// OUTPUTS: {ROI_QB_MUL_1_SVN_CLASS.png} -// ${OTB_DATA_ROOT}/Examples/svm_image_model.svm -// Software Guide : EndCommandLineArgs - -// Software Guide : BeginLatex -// This example illustrates the use of the -// \doxygen{otb}{SVMClassifier} class for performing SVM -// classification on images. -// In this example, we will use an SVM model estimated in the example -// of section \ref{sec:LearningWithImages} -// to separate between water and non-water pixels by using the RGB -// values only. The images used for this example are shown in -// figure~\ref{fig:SVMROIS}. -// The first thing to do is include the header file for the -// class. Since the \doxygen{otb}{SVMClassifier} takes -// \doxygen{itk}{ListSample}s as input, the class -// \doxygen{itk}{PointSetToListAdaptor} is needed. -// -// -// Software Guide : EndLatex - -#include "itkImageToListSampleAdaptor.h" - -// Software Guide : BeginCodeSnippet -#include "otbSVMClassifier.h" -// Software Guide : EndCodeSnippet - -int main(int argc, char* argv[]) -{ - - if (argc != 4) - { - std::cout << "Usage : " << argv[0] << " inputImage outputImage modelFile " - << std::endl; - return EXIT_FAILURE; - } - - const char * imageFilename = argv[1]; - const char * modelFilename = argv[3]; - const char * outputFilename = argv[2]; - -// Software Guide : BeginLatex -// -// In the framework of supervised learning and classification, we will -// always use feature vectors for the characterization of the -// classes. On the other hand, the class labels are scalar -// values. Here, we start by defining the type of the features as the -// \code{PixelType}, which will be used to define the feature -// \code{VectorType}. We also declare the type for the labels. -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet - typedef double PixelType; - typedef int LabelPixelType; -// Software Guide : EndCodeSnippet - const unsigned int Dimension = 2; - -// Software Guide : BeginLatex -// -// We can now proceed to define the image type used for storing the -// features. We also define the reader. -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet - typedef otb::Image<itk::FixedArray<PixelType, 3>, - Dimension> InputImageType; - - typedef otb::ImageFileReader<InputImageType> ReaderType; -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// We can now read the image by calling the \code{Update} method of the reader. -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet - ReaderType::Pointer reader = ReaderType::New(); - - reader->SetFileName(imageFilename); - - reader->Update(); -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// The image has now to be transformed to a sample which -// is compatible with the classification framework. We will use a -// \doxygen{itk}{Statistics::ImageToListSampleAdaptor} for this -// task. This class is templated over the image type used for -// storing the measures. -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet - typedef itk::Statistics::ImageToListSampleAdaptor<InputImageType> SampleType; - SampleType::Pointer sample = SampleType::New(); -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// After instantiation, we can set the image as an imput of our -// sample adaptor. -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet - sample->SetImage(reader->GetOutput()); -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// Now, we need to declare the SVM model which is to be used by the -// classifier. The SVM model is templated over the type of value used -// for the measures and the type of pixel used for the labels. -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet - typedef otb::SVMModel<PixelType, LabelPixelType> ModelType; - - ModelType::Pointer model = ModelType::New(); -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// After instantiation, we can load a model saved to a file (see -// section \ref{sec:LearningWithImages} for an example of model -// estimation and storage to a file. -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet - model->LoadModel(modelFilename); -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// We have now all the elements to create a classifier. The classifier -// is templated over the sample type (the type of the data to be -// classified) and the label type (the type of the output of the classifier). -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet - typedef otb::SVMClassifier<SampleType, LabelPixelType> ClassifierType; - - ClassifierType::Pointer classifier = ClassifierType::New(); -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// We set the classifier parameters : number of classes, SVM model, -// the sample data. And we trigger the classification process by -// calling the \code{Update} method. -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet - int numberOfClasses = model->GetNumberOfClasses(); - classifier->SetNumberOfClasses(numberOfClasses); - classifier->SetModel(model); - classifier->SetInput(sample.GetPointer()); - classifier->Update(); -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// After the classification step, we usually want to get the -// results. The classifier gives an output under the form of a sample -// list. This list supports the classical STL iterators. Therefore, we -// will create an output image and fill it up with the results of the -// classification. The pixel type of the output image is the same as -// the one used for the labels. -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet - typedef ClassifierType::ClassLabelType OutputPixelType; - typedef otb::Image<OutputPixelType, Dimension> OutputImageType; - - OutputImageType::Pointer outputImage = OutputImageType::New(); -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// We allocate the memory for the output image using the information -// from the input image. -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet - typedef itk::Index<Dimension> myIndexType; - typedef itk::Size<Dimension> mySizeType; - typedef itk::ImageRegion<Dimension> myRegionType; - - mySizeType size; - size[0] = reader->GetOutput()->GetRequestedRegion().GetSize()[0]; - size[1] = reader->GetOutput()->GetRequestedRegion().GetSize()[1]; - - myIndexType start; - start[0] = 0; - start[1] = 0; - - myRegionType region; - region.SetIndex(start); - region.SetSize(size); - - outputImage->SetRegions(region); - outputImage->Allocate(); -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// We can now declare the iterators on the list that we get at the -// output of the classifier as well as the iterator to fill the output image. -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet - ClassifierType::OutputType* membershipSample = - classifier->GetOutput(); - ClassifierType::OutputType::ConstIterator m_iter = - membershipSample->Begin(); - ClassifierType::OutputType::ConstIterator m_last = - membershipSample->End(); - - typedef itk::ImageRegionIterator<OutputImageType> OutputIteratorType; - OutputIteratorType outIt(outputImage, - outputImage->GetBufferedRegion()); - - outIt.GoToBegin(); -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// We will iterate through the list, get the labels and assign pixel -// values to the output image. -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet - while (m_iter != m_last && !outIt.IsAtEnd()) - { - outIt.Set(m_iter.GetClassLabel()); - ++m_iter; - ++outIt; - } -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// Only for visualization purposes, we choose to rescale the image of -// classes before saving it to a file. We will use the -// \doxygen{itk}{RescaleIntensityImageFilter} for this purpose. -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet - typedef otb::Image<unsigned char, Dimension> FileImageType; - - typedef itk::RescaleIntensityImageFilter<OutputImageType, - FileImageType> RescalerType; - - RescalerType::Pointer rescaler = RescalerType::New(); - - rescaler->SetOutputMinimum(itk::NumericTraits<unsigned char>::min()); - rescaler->SetOutputMaximum(itk::NumericTraits<unsigned char>::max()); - - rescaler->SetInput(outputImage); -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// We can now create an image file writer and save the image. -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet - typedef otb::ImageFileWriter<FileImageType> WriterType; - - WriterType::Pointer writer = WriterType::New(); - - writer->SetFileName(outputFilename); - writer->SetInput(rescaler->GetOutput()); - - writer->Update(); -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// Figure \ref{fig:SVMCLASS} shows the result of the SVM classification. -// \begin{figure} -// \center -// \includegraphics[width=0.45\textwidth]{ROI_QB_MUL_1.eps} -// \includegraphics[width=0.45\textwidth]{ROI_QB_MUL_1_SVN_CLASS.eps} -// \itkcaption[SVM Image Classification]{Result of the SVM -// classification . Left: RGB image. Right: image of classes.} -// \label{fig:SVMCLASS} -// \end{figure} -// Software Guide : EndLatex - - return EXIT_SUCCESS; -} diff --git a/Examples/Learning/SVMImageEstimatorClassificationMultiExample.cxx b/Examples/Learning/SVMImageEstimatorClassificationMultiExample.cxx index ad59e3afbfafac15f9635906fe14d90e25b3ac23..fec55cbf7de04326495f5ef8d18f4a9b825726e4 100644 --- a/Examples/Learning/SVMImageEstimatorClassificationMultiExample.cxx +++ b/Examples/Learning/SVMImageEstimatorClassificationMultiExample.cxx @@ -52,15 +52,16 @@ #include <iostream> // Software Guide : BeginCodeSnippet -#include "otbSVMImageModelEstimator.h" -#include "itkImageToListSampleAdaptor.h" -#include "otbSVMClassifier.h" +#include "otbLibSVMMachineLearningModel.h" +#include "itkImageToListSampleFilter.h" +#include "otbImageClassificationFilter.h" // Software Guide : EndCodeSnippet #include "otbImageFileWriter.h" #include "itkUnaryFunctorImageFilter.h" #include "itkScalarToRGBPixelFunctor.h" +#include "itkBinaryThresholdImageFilter.h" #include "otbImageFileReader.h" @@ -92,13 +93,13 @@ int main(int itkNotUsed(argc), char *argv[]) // Software Guide : BeginLatex // -// The \doxygen{otb}{SVMImageModelEstimator} class is templated over -// the input (features) and the training (labels) images. +// The \doxygen{otb}{LibSVMMachineLearningModel} class is templated over +// the input (features) and the training (labels) values. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - typedef otb::SVMImageModelEstimator<InputImageType, - TrainingImageType> EstimatorType; + typedef otb::LibSVMMachineLearningModel<InputPixelType, + InputPixelType> ModelType; // Software Guide : EndCodeSnippet @@ -128,107 +129,67 @@ int main(int itkNotUsed(argc), char *argv[]) inputReader->SetFileName(inputImageFileName); trainingReader->SetFileName(trainingImageFileName); - inputReader->Update(); - trainingReader->Update(); + //~ inputReader->Update(); + //~ trainingReader->Update(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // -// We can now instantiate the model estimator and set its parameters. +// The input data is contained in images. Only label values greater than 0 +// shall be used, so we create two iterators to fill the input and target +// ListSamples. // // Software Guide : EndLatex -// Software Guide : BeginCodeSnippet - EstimatorType::Pointer svmEstimator = EstimatorType::New(); - - svmEstimator->SetInputImage(inputReader->GetOutput()); - svmEstimator->SetTrainingImage(trainingReader->GetOutput()); - -// Software Guide : EndCodeSnippet -// Software Guide : BeginLatex -// -// The model estimation procedure is triggered by calling the -// estimator's \code{Update} method. -// -// Software Guide : EndLatex // Software Guide : BeginCodeSnippet - svmEstimator->Update(); - -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// We can now proceed to the image classification. We start by -// declaring the type of the image to be classified. ITK's -// classification framework needs the type of the pixel to be of -// fixed type, so we declare the following types. -// -// Software Guide : EndLatex -// Software Guide : BeginCodeSnippet - typedef otb::Image<itk::FixedArray<InputPixelType, 3>, - Dimension> ClassifyImageType; + typedef itk::BinaryThresholdImageFilter<TrainingImageType,TrainingImageType> ThresholdFilterType; + ThresholdFilterType::Pointer thresholder = ThresholdFilterType::New(); + thresholder->SetInput(trainingReader->GetOutput()); + thresholder->SetLowerThreshold(1); + thresholder->SetOutsideValue(0); + thresholder->SetInsideValue(1); - typedef otb::ImageFileReader<ClassifyImageType> ClassifyReaderType; -// Software Guide : EndCodeSnippet + typedef itk::Statistics::ImageToListSampleFilter<InputImageType,TrainingImageType> ImageToListSample; + typedef itk::Statistics::ImageToListSampleFilter<TrainingImageType,TrainingImageType> ImageToTargetListSample; -// Software Guide : BeginLatex -// -// We can now read the image by calling the \code{Update} method of the reader. -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet - ClassifyReaderType::Pointer cReader = ClassifyReaderType::New(); + ImageToListSample::Pointer imToList = ImageToListSample::New(); + imToList->SetInput(inputReader->GetOutput()); + imToList->SetMaskImage(thresholder->GetOutput()); + imToList->SetMaskValue(1); + imToList->Update(); - cReader->SetFileName(inputImageFileName); + ImageToTargetListSample::Pointer imToTargetList = ImageToTargetListSample::New(); + imToTargetList->SetInput(trainingReader->GetOutput()); + imToTargetList->SetMaskImage(thresholder->GetOutput()); + imToTargetList->SetMaskValue(1); + imToTargetList->Update(); - cReader->Update(); -// Software Guide : EndCodeSnippet -// Software Guide : BeginLatex -// -// The image has now to be transformed to a sample which -// is compatible with the classification framework. We will use a -// \doxygen{itk}{Statistics::ImageToListSampleAdaptor} for this -// task. This class is templated over the image type used for -// storing the measures. -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet - typedef itk::Statistics::ImageToListSampleAdaptor<ClassifyImageType> SampleType; - SampleType::Pointer sample = SampleType::New(); -// Software Guide : EndCodeSnippet +// Software Guide : EndCodeSnippet -// Software Guide : BeginLatex +// Software Guide : BeginLatex // -// After instantiation, we can set the image as an imput of our -// sample adaptor. +// We can now instantiate the model and set its parameters. // // Software Guide : EndLatex +// Software Guide : BeginCodeSnippet + ModelType::Pointer svmModel = ModelType::New(); + svmModel->SetInputListSample(const_cast<ModelType::InputListSampleType*>(imToList->GetOutput())); + svmModel->SetTargetListSample(const_cast<ModelType::TargetListSampleType*>(imToTargetList->GetOutput())); -// Software Guide : BeginCodeSnippet - sample->SetImage(cReader->GetOutput()); -// Software Guide : EndCodeSnippet +// Software Guide : EndCodeSnippet -// Software Guide : BeginLatex +// Software Guide : BeginLatex // -// Now, we need to declare the SVM model which is to be used by the -// classifier. The SVM model is templated over the type of value used -// for the measures and the type of pixel used for the labels. The -// model is obtained from the model estimator by calling the -// \code{GetModel} method. +// The model training procedure is triggered by calling the +// model's \code{Train} method. // // Software Guide : EndLatex +// Software Guide : BeginCodeSnippet + svmModel->Train(); -// Software Guide : BeginCodeSnippet - typedef InputPixelType LabelPixelType; - - typedef otb::SVMModel<InputPixelType, LabelPixelType> ModelType; - - ModelType::Pointer model = svmEstimator->GetModel(); -// Software Guide : EndCodeSnippet +// Software Guide : EndCodeSnippet // Software Guide : BeginLatex // @@ -239,7 +200,7 @@ int main(int itkNotUsed(argc), char *argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - typedef otb::SVMClassifier<SampleType, LabelPixelType> ClassifierType; + typedef otb::ImageClassificationFilter<InputImageType, TrainingImageType> ClassifierType; ClassifierType::Pointer classifier = ClassifierType::New(); // Software Guide : EndCodeSnippet @@ -253,11 +214,8 @@ int main(int itkNotUsed(argc), char *argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - int numberOfClasses = model->GetNumberOfClasses(); - classifier->SetNumberOfClasses(numberOfClasses); - classifier->SetModel(model); - classifier->SetInput(sample.GetPointer()); - classifier->Update(); + classifier->SetModel(svmModel); + classifier->SetInput(inputReader->GetOutput()); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex @@ -272,10 +230,7 @@ int main(int itkNotUsed(argc), char *argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - typedef ClassifierType::ClassLabelType OutputPixelType; - typedef otb::Image<OutputPixelType, Dimension> OutputImageType; - OutputImageType::Pointer outputImage = OutputImageType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex @@ -286,25 +241,7 @@ int main(int itkNotUsed(argc), char *argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - typedef itk::Index<Dimension> myIndexType; - typedef itk::Size<Dimension> mySizeType; - typedef itk::ImageRegion<Dimension> myRegionType; - - mySizeType size; - size[0] = cReader->GetOutput()->GetRequestedRegion().GetSize()[0]; - size[1] = cReader->GetOutput()->GetRequestedRegion().GetSize()[1]; - - myIndexType start; - start[0] = 0; - start[1] = 0; - myRegionType region; - region.SetIndex(start); - region.SetSize(size); - - outputImage->SetRegions(region); - outputImage->Allocate(); - std::cout << "---" << std::endl; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex @@ -315,18 +252,7 @@ int main(int itkNotUsed(argc), char *argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - ClassifierType::OutputType* membershipSample = - classifier->GetOutput(); - ClassifierType::OutputType::ConstIterator m_iter = - membershipSample->Begin(); - ClassifierType::OutputType::ConstIterator m_last = - membershipSample->End(); - - typedef itk::ImageRegionIterator<OutputImageType> OutputIteratorType; - OutputIteratorType outIt(outputImage, - outputImage->GetBufferedRegion()); - - outIt.GoToBegin(); + // Software Guide : EndCodeSnippet // Software Guide : BeginLatex @@ -337,21 +263,15 @@ int main(int itkNotUsed(argc), char *argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - while (m_iter != m_last && !outIt.IsAtEnd()) - { - outIt.Set(m_iter.GetClassLabel()); - ++m_iter; - ++outIt; - } - std::cout << "---" << std::endl; + // Software Guide : EndCodeSnippet - typedef otb::ImageFileWriter<OutputImageType> WriterType; + typedef otb::ImageFileWriter<TrainingImageType> WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName(outputImageFileName); - writer->SetInput(outputImage); + writer->SetInput(classifier->GetOutput()); writer->Update(); @@ -372,12 +292,12 @@ int main(int itkNotUsed(argc), char *argv[]) typedef otb::Image<RGBPixelType, 2> RGBImageType; typedef itk::Functor::ScalarToRGBPixelFunctor<unsigned long> ColorMapFunctorType; - typedef itk::UnaryFunctorImageFilter<OutputImageType, + typedef itk::UnaryFunctorImageFilter<TrainingImageType, RGBImageType, ColorMapFunctorType> ColorMapFilterType; ColorMapFilterType::Pointer colormapper = ColorMapFilterType::New(); - colormapper->SetInput(outputImage); + colormapper->SetInput(classifier->GetOutput()); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex diff --git a/Examples/Learning/SVMImageModelEstimatorExample.cxx b/Examples/Learning/SVMImageModelEstimatorExample.cxx deleted file mode 100644 index 9ee96db859d87531a99b575f86758e05c6e4e360..0000000000000000000000000000000000000000 --- a/Examples/Learning/SVMImageModelEstimatorExample.cxx +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - - -// Software Guide : BeginCommandLineArgs -// INPUTS: {ROI_QB_MUL_1.png}, {ROI_mask.png} -// OUTPUTS: {svm_image_model.svn} -// Software Guide : EndCommandLineArgs - -// Software Guide : BeginLatex -// This example illustrates the use of the -// \doxygen{otb}{SVMImageModelEstimator} class. This class allows the -// estimation of a SVM model (supervised learning) from a feature -// image and an image of labels. In this example, we will train an SVM -// to separate between water and non-water pixels by using the RGB -// values only. The images used for this example are shown in -// figure~\ref{fig:SVMROIS}. -// \begin{figure} -// \center -// \includegraphics[width=0.45\textwidth]{ROI_QB_MUL_1.eps} -// \includegraphics[width=0.45\textwidth]{ROI_mask.eps} -// \itkcaption[SVM Image Model Estimation]{Images used for the -// estimation of the SVM model. Left: RGB image. Right: image of labels.} -// \label{fig:SVMROIS} -// \end{figure} -// The first thing to do is include the header file for the class. -// -// Software Guide : EndLatex - -#include "itkMacro.h" -#include "otbImage.h" -#include "otbVectorImage.h" -#include <iostream> - -// Software Guide : BeginCodeSnippet -#include "otbSVMImageModelEstimator.h" -// Software Guide : EndCodeSnippet - -#include "otbImageFileReader.h" - -int main(int itkNotUsed(argc), char* argv[]) -{ - - const char* inputImageFileName = argv[1]; - const char* trainingImageFileName = argv[2]; - const char* outputModelFileName = argv[3]; - -// Software Guide : BeginLatex -// -// We define the types for the input and training images. Even if the -// input image will be an RGB image, we can read it as a 3 component -// vector image. This simplifies the interfacing with OTB's SVM -// framework. -// -// Software Guide : EndLatex -// Software Guide : BeginCodeSnippet - typedef unsigned char InputPixelType; - const unsigned int Dimension = 2; - - typedef otb::VectorImage<InputPixelType, Dimension> InputImageType; - - typedef otb::Image<InputPixelType, Dimension> TrainingImageType; -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// The \doxygen{otb}{SVMImageModelEstimator} class is templated over -// the input (features) and the training (labels) images. -// -// Software Guide : EndLatex -// Software Guide : BeginCodeSnippet - typedef otb::SVMImageModelEstimator<InputImageType, - TrainingImageType> EstimatorType; - -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// As usual, we define the readers for the images. -// -// Software Guide : EndLatex -// Software Guide : BeginCodeSnippet - typedef otb::ImageFileReader<InputImageType> InputReaderType; - typedef otb::ImageFileReader<TrainingImageType> TrainingReaderType; - - InputReaderType::Pointer inputReader = InputReaderType::New(); - TrainingReaderType::Pointer trainingReader = TrainingReaderType::New(); - -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// We read the images. It is worth to note that, in order to ensure -// the pipeline coherence, the output of the objects which precede the -// model estimator in the pipeline, must be up to date, so we call -// the corresponding \code{Update} methods. -// -// Software Guide : EndLatex -// Software Guide : BeginCodeSnippet - inputReader->SetFileName(inputImageFileName); - trainingReader->SetFileName(trainingImageFileName); - - inputReader->Update(); - trainingReader->Update(); - -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// We can now instantiate the model estimator and set its parameters. -// -// Software Guide : EndLatex -// Software Guide : BeginCodeSnippet - EstimatorType::Pointer svmEstimator = EstimatorType::New(); - - svmEstimator->SetInputImage(inputReader->GetOutput()); - svmEstimator->SetTrainingImage(trainingReader->GetOutput()); - -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// The model estimation procedure is triggered by calling the -// estimator's \code{Update} method. -// -// Software Guide : EndLatex -// Software Guide : BeginCodeSnippet - svmEstimator->Update(); - -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// Finally, the estimated model can be saved to a file for later use. -// -// Software Guide : EndLatex -// Software Guide : BeginCodeSnippet - svmEstimator->SaveModel(outputModelFileName); - -// Software Guide : EndCodeSnippet - - return EXIT_SUCCESS; -} diff --git a/Examples/Learning/SVMPointSetClassificationExample.cxx b/Examples/Learning/SVMPointSetClassificationExample.cxx deleted file mode 100644 index e092f3ec4e9036e3a0daf5a561c896806019403d..0000000000000000000000000000000000000000 --- a/Examples/Learning/SVMPointSetClassificationExample.cxx +++ /dev/null @@ -1,322 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - - -// Software Guide : BeginCommandLineArgs -// INPUTS: {svm_model.svn} -// OUTPUTS: -// Software Guide : EndCommandLineArgs - -#include "itkMacro.h" -#include <iostream> -#include <cstdlib> - -// Software Guide : BeginLatex -// This example illustrates the use of the -// \doxygen{otb}{SVMClassifier} class for performing SVM -// classification on pointsets. -// The first thing to do is include the header file for the -// class. Since the \doxygen{otb}{SVMClassifier} takes -// \doxygen{itk}{ListSample}s as input, the class -// \doxygen{itk}{PointSetToListSampleAdaptor} is needed. -// -// We start by including the needed header files. -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet -#include "itkPointSetToListSampleAdaptor.h" -#include "otbSVMClassifier.h" -// Software Guide : EndCodeSnippet - -int main(int itkNotUsed(argc), char* argv[]) -{ -// Software Guide : BeginLatex -// -// In the framework of supervised learning and classification, we will -// always use feature vectors for the characterization of the -// classes. On the other hand, the class labels are scalar -// values. Here, we start by defining the type of the features as the -// \code{PixelType}, which will be used to define the feature -// \code{VectorType}. We also declare the type for the labels. -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet - typedef float InputPixelType; - - typedef std::vector<InputPixelType> InputVectorType; - typedef int LabelPixelType; -// Software Guide : EndCodeSnippet - const unsigned int Dimension = 2; - -// Software Guide : BeginLatex -// -// We can now proceed to define the point sets used for storing the -// features and the labels. -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet - typedef itk::PointSet<InputVectorType, Dimension> MeasurePointSetType; -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// We will need to get access to the data stored in the point sets, so -// we define the appropriate for the points and the points containers -// used by the point sets (see the section \ref{sec:PointSetSection} -// for more information on how to use point sets). -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet - typedef MeasurePointSetType::PointType MeasurePointType; - typedef MeasurePointSetType::PointsContainer MeasurePointsContainer; - - MeasurePointSetType::Pointer tPSet = MeasurePointSetType::New(); - MeasurePointsContainer::Pointer tCont = MeasurePointsContainer::New(); -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// We need now to build the test set for the SVM. In this -// simple example, we will build a SVM who classes points depending on -// which side of the line $x=y$ they are located. We start by -// generating 500 random points. -// -// Software Guide : EndLatex - - srand(0); - - unsigned int pointId; -// Software Guide : BeginCodeSnippet - int lowest = 0; - int range = 1000; - - for (pointId = 0; pointId < 100; pointId++) - { - - MeasurePointType tP; - - int x_coord = lowest + static_cast<int>(range * (rand() / (RAND_MAX + 1.0))); - int y_coord = lowest + static_cast<int>(range * (rand() / (RAND_MAX + 1.0))); - - std::cout << "coords : " << x_coord << " " << y_coord << std::endl; - tP[0] = x_coord; - tP[1] = y_coord; -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// We push the features in the vector after a normalization which is -// useful for SVM convergence. -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet - InputVectorType measure; - measure.push_back(static_cast<InputPixelType>((x_coord * 1.0 - - lowest) / range)); - measure.push_back(static_cast<InputPixelType>((y_coord * 1.0 - - lowest) / range)); -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// And we insert the points in the points container. -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet - tCont->InsertElement(pointId, tP); - tPSet->SetPointData(pointId, measure); - - } -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// After the loop, we set the points container to the point set. -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet - tPSet->SetPoints(tCont); -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// Once the pointset is ready, we must transform it to a sample which -// is compatible with the classification framework. We will use a -// \doxygen{itk}{Statistics::PointSetToListSampleAdaptor} for this -// task. This class is templated over the point set type used for -// storing the measures. -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet - typedef itk::Statistics::PointSetToListSampleAdaptor<MeasurePointSetType> - SampleType; - SampleType::Pointer sample = SampleType::New(); -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// After instantiation, we can set the point set as an imput of our -// sample adaptor. -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet - sample->SetPointSet(tPSet); -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// Now, we need to declare the SVM model which is to be used by the -// classifier. The SVM model is templated over the type of value used -// for the measures and the type of pixel used for the labels. -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet - typedef otb::SVMModel<SampleType::MeasurementVectorType::ValueType, - LabelPixelType> ModelType; - - ModelType::Pointer model = ModelType::New(); -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// After instantiation, we can load a model saved to a file (see -// section \ref{sec:LearningWithPointSets} for an example of model -// estimation and storage to a file). -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet - model->LoadModel(argv[1]); -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// We have now all the elements to create a classifier. The classifier -// is templated over the sample type (the type of the data to be -// classified) and the label type (the type of the output of the classifier). -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet - typedef otb::SVMClassifier<SampleType, LabelPixelType> ClassifierType; - - ClassifierType::Pointer classifier = ClassifierType::New(); -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// We set the classifier parameters : number of classes, SVM model, -// the sample data. And we trigger the classification process by -// calling the \code{Update} method. -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet - int numberOfClasses = model->GetNumberOfClasses(); - classifier->SetNumberOfClasses(numberOfClasses); - classifier->SetModel(model); - classifier->SetInput(sample.GetPointer()); - classifier->Update(); -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// After the classification step, we usually want to get the -// results. The classifier gives an output under the form of a sample -// list. This list supports the classical STL iterators. -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet - ClassifierType::OutputType* membershipSample = - classifier->GetOutput(); - - ClassifierType::OutputType::ConstIterator m_iter = - membershipSample->Begin(); - ClassifierType::OutputType::ConstIterator m_last = - membershipSample->End(); -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// We will iterate through the list, get the labels and compute the -// classification error. -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet - double error = 0.0; - pointId = 0; - while (m_iter != m_last) - { -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// We get the label for each point. -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet - ClassifierType::ClassLabelType label = m_iter.GetClassLabel(); -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// And we compare it to the corresponding one of the test set. -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet - InputVectorType measure; - - tPSet->GetPointData(pointId, &measure); - - ClassifierType::ClassLabelType expectedLabel; - if (measure[0] < measure[1]) expectedLabel = -1; - else expectedLabel = 1; - - double dist = fabs(measure[0] - measure[1]); - - if (label != expectedLabel) error++; - - std::cout << int(label) << "/" << int(expectedLabel) << " --- " << dist << - std::endl; - - ++pointId; - ++m_iter; - } - - std::cout << "Error = " << error / pointId << " % " << std::endl; -// Software Guide : EndCodeSnippet - - return EXIT_SUCCESS; -} diff --git a/Examples/Learning/SVMPointSetExample.cxx b/Examples/Learning/SVMPointSetExample.cxx deleted file mode 100644 index 6c60460cc3211434eb089be045569299c6c48b88..0000000000000000000000000000000000000000 --- a/Examples/Learning/SVMPointSetExample.cxx +++ /dev/null @@ -1,219 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - - -#include "itkMacro.h" -#include <iostream> -#include <cstdlib> - -#include "otbSVMPointSetModelEstimator.h" -#include "itkPointSetToListSampleAdaptor.h" -#include "otbSVMClassifier.h" - -int main(int itkNotUsed(argc), char* itkNotUsed(argv)[]) -{ - - typedef float InputPixelType; - - typedef std::vector<InputPixelType> InputVectorType; - typedef int LabelPixelType; - const unsigned int Dimension = 2; - - typedef itk::PointSet<InputVectorType, Dimension> MeasurePointSetType; - - typedef itk::PointSet<LabelPixelType, Dimension> LabelPointSetType; - - MeasurePointSetType::Pointer mPSet = MeasurePointSetType::New(); - LabelPointSetType::Pointer lPSet = LabelPointSetType::New(); - - typedef MeasurePointSetType::PointType MeasurePointType; - typedef LabelPointSetType::PointType LabelPointType; - - typedef MeasurePointSetType::PointsContainer MeasurePointsContainer; - typedef LabelPointSetType::PointsContainer LabelPointsContainer; - - MeasurePointsContainer::Pointer mCont = MeasurePointsContainer::New(); - LabelPointsContainer::Pointer lCont = LabelPointsContainer::New(); - - /* We learn the y>x | y<x boundary*/ -// srand((unsigned)time(0)); - srand(0); - int lowest = 0; - int range = 1000; - - unsigned int pointId; - - for (pointId = 0; pointId < 500; pointId++) - { - - MeasurePointType mP; - LabelPointType lP; - - int x_coord = lowest + static_cast<int>(range * (rand() / (RAND_MAX + 1.0))); - int y_coord = lowest + static_cast<int>(range * (rand() / (RAND_MAX + 1.0))); - - std::cout << "coords : " << x_coord << " " << y_coord << std::endl; - mP[0] = x_coord; - mP[1] = y_coord; - - lP[0] = x_coord; - lP[1] = y_coord; - - InputVectorType measure; - measure.push_back(static_cast<InputPixelType>((x_coord * 1.0 - - lowest) / range)); - measure.push_back(static_cast<InputPixelType>((y_coord * 1.0 - - lowest) / range)); - - LabelPixelType label; - - if (x_coord < y_coord) label = 0; - else label = 1; - - std::cout << "Label : " << label << std::endl; - std::cout << "Measures : " << measure[0] << " " << measure[1] << std::endl; - - mCont->InsertElement(pointId, mP); - mPSet->SetPointData(pointId, measure); - - lCont->InsertElement(pointId, lP); - lPSet->SetPointData(pointId, label); - - } - - mPSet->SetPoints(mCont); - lPSet->SetPoints(lCont); - - typedef otb::SVMPointSetModelEstimator<MeasurePointSetType, - LabelPointSetType> EstimatorType; - - EstimatorType::Pointer estimator = EstimatorType::New(); - - estimator->SetInputPointSet(mPSet); - estimator->SetTrainingPointSet(lPSet); - - estimator->Update(); - - std::cout << "Saving model" << std::endl; - estimator->SaveModel("model.svm"); - - // Build the test set - - MeasurePointSetType::Pointer tPSet = MeasurePointSetType::New(); - MeasurePointsContainer::Pointer tCont = MeasurePointsContainer::New(); - - for (pointId = 0; pointId < 100; pointId++) - { - - MeasurePointType tP; - - int x_coord = lowest + static_cast<int>(range * (rand() / (RAND_MAX + 1.0))); - int y_coord = lowest + static_cast<int>(range * (rand() / (RAND_MAX + 1.0))); - - std::cout << "coords : " << x_coord << " " << y_coord << std::endl; - tP[0] = x_coord; - tP[1] = y_coord; - - InputVectorType measure; - measure.push_back(static_cast<InputPixelType>((x_coord * 1.0 - - lowest) / range)); - measure.push_back(static_cast<InputPixelType>((y_coord * 1.0 - - lowest) / range)); - - std::cout << "Measures : " << measure[0] << " " << measure[1] << std::endl; - - tCont->InsertElement(pointId, tP); - tPSet->SetPointData(pointId, measure); - - } - - tPSet->SetPoints(tCont); - - // Classify - - typedef itk::Statistics::PointSetToListSampleAdaptor<MeasurePointSetType> - SampleType; - SampleType::Pointer sample = SampleType::New(); - sample->SetPointSet(tPSet); - - std::cout << "Sample set to Adaptor" << std::endl; - - /** preparing classifier and decision rule object */ - typedef otb::SVMModel<SampleType::MeasurementVectorType::ValueType, - LabelPixelType> ModelType; - - ModelType::Pointer model = estimator->GetModel(); - - int numberOfClasses = model->GetNumberOfClasses(); - - std::cout << "Classification for " << numberOfClasses << " classes " << - std::endl; - - typedef otb::SVMClassifier<SampleType, LabelPixelType> ClassifierType; - - ClassifierType::Pointer classifier = ClassifierType::New(); - - classifier->SetNumberOfClasses(numberOfClasses); - classifier->SetModel(model); - classifier->SetInput(sample.GetPointer()); - classifier->Update(); - - /* Build the class map */ - std::cout << "Output image creation" << std::endl; - - std::cout << "classifier get output" << std::endl; - ClassifierType::OutputType* membershipSample = - classifier->GetOutput(); - std::cout << "Sample iterators" << std::endl; - ClassifierType::OutputType::ConstIterator m_iter = - membershipSample->Begin(); - ClassifierType::OutputType::ConstIterator m_last = - membershipSample->End(); - - double error = 0.0; - pointId = 0; - while (m_iter != m_last) - { - ClassifierType::ClassLabelType label = m_iter.GetClassLabel(); - - InputVectorType measure; - - tPSet->GetPointData(pointId, &measure); - - ClassifierType::ClassLabelType expectedLabel; - if (measure[0] < measure[1]) expectedLabel = 0; - else expectedLabel = 1; - - double dist = fabs(measure[0] - measure[1]); - - if (label != expectedLabel) error++; - - std::cout << int(label) << "/" << int(expectedLabel) << " --- " << dist << - std::endl; - - ++pointId; - ++m_iter; - } - - std::cout << "Error = " << error / pointId << std::endl; - - return EXIT_SUCCESS; -} diff --git a/Examples/Learning/SVMPointSetModelEstimatorExample.cxx b/Examples/Learning/SVMPointSetModelEstimatorExample.cxx deleted file mode 100644 index a351194730eb35b0c6103dde6d00df644cb72a63..0000000000000000000000000000000000000000 --- a/Examples/Learning/SVMPointSetModelEstimatorExample.cxx +++ /dev/null @@ -1,264 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - - -#include "itkMacro.h" -#include "itkPointSet.h" -#include <iostream> -#include <cstdlib> - -// Software Guide : BeginLatex -// -// This example illustrates the use of the -// \doxygen{otb}{SVMPointSetModelEstimator} in order to perform the -// SVM learning from an \doxygen{itk}{PointSet} data structure. -// -// The first step required to use this filter is to include its header file. -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet -#include "otbSVMPointSetModelEstimator.h" -// Software Guide : EndCodeSnippet - -int main(int itkNotUsed(argc), char* itkNotUsed(argv)[]) -{ - -// Software Guide : BeginLatex -// -// In the framework of supervised learning and classification, we will -// always use feature vectors for the characterization of the -// classes. On the other hand, the class labels are scalar -// values. Here, we start by defining the type of the features as the -// \code{PixelType}, which will be used to define the feature -// \code{VectorType}. We also declare the type for the labels. -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet - typedef float PixelType; - typedef std::vector<PixelType> VectorType; - typedef int LabelPixelType; -// Software Guide : EndCodeSnippet - const unsigned int Dimension = 2; - -// Software Guide : BeginLatex -// -// We can now proceed to define the point sets used for storing the -// features and the labels. -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet - typedef itk::PointSet<VectorType, Dimension> FeaturePointSetType; - - typedef itk::PointSet<LabelPixelType, Dimension> LabelPointSetType; - - FeaturePointSetType::Pointer fPSet = FeaturePointSetType::New(); - LabelPointSetType::Pointer lPSet = LabelPointSetType::New(); -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// We will need to get access to the data stored in the point sets, so -// we define the appropriate for the points and the points containers -// used by the point sets (see the section \ref{sec:PointSetSection} -// for more information oin haw to use point sets). -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet - typedef FeaturePointSetType::PointType FeaturePointType; - typedef LabelPointSetType::PointType LabelPointType; - - typedef FeaturePointSetType::PointsContainer FeaturePointsContainer; - typedef LabelPointSetType::PointsContainer LabelPointsContainer; - - FeaturePointsContainer::Pointer fCont = FeaturePointsContainer::New(); - LabelPointsContainer::Pointer lCont = LabelPointsContainer::New(); -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// We need now to build the training set for the SVM learning. In this -// simple example, we will build a SVM who classes points depending on -// which side of the line $x=y$ they are located. We start by -// generating 500 random points. -// -// Software Guide : EndLatex - - /* We learn the y>x | y<x boundary*/ - srand(0); - -// Software Guide : BeginCodeSnippet - int lowest = 0; - int range = 1000; - - for (unsigned int pointId = 0; pointId < 500; pointId++) - { - - FeaturePointType fP; - LabelPointType lP; - - int x_coord = lowest + static_cast<int>(range * (rand() / (RAND_MAX + 1.0))); - int y_coord = lowest + static_cast<int>(range * (rand() / (RAND_MAX + 1.0))); -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// We set the coordinates of the points. They are the same for the -// feature vector and for the label. -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet - fP[0] = x_coord; - fP[1] = y_coord; - - lP[0] = x_coord; - lP[1] = y_coord; -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// We push the features in the vector after a normalization which is -// useful for SVM convergence. -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet - VectorType feature; - feature.push_back(static_cast<PixelType>((x_coord * 1.0 - lowest) / range)); - feature.push_back(static_cast<PixelType>((y_coord * 1.0 - lowest) / range)); -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// We decide on the label for each point. -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet - LabelPixelType label; - - if (x_coord < y_coord) label = -1; - else label = 1; -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// And we insert the points in the points containers. -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet - fCont->InsertElement(pointId, fP); - fPSet->SetPointData(pointId, feature); - - lCont->InsertElement(pointId, lP); - lPSet->SetPointData(pointId, label); - - } -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// After the loop, we set the points containers to the point sets. -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet - fPSet->SetPoints(fCont); - lPSet->SetPoints(lCont); -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// Up to now, we have only prepared the data for the SVM learning. We -// can now create the SVM model estimator. This class is templated -// over the feature and the label point set types. -// \index{otb::SVMPointSetModelEstimator} -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet - typedef otb::SVMPointSetModelEstimator<FeaturePointSetType, - LabelPointSetType> EstimatorType; - - EstimatorType::Pointer estimator = EstimatorType::New(); -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// The next step consists in setting the point sets for the estimator -// and the number of classes for the model. The feture point set is -// set using the \code{SetInputPointSet} and the label point set is -// set with the \code{SetTrainingPointSet} method. -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet - estimator->SetInputPointSet(fPSet); - estimator->SetTrainingPointSet(lPSet); -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// The model estimation is triggered by calling the \code{Update} -// method. -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet - estimator->Update(); -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// Finally, we can save the result of the learning to a file. -// -// Software Guide : EndLatex - -// Software Guide : BeginCodeSnippet - estimator->SaveModel("svm_model.svm"); -// Software Guide : EndCodeSnippet - -// Software Guide : BeginLatex -// -// The \doxygen{otb}{otbSVMModel} class provides several accessors in -// order to get some information about the result of the learning -// step. For instance, one can get the number of support vectors kept -// to define the separation surface by using the -// \code{GetNumberOfSupportVectors()}. This can be very useful to -// detect some kind of overlearning (the number of support vectors is -// close to the number of examples). One can also get the SVs -// themselves by calling the \code {GetSupportVectors()}. The $\alpha$ -// values for the support vectors can be accessed by using the -// \code{GetAlpha()} method. Finally the \code{Evaluate()} method will -// return the result of the classification of a sample and the -// \code{EvaluateHyperplaneDistance()} will return the distance of -// the sample to the separating surface (or surfaces in the case of -// multi-class problems). -// -// Software Guide : EndLatex - - return EXIT_SUCCESS; -} diff --git a/Examples/Learning/test/CMakeLists.txt b/Examples/Learning/test/CMakeLists.txt index b5d2b6f1f83f91122ae15f7026ca6023e5e7b2fb..92581e8f1318ed2aa8b0575aae8dc2ee4be2d026 100644 --- a/Examples/Learning/test/CMakeLists.txt +++ b/Examples/Learning/test/CMakeLists.txt @@ -21,19 +21,7 @@ set(BASELINE ${OTB_DATA_ROOT}/Baseline/Examples/Learning) 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 - ${TEMP}/ROI_QB_MUL_1_SVN_CLASS.png - Execute $<TARGET_FILE:SVMImageClassificationExample> - ${INPUTDATA}/ROI_QB_MUL_1.png - ${TEMP}/ROI_QB_MUL_1_SVN_CLASS.png - ${OTB_DATA_ROOT}/Examples/svm_image_model.svm -) - # ------- SVMImageEstimatorClassificationMultiExampleTest---------- otb_add_test(NAME leTeSVMImageEstimatorClassificationMultiExampleTest COMMAND ${OTB_TEST_DRIVER} @@ -47,19 +35,6 @@ otb_add_test(NAME leTeSVMImageEstimatorClassificationMultiExampleTest COMMAND ${ ${TEMP}/ROI_QB_MUL_1_SVN_CLASS_MULTI_Rescaled.png ) -# ------- SVMImageModelEstimatorExampleTest---------- - -otb_add_test(NAME leTeSVMImageModelEstimatorExampleTest COMMAND ${OTB_TEST_DRIVER} - --compare-ascii ${EPSILON_3} - ${BASELINE}/svm_image_model.svn - ${TEMP}/svm_image_model.svn - --ignore-lines-with 2 probA probB - Execute $<TARGET_FILE:SVMImageModelEstimatorExample> - ${INPUTDATA}/ROI_QB_MUL_1.png - ${INPUTDATA}/ROI_mask.png - ${TEMP}/svm_image_model.svn -) - endif() # ------- GenerateTrainingImageExampleTest---------- diff --git a/Modules/Adapters/GdalAdapters/include/otbGeometriesToGeometriesFilter.h b/Modules/Adapters/GdalAdapters/include/otbGeometriesToGeometriesFilter.h index ee1cc07ddac2a681fd6098c3b7bdde39452b9952..5f3ce2267578b13a85a1750cab18046cf680f9c7 100644 --- a/Modules/Adapters/GdalAdapters/include/otbGeometriesToGeometriesFilter.h +++ b/Modules/Adapters/GdalAdapters/include/otbGeometriesToGeometriesFilter.h @@ -170,14 +170,6 @@ private: */ virtual void DoFinalizeInitialization() {} //@} - - /** THIS METHOD IS DEPRECATED AND SHOULD NOT BE USED. */ - void DoFinalizeInitialisation() - { - otbWarningMacro( - << "DoFinalizeInitialisation has been deprecated. Please use DoFinalizeInitialization() instead"); - this->DoFinalizeInitialization(); - } friend struct otb::internal::ProcessVisitor; }; diff --git a/Modules/Adapters/OSSIMAdapters/include/otbDEMHandler.h b/Modules/Adapters/OSSIMAdapters/include/otbDEMHandler.h index 8b9c238e750fb82582395bf01f793a52814fa5aa..dc7a552e2a1efd3174474e5048f4522913a75a5b 100644 --- a/Modules/Adapters/OSSIMAdapters/include/otbDEMHandler.h +++ b/Modules/Adapters/OSSIMAdapters/include/otbDEMHandler.h @@ -41,9 +41,8 @@ namespace otb * * This class is the single configuration and access point for * elevation handling in images projections and localization - * functions. Since this class is a singleton, the New() method is - * deprecated and will be removed in future release. Please use the - * DEMHandler::Instance() method instead. + * functions. Since this class is a singleton, there is no New() method. The + * DEMHandler::Instance() method should be used instead. * * Please be aware that a proper instantiation and parameter setting * of this class is advised before any call to geometric filters or diff --git a/Modules/Adapters/OSSIMAdapters/include/otbMapProjectionAdapter.h b/Modules/Adapters/OSSIMAdapters/include/otbMapProjectionAdapter.h index 37f135939f5fea1b9e3b4cce5286d7a0631f6346..7ba5ffe592361e2203ba0fa015c67834b4a2e337 100644 --- a/Modules/Adapters/OSSIMAdapters/include/otbMapProjectionAdapter.h +++ b/Modules/Adapters/OSSIMAdapters/include/otbMapProjectionAdapter.h @@ -80,14 +80,6 @@ public: bool InstantiateProjection(); - /** THIS METHOD IS DEPRECATED AND SHOULD NOT BE USED. */ - bool InstanciateProjection() - { - otbWarningMacro( - << "InstanciateProjection has been deprecated. Please use InstanciateProjection() instead"); - return this->InstantiateProjection(); - } - void InverseTransform(double x, double y, double z, double& lon, double& lat, double& h); void ForwardTransform(double lon, double lat, double h, diff --git a/Modules/Applications/AppClassification/app/CMakeLists.txt b/Modules/Applications/AppClassification/app/CMakeLists.txt index 0d1475994c11bb266b43ef15309394172fee38b3..573d730b470310dccc826c1330898839fe9c0f40 100644 --- a/Modules/Applications/AppClassification/app/CMakeLists.txt +++ b/Modules/Applications/AppClassification/app/CMakeLists.txt @@ -60,11 +60,6 @@ otb_create_application( SOURCES otbImageClassifier.cxx LINK_LIBRARIES ${${otb-module}_LIBRARIES}) -otb_create_application( - NAME TrainOGRLayersClassifier - SOURCES otbTrainOGRLayersClassifier.cxx - LINK_LIBRARIES ${${otb-module}_LIBRARIES}) - otb_create_application( NAME TrainVectorClassifier SOURCES otbTrainVectorClassifier.cxx diff --git a/Modules/Applications/AppClassification/app/otbComputeOGRLayersFeaturesStatistics.cxx b/Modules/Applications/AppClassification/app/otbComputeOGRLayersFeaturesStatistics.cxx index 4f33d7a562ca35df6befc2793d223a43a8de4a17..75a39d9d72934db134c9292eef159e74a31cd2bb 100644 --- a/Modules/Applications/AppClassification/app/otbComputeOGRLayersFeaturesStatistics.cxx +++ b/Modules/Applications/AppClassification/app/otbComputeOGRLayersFeaturesStatistics.cxx @@ -55,16 +55,16 @@ private: SetDocLongDescription("Compute statistics (mean and standard deviation) of the features in a set of OGR Layers, and write them in an XML file. This XML file can then be used by the training application."); SetDocLimitations("Experimental. For now only shapefiles are supported."); SetDocAuthors("David Youssefi during internship at CNES"); - SetDocSeeAlso("OGRLayerClassifier,TrainOGRLayersClassifier"); + SetDocSeeAlso("OGRLayerClassifier,TrainVectorClassifier"); AddDocTag(Tags::Segmentation); - AddParameter(ParameterType_InputVectorData, "inshp", "Name of the input shapefile"); + AddParameter(ParameterType_InputVectorData, "inshp", "Vector Data"); SetParameterDescription("inshp","Name of the input shapefile"); - AddParameter(ParameterType_OutputFilename, "outstats", "XML file containing mean and variance of each feature."); + AddParameter(ParameterType_OutputFilename, "outstats", "Output XML file"); SetParameterDescription("outstats", "XML file containing mean and variance of each feature."); - AddParameter(ParameterType_ListView, "feat", "List of features to consider for statistics."); + AddParameter(ParameterType_ListView, "feat", "Feature"); SetParameterDescription("feat","List of features to consider for statistics."); // Doc example parameter settings diff --git a/Modules/Applications/AppClassification/app/otbOGRLayerClassifier.cxx b/Modules/Applications/AppClassification/app/otbOGRLayerClassifier.cxx index 451159863362fbafa6b7a4f2be09e1b6fe9926aa..1add64f9282a18f99226e889858ea189bb2075e6 100644 --- a/Modules/Applications/AppClassification/app/otbOGRLayerClassifier.cxx +++ b/Modules/Applications/AppClassification/app/otbOGRLayerClassifier.cxx @@ -64,7 +64,7 @@ private: SetDocLongDescription("This application will apply a trained machine learning model on the selected feature to get a classification of each geometry contained in an OGR layer. The list of feature must match the list used for training. The predicted label is written in the user defined field for each geometry."); SetDocLimitations("Experimental. Only shapefiles are supported for now."); SetDocAuthors("David Youssefi during internship at CNES"); - SetDocSeeAlso("ComputeOGRLayersFeaturesStatistics,TrainOGRLayersClassifier"); + SetDocSeeAlso("ComputeOGRLayersFeaturesStatistics"); AddDocTag(Tags::Segmentation); AddParameter(ParameterType_InputVectorData, "inshp", "Name of the input shapefile"); @@ -192,10 +192,8 @@ private: typedef otb::LibSVMMachineLearningModel<ValueType,LabelPixelType> LibSVMType; LibSVMType::Pointer libSVMClassifier = LibSVMType::New(); - libSVMClassifier->SetInputListSample(trainingListSample); - libSVMClassifier->SetTargetListSample(trainingLabeledListSample); libSVMClassifier->Load(modelfile); - libSVMClassifier->PredictAll(); + trainingLabeledListSample = libSVMClassifier->PredictBatch(trainingListSample); otb::ogr::DataSource::Pointer source2 = otb::ogr::DataSource::New(shapefile, otb::ogr::DataSource::Modes::Update_LayerUpdate); otb::ogr::Layer layer2 = source2->GetLayer(0); diff --git a/Modules/Applications/AppClassification/app/otbTrainOGRLayersClassifier.cxx b/Modules/Applications/AppClassification/app/otbTrainOGRLayersClassifier.cxx deleted file mode 100644 index d576ed661ec70edd122cf84851e9bc7a503d8018..0000000000000000000000000000000000000000 --- a/Modules/Applications/AppClassification/app/otbTrainOGRLayersClassifier.cxx +++ /dev/null @@ -1,224 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "otbWrapperApplication.h" -#include "otbWrapperApplicationFactory.h" - -#include "otbOGRDataSourceWrapper.h" -#include "otbOGRFeatureWrapper.h" -#include "otbStatisticsXMLFileWriter.h" - -#include "itkVariableLengthVector.h" -#include "otbStatisticsXMLFileReader.h" - -#include "itkListSample.h" -#include "otbShiftScaleSampleListFilter.h" - -#ifdef OTB_USE_LIBSVM -#include "otbLibSVMMachineLearningModel.h" -#endif - -#include <time.h> - -namespace otb -{ -namespace Wrapper -{ -class TrainOGRLayersClassifier : public Application -{ -public: - typedef TrainOGRLayersClassifier Self; - typedef Application Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - itkNewMacro(Self) -; - - itkTypeMacro(TrainOGRLayersClassifier, otb::Application) -; - -private: - void DoInit() ITK_OVERRIDE - { - SetName("TrainOGRLayersClassifier"); - SetDescription("Train a SVM classifier based on labeled geometries and a list of features to consider."); - - SetDocName("TrainOGRLayersClassifier (DEPRECATED)"); - SetDocLongDescription("This application trains a SVM classifier based on " - "labeled geometries and a list of features to consider for classification." - " This application is deprecated, prefer using TrainVectorClassifier which" - " offers access to all the classifiers."); - SetDocLimitations("Experimental. For now only shapefiles are supported. Tuning of SVM classifier is not available."); - SetDocAuthors("David Youssefi during internship at CNES"); - SetDocSeeAlso("OGRLayerClassifier,ComputeOGRLayersFeaturesStatistics"); - AddDocTag(Tags::Segmentation); - - AddParameter(ParameterType_InputVectorData, "inshp", "Name of the input shapefile"); - SetParameterDescription("inshp","Name of the input shapefile"); - - AddParameter(ParameterType_InputFilename, "instats", "XML file containing mean and variance of each feature."); - SetParameterDescription("instats", "XML file containing mean and variance of each feature."); - - AddParameter(ParameterType_OutputFilename, "outsvm", "Output model filename."); - SetParameterDescription("outsvm", "Output model filename."); - - AddParameter(ParameterType_ListView, "feat", "List of features to consider for classification."); - SetParameterDescription("feat","List of features to consider for classification."); - - AddParameter(ParameterType_String,"cfield","Field containing the class id for supervision"); - SetParameterDescription("cfield","Field containing the class id for supervision. Only geometries with this field available will be taken into account."); - SetParameterString("cfield","class", false); - - // Doc example parameter settings - SetDocExampleParameterValue("inshp", "vectorData.shp"); - SetDocExampleParameterValue("instats", "meanVar.xml"); - SetDocExampleParameterValue("outsvm", "svmModel.svm"); - SetDocExampleParameterValue("feat", "perimeter"); - SetDocExampleParameterValue("cfield", "predicted"); - - } - - void DoUpdateParameters() ITK_OVERRIDE - { - if ( HasValue("inshp") ) - { - std::string shapefile = GetParameterString("inshp"); - - otb::ogr::DataSource::Pointer ogrDS; - otb::ogr::Layer layer(ITK_NULLPTR, false); - - OGRSpatialReference oSRS(""); - std::vector<std::string> options; - - ogrDS = otb::ogr::DataSource::New(shapefile, otb::ogr::DataSource::Modes::Read); - std::string layername = itksys::SystemTools::GetFilenameName(shapefile); - layername = layername.substr(0,layername.size()-4); - layer = ogrDS->GetLayer(0); - - otb::ogr::Feature feature = layer.ogr().GetNextFeature(); - ClearChoices("feat"); - for(int iField=0; iField<feature.ogr().GetFieldCount(); iField++) - { - std::string key, item = feature.ogr().GetFieldDefnRef(iField)->GetNameRef(); - key = item; - key.erase(std::remove(key.begin(), key.end(), ' '), key.end()); - std::transform(key.begin(), key.end(), key.begin(), tolower); - key="feat."+key; - AddChoice(key,item); - } - } - } - - void DoExecute() ITK_OVERRIDE - { - #ifdef OTB_USE_LIBSVM - clock_t tic = clock(); - - std::string shapefile = GetParameterString("inshp"); - std::string XMLfile = GetParameterString("instats"); - std::string modelfile = GetParameterString("outsvm"); - - typedef double ValueType; - typedef itk::VariableLengthVector<ValueType> MeasurementType; - typedef itk::Statistics::ListSample <MeasurementType> ListSampleType; - typedef otb::StatisticsXMLFileReader<MeasurementType> StatisticsReader; - - typedef unsigned int LabelPixelType; - typedef itk::FixedArray<LabelPixelType,1> LabelSampleType; - typedef itk::Statistics::ListSample <LabelSampleType> LabelListSampleType; - - typedef otb::Statistics::ShiftScaleSampleListFilter<ListSampleType, ListSampleType> ShiftScaleFilterType; - - StatisticsReader::Pointer statisticsReader = StatisticsReader::New(); - statisticsReader->SetFileName(XMLfile); - - MeasurementType meanMeasurementVector = statisticsReader->GetStatisticVectorByName("mean"); - MeasurementType stddevMeasurementVector = statisticsReader->GetStatisticVectorByName("stddev"); - - otb::ogr::DataSource::Pointer source = otb::ogr::DataSource::New(shapefile, otb::ogr::DataSource::Modes::Read); - otb::ogr::Layer layer = source->GetLayer(0); - bool goesOn = true; - otb::ogr::Feature feature = layer.ogr().GetNextFeature(); - - ListSampleType::Pointer input = ListSampleType::New(); - LabelListSampleType::Pointer target = LabelListSampleType::New(); - const int nbFeatures = GetSelectedItems("feat").size(); - - input->SetMeasurementVectorSize(nbFeatures); - - if(feature.addr()) - while(goesOn) - { - if(feature.ogr().IsFieldSet(feature.ogr().GetFieldIndex(GetParameterString("cfield").c_str()))) - { - MeasurementType mv; mv.SetSize(nbFeatures); - - for(int idx=0; idx < nbFeatures; ++idx) - mv[idx] = feature.ogr().GetFieldAsDouble(GetSelectedItems("feat")[idx]); - - input->PushBack(mv); - target->PushBack(feature.ogr().GetFieldAsInteger(GetParameterString("cfield").c_str())); - } - feature = layer.ogr().GetNextFeature(); - goesOn = feature.addr() != ITK_NULLPTR; - } - - ShiftScaleFilterType::Pointer trainingShiftScaleFilter = ShiftScaleFilterType::New(); - trainingShiftScaleFilter->SetInput(input); - trainingShiftScaleFilter->SetShifts(meanMeasurementVector); - trainingShiftScaleFilter->SetScales(stddevMeasurementVector); - trainingShiftScaleFilter->Update(); - - ListSampleType::Pointer listSample; - LabelListSampleType::Pointer labelListSample; - - listSample = trainingShiftScaleFilter->GetOutput(); - labelListSample = target; - - ListSampleType::Pointer trainingListSample = listSample; - LabelListSampleType::Pointer trainingLabeledListSample = labelListSample; - - typedef otb::LibSVMMachineLearningModel<ValueType,LabelPixelType> LibSVMType; - LibSVMType::Pointer libSVMClassifier = LibSVMType::New(); - libSVMClassifier->SetInputListSample(trainingListSample); - libSVMClassifier->SetTargetListSample(trainingLabeledListSample); - libSVMClassifier->SetParameterOptimization(true); - libSVMClassifier->SetC(1.0); - libSVMClassifier->SetKernelType(LINEAR); - libSVMClassifier->Train(); - libSVMClassifier->Save(modelfile); - - clock_t toc = clock(); - - otbAppLogINFO( "Elapsed: "<< ((double)(toc - tic) / CLOCKS_PER_SEC)<<" seconds."); - - #else - otbAppLogFATAL("Module LIBSVM is not installed. You should consider turning OTB_USE_LIBSVM on during cmake configuration."); - #endif - - } - -}; -} -} - -OTB_APPLICATION_EXPORT(otb::Wrapper::TrainOGRLayersClassifier) - - diff --git a/Modules/Applications/AppClassification/app/otbTrainRegression.cxx b/Modules/Applications/AppClassification/app/otbTrainRegression.cxx index 8c024a9088f631ddfb896b39914db1dbc9692817..0e9fc02dfea39cb3503079848110c7e639a2248d 100644 --- a/Modules/Applications/AppClassification/app/otbTrainRegression.cxx +++ b/Modules/Applications/AppClassification/app/otbTrainRegression.cxx @@ -506,8 +506,6 @@ void DoExecute() ITK_OVERRIDE // Performances estimation //-------------------------- ListSampleType::Pointer performanceListSample; - TargetListSampleType::Pointer predictedList = TargetListSampleType::New(); - predictedList->SetMeasurementVectorSize(1); TargetListSampleType::Pointer performanceLabeledListSample; //Test the input validation set size @@ -523,7 +521,8 @@ void DoExecute() ITK_OVERRIDE performanceLabeledListSample = trainingLabeledListSample; } - this->Classify(performanceListSample, predictedList, GetParameterString("io.out")); + TargetListSampleType::Pointer predictedList = + this->Classify(performanceListSample, GetParameterString("io.out")); otbAppLogINFO("Training performances"); double mse=0.0; diff --git a/Modules/Applications/AppClassification/app/otbTrainVectorClassifier.cxx b/Modules/Applications/AppClassification/app/otbTrainVectorClassifier.cxx index 5d9d3b897594cbd962b0c6b5763c18f21f0f75c4..f24a4f6567aa2887c42ebd2862acce813d64b7b8 100644 --- a/Modules/Applications/AppClassification/app/otbTrainVectorClassifier.cxx +++ b/Modules/Applications/AppClassification/app/otbTrainVectorClassifier.cxx @@ -56,6 +56,16 @@ public: protected: void DoInit() { + SetName( "TrainVectorClassifier" ); + SetDescription( "Train a classifier based on labeled geometries and a list of features to consider." ); + + SetDocName( "Train Vector Classifier" ); + SetDocLongDescription( "This application trains a classifier based on " + "labeled geometries and a list of features to consider for classification." ); + SetDocLimitations( " " ); + SetDocAuthors( "OTB Team" ); + SetDocSeeAlso( " " ); + Superclass::DoInit(); } diff --git a/Modules/Applications/AppClassification/include/otbLearningApplicationBase.h b/Modules/Applications/AppClassification/include/otbLearningApplicationBase.h index 991ee9aa892137f12ee07bdb3b89d15bdbb26d4a..e71be6402140e11227b8c4373dc14cfdb896c7b6 100644 --- a/Modules/Applications/AppClassification/include/otbLearningApplicationBase.h +++ b/Modules/Applications/AppClassification/include/otbLearningApplicationBase.h @@ -130,9 +130,9 @@ protected: 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); + typename TargetListSampleType::Pointer Classify( + typename ListSampleType::Pointer validationListSample, + std::string modelPath); /** Init method that creates all the parameters for machine learning models */ void DoInit() ITK_OVERRIDE; diff --git a/Modules/Applications/AppClassification/include/otbLearningApplicationBase.txx b/Modules/Applications/AppClassification/include/otbLearningApplicationBase.txx index fe4e2d618b20681e8e2ce86cacbf9306f206b8d4..9fc20626d43e71e7795ed25b13d413139db2f1f0 100644 --- a/Modules/Applications/AppClassification/include/otbLearningApplicationBase.txx +++ b/Modules/Applications/AppClassification/include/otbLearningApplicationBase.txx @@ -128,10 +128,10 @@ LearningApplicationBase<TInputValue,TOutputValue> } template <class TInputValue, class TOutputValue> -void +typename LearningApplicationBase<TInputValue,TOutputValue> +::TargetListSampleType::Pointer LearningApplicationBase<TInputValue,TOutputValue> ::Classify(typename ListSampleType::Pointer validationListSample, - typename TargetListSampleType::Pointer predictedList, std::string modelPath) { // Setup fake reporter @@ -152,13 +152,14 @@ LearningApplicationBase<TInputValue,TOutputValue> model->Load(modelPath); model->SetRegressionMode(this->m_RegressionFlag); - model->SetInputListSample(validationListSample); - model->SetTargetListSample(predictedList); - model->PredictAll(); + + typename TargetListSampleType::Pointer predictedList = model->PredictBatch(validationListSample, NULL); // update reporter dummyFilter->UpdateProgress(1.0f); dummyFilter->InvokeEvent(itk::EndEvent()); + + return predictedList; } template <class TInputValue, class TOutputValue> diff --git a/Modules/Applications/AppClassification/include/otbTrainImagesBase.txx b/Modules/Applications/AppClassification/include/otbTrainImagesBase.txx index 243086d2de0a4039b4ce8b04e42cc1168890bc41..deb34bfc735224c66b64ac8a4d3d15d0b98ed7b3 100644 --- a/Modules/Applications/AppClassification/include/otbTrainImagesBase.txx +++ b/Modules/Applications/AppClassification/include/otbTrainImagesBase.txx @@ -196,17 +196,20 @@ TrainImagesBase::SamplingRates TrainImagesBase::ComputeFinalMaximumSamplingRates // only fmt will be used for both training and validation samples // So we try to compute the total number of samples given input // parameters mt, mv and vtr. - if( mt > -1 && mv > -1 ) - { - rates.fmt = mt + mv; - } - if( mt > -1 && mv <= -1 && vtr < 0.99999 ) + if( mt > -1 && vtr < 0.99999 ) { rates.fmt = static_cast<long>(( double ) mt / ( 1.0 - vtr )); } - if( mt <= -1 && mv > -1 && vtr > 0.00001 ) + if( mv > -1 && vtr > 0.00001 ) { - rates.fmt = static_cast<long>(( double ) mv / vtr); + if( rates.fmt > -1 ) + { + rates.fmt = std::min( rates.fmt, static_cast<long>(( double ) mv / vtr) ); + } + else + { + rates.fmt = static_cast<long>(( double ) mv / vtr); + } } } } @@ -228,8 +231,10 @@ void TrainImagesBase::ComputeSamplingRate(const std::vector<std::string> &statis { if( maximum > -1 ) { + std::ostringstream oss; + oss << maximum; GetInternalApplication( "rates" )->SetParameterString( "strategy", "constant", false ); - GetInternalApplication( "rates" )->SetParameterInt( "strategy.constant.nb", static_cast<int>(maximum), false ); + GetInternalApplication( "rates" )->SetParameterString( "strategy.constant.nb", oss.str(), false ); } else { diff --git a/Modules/Applications/AppClassification/include/otbTrainVectorBase.h b/Modules/Applications/AppClassification/include/otbTrainVectorBase.h index f5e87e2943e46801409d3c7c1f00a559b13c5fdb..4abb235b39bc0cbacd18b70e639d0e0c327b7ae0 100644 --- a/Modules/Applications/AppClassification/include/otbTrainVectorBase.h +++ b/Modules/Applications/AppClassification/include/otbTrainVectorBase.h @@ -173,7 +173,7 @@ protected: * Otherwise mean is set to 0 and standard deviation to 1 for each Features. * \param nbFeatures */ - ShiftScaleParameters ComputeStatistics(unsigned int nbFeatures); + ShiftScaleParameters GetStatistics(unsigned int nbFeatures); SamplesWithLabel m_TrainingSamplesWithLabel; SamplesWithLabel m_ClassificationSamplesWithLabel; diff --git a/Modules/Applications/AppClassification/include/otbTrainVectorBase.txx b/Modules/Applications/AppClassification/include/otbTrainVectorBase.txx index 22fb96b47becde7a4461623e9f0f79e9b1240c97..57554baccf5174c0ad084a1e80b99a0d93e5f56c 100644 --- a/Modules/Applications/AppClassification/include/otbTrainVectorBase.txx +++ b/Modules/Applications/AppClassification/include/otbTrainVectorBase.txx @@ -29,16 +29,6 @@ namespace Wrapper void TrainVectorBase::DoInit() { - SetName( "TrainVectorClassifier" ); - SetDescription( "Train a classifier based on labeled geometries and a list of features to consider." ); - - SetDocName( "Train Vector Classifier" ); - SetDocLongDescription( "This application trains a classifier based on " - "labeled geometries and a list of features to consider for classification." ); - SetDocLimitations( " " ); - SetDocAuthors( "OTB Team" ); - SetDocSeeAlso( " " ); - // Common Parameters for all Learning Application AddParameter( ParameterType_Group, "io", "Input and output data" ); SetParameterDescription( "io", "This group of parameters allows setting input and output data." ); @@ -149,7 +139,7 @@ void TrainVectorBase::DoExecute() otbAppLogFATAL( << "No features have been selected to train the classifier on!" ); } - ShiftScaleParameters measurement = ComputeStatistics( m_FeaturesInfo.m_NbFeatures ); + ShiftScaleParameters measurement = GetStatistics( m_FeaturesInfo.m_NbFeatures ); ExtractAllSamples( measurement ); this->Train( m_TrainingSamplesWithLabel.listSample, m_TrainingSamplesWithLabel.labeledListSample, GetParameterString( "io.out" ) ); @@ -202,7 +192,7 @@ TrainVectorBase::ExtractClassificationSamplesWithLabel(const ShiftScaleParameter TrainVectorBase::ShiftScaleParameters -TrainVectorBase::ComputeStatistics(unsigned int nbFeatures) +TrainVectorBase::GetStatistics(unsigned int nbFeatures) { ShiftScaleParameters measurement = ShiftScaleParameters(); if( HasValue( "io.stats" ) && IsParameterEnabled( "io.stats" ) ) diff --git a/Modules/Applications/AppClassification/test/CMakeLists.txt b/Modules/Applications/AppClassification/test/CMakeLists.txt index 9cc991bd3c84573f485fc3cfdf448bb7ebb555ef..698e31b818759f465fc6cfc9c0d3f5e321d89ad9 100644 --- a/Modules/Applications/AppClassification/test/CMakeLists.txt +++ b/Modules/Applications/AppClassification/test/CMakeLists.txt @@ -364,19 +364,6 @@ if(OTB_USE_LIBSVM) endif() -#----------- TrainOGRLayersClassifier TESTS ---------------- -otb_test_application(NAME apTvClTrainOGRLayersClassifier - APP TrainOGRLayersClassifier - OPTIONS -inshp ${INPUTDATA}/Classification/apTvClLabeledVector.shp - -feat meanB0 meanB1 meanB2 meanB3 varB0 varB1 varB2 varB3 - -instats ${TEMP}/apTvClComputeOGRLayersFeaturesStatistics.xml - -outsvm ${TEMP}/apTvClModel.svm - VALID --compare-ascii ${NOTOL} - ${OTBAPP_BASELINE_FILES}/apTvClModel.svm - ${TEMP}/apTvClModel.svm) - -set_tests_properties(apTvClTrainOGRLayersClassifier PROPERTIES DEPENDS apTvClComputeOGRLayersFeaturesStatistics) - #----------- ComputeConfusionMatrix TESTS ---------------- otb_test_application(NAME apTvComputeConfusionMatrixV APP ComputeConfusionMatrix diff --git a/Modules/Applications/AppProjection/app/otbObtainUTMZoneFromGeoPoint.cxx b/Modules/Applications/AppProjection/app/otbObtainUTMZoneFromGeoPoint.cxx index 4918543fde8fcb5baec907452060a9b13eac46f8..7755d65f8cb28d3f7400dcc3bf962c7e5fbefbb6 100644 --- a/Modules/Applications/AppProjection/app/otbObtainUTMZoneFromGeoPoint.cxx +++ b/Modules/Applications/AppProjection/app/otbObtainUTMZoneFromGeoPoint.cxx @@ -21,8 +21,7 @@ #include "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" -#include "otbMapProjections.h" -#include "otbUtils.h" +#include "otbMapProjectionAdapter.h" namespace otb { diff --git a/Modules/Applications/AppSARCalibration/app/CMakeLists.txt b/Modules/Applications/AppSARCalibration/app/CMakeLists.txt index ca6300aed6181e6a5a4b8a37b7080ff2dc58fc05..ee25f98ec2671127a0a8f63a0dcdd0b7942096ef 100644 --- a/Modules/Applications/AppSARCalibration/app/CMakeLists.txt +++ b/Modules/Applications/AppSARCalibration/app/CMakeLists.txt @@ -23,11 +23,6 @@ set(OTBAppSARCalibration_LINK_LIBS ${OTBApplicationEngine_LIBRARIES} ) -otb_create_application( - NAME SarRadiometricCalibration - SOURCES otbSarRadiometricCalibration.cxx - LINK_LIBRARIES ${${otb-module}_LIBRARIES}) - otb_create_application( NAME SARCalibration SOURCES otbSARCalibration.cxx diff --git a/Modules/Applications/AppSARCalibration/app/otbSarRadiometricCalibration.cxx b/Modules/Applications/AppSARCalibration/app/otbSarRadiometricCalibration.cxx deleted file mode 100644 index 1267cb5f7ed2cce9df725ffd0109355caa7c7832..0000000000000000000000000000000000000000 --- a/Modules/Applications/AppSARCalibration/app/otbSarRadiometricCalibration.cxx +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "otbWrapperApplication.h" -#include "otbWrapperApplicationFactory.h" - -#include "otbSarRadiometricCalibrationToImageFilter.h" - -namespace otb -{ -namespace Wrapper -{ -class SarRadiometricCalibration : public Application -{ -public: - /** Standard class typedefs. */ - typedef SarRadiometricCalibration Self; - typedef Application Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** Standard macro */ - itkNewMacro(Self); - - itkTypeMacro(SarRadiometricCalibration, otb::Application); - - typedef otb::SarRadiometricCalibrationToImageFilter<ComplexFloatImageType, - FloatImageType> CalibrationFilterType; - -private: - void DoInit() ITK_OVERRIDE - { - SetName("SarRadiometricCalibration"); - SetDescription("Perform radiometric calibration of SAR images. Following sensors are supported: TerraSAR-X, Sentinel1 and Radarsat-2.Both Single Look Complex(SLC) and detected products are supported as input.\n"); - - // Documentation - SetDocName("SAR Radiometric calibration (DEPRECATED)"); - SetDocLongDescription("The objective of SAR calibration is to provide imagery in which the pixel values can be directly related to the radar backscatter of the scene. This application allows computing Sigma Naught (Radiometric Calibration) for TerraSAR-X, Sentinel1 L1 and Radarsat-2 sensors. Metadata are automatically retrieved from image products.The application supports complex and non-complex images (SLC or detected products).\n"); - SetDocLimitations("None"); - SetDocAuthors("OTB-Team"); - SetDocSeeAlso(" "); - - AddDocTag(Tags::Calibration); - AddDocTag(Tags::SAR); - - AddParameter(ParameterType_ComplexInputImage, "in", "Input Image"); - SetParameterDescription("in", "Input complex image"); - - AddParameter(ParameterType_OutputImage, "out", "Output Image"); - SetParameterDescription("out", "Output calibrated image. This image contains the backscatter (sigmaNought) of the input image."); - - AddRAMParameter(); - - AddParameter(ParameterType_Empty, "noise", "Disable Noise"); - SetParameterDescription("noise", "Flag to disable noise. For 5.2.0 release, the noise values are only read by TerraSARX product."); - MandatoryOff("noise"); - - AddParameter(ParameterType_Choice, "lut", "Lookup table sigma /gamma/ beta/ DN."); - SetParameterDescription("lut", "Lookup table values are not available with all SAR products. Products that provide lookup table with metadata are: Sentinel1, Radarsat2."); - AddChoice("lut.sigma", "Use sigma nought lookup"); - SetParameterDescription("lut.sigma","Use Sigma nought lookup value from product metadata"); - AddChoice("lut.gamma", "Use gamma nought lookup"); - SetParameterDescription("lut.gamma","Use Gamma nought lookup value from product metadata"); - AddChoice("lut.beta", "Use beta nought lookup"); - SetParameterDescription("lut.beta","Use Beta nought lookup value from product metadata"); - AddChoice("lut.dn", "Use DN value lookup"); - SetParameterDescription("lut.dn","Use DN value lookup value from product metadata"); - SetDefaultParameterInt("lut", 0); - - // Doc example parameter settings - SetDocExampleParameterValue("in", "RSAT_imagery_HH.tif"); - SetDocExampleParameterValue("out", "SarRadiometricCalibration.tif" ); - } - - void DoUpdateParameters() ITK_OVERRIDE - { - - } - - void DoExecute() ITK_OVERRIDE - { - otbAppLogWARNING("This application is deprecated, it will be renamed in next" - " version of OTB. Please consider using the renamed copy SARCalibration." - " Parameters and behaviour are identic."); - // Get the input complex image - ComplexFloatImageType* floatComplexImage = GetParameterComplexFloatImage("in"); - - // Set the filer input - m_CalibrationFilter = CalibrationFilterType::New(); - m_CalibrationFilter->SetInput(floatComplexImage); - - if (IsParameterEnabled("noise")) - { - m_CalibrationFilter->SetEnableNoise(false); - } - - short lut = 0; - - lut = GetParameterInt("lut"); - - m_CalibrationFilter->SetLookupSelected(lut); - - // Set the output image - SetParameterOutputImage("out", m_CalibrationFilter->GetOutput()); - - } - - CalibrationFilterType::Pointer m_CalibrationFilter; - -}; -} -} - -OTB_APPLICATION_EXPORT(otb::Wrapper::SarRadiometricCalibration) diff --git a/Modules/Applications/AppSARCalibration/test/CMakeLists.txt b/Modules/Applications/AppSARCalibration/test/CMakeLists.txt index dd7af0a5e2ef556aca6d046f09713954e5233ae8..1ca0afb569f058654d1df161432d920c8eb66df2 100644 --- a/Modules/Applications/AppSARCalibration/test/CMakeLists.txt +++ b/Modules/Applications/AppSARCalibration/test/CMakeLists.txt @@ -19,8 +19,8 @@ # otb_module_test() -#----------- SarRadiometricCalibration TESTS ---------------- -otb_test_application(NAME apTvRaSarRadiometricCalibration_SENTINEL1 +#----------- SARCalibration TESTS ---------------- +otb_test_application(NAME apTvRaSARCalibration_SENTINEL1 APP SARCalibration OPTIONS -in ${INPUTDATA}/SENTINEL1_SLC_S6_1S_extract_1200_1100_300_300.tiff?&geom=${INPUTDATA}/SENTINEL1_SLC_S6_1S_extract_1200_1100_300_300.geom -out ${TEMP}/apTvRaSarRadiometricCalibration_SENTINEL1.tif @@ -29,7 +29,7 @@ otb_test_application(NAME apTvRaSarRadiometricCalibration_SENTINEL1 ${TEMP}/apTvRaSarRadiometricCalibration_SENTINEL1.tif ) if(OTB_DATA_USE_LARGEINPUT) - otb_test_application(NAME apTvRaSarRadiometricCalibration_SENTINEL1_PRODUCT_INPUT + otb_test_application(NAME apTvRaSARCalibration_SENTINEL1_PRODUCT_INPUT APP SARCalibration OPTIONS -in LARGEINPUT{SENTINEL1/S1A_S6_SLC__1SSV_20150619T195043/measurement/s1a-s6-slc-vv-20150619t195043-20150619t195101-006447-00887d-001.tiff} -out "${TEMP}/apTvRaSarRadiometricCalibration_SENTINEL1_PRODUCT_INPUT.tif?box=1200:1100:256:256" @@ -38,7 +38,7 @@ if(OTB_DATA_USE_LARGEINPUT) ${TEMP}/apTvRaSarRadiometricCalibration_SENTINEL1_PRODUCT_INPUT.tif ) endif() -otb_test_application(NAME apTvRaSarRadiometricCalibration_RADARSAT2 +otb_test_application(NAME apTvRaSARCalibration_RADARSAT2 APP SARCalibration OPTIONS -in ${INPUTDATA}/RADARSAT2_ALTONA_300_300_VV.tif?&geom=${INPUTDATA}/RADARSAT2_ALTONA_300_300_VV.geom -out ${TEMP}/apTvRaSarRadiometricCalibration_RADARSAT2.tif diff --git a/Modules/Core/Common/include/otbImageAndVectorImageOperationFilter.h b/Modules/Core/Common/include/otbImageAndVectorImageOperationFilter.h index dcb06b8e0637378628726235004a5e95540df801..d5e32b6564fe7903723d88f76a903395f99fd673 100644 --- a/Modules/Core/Common/include/otbImageAndVectorImageOperationFilter.h +++ b/Modules/Core/Common/include/otbImageAndVectorImageOperationFilter.h @@ -176,14 +176,6 @@ public: itkGetMacro(UseDivision, bool); itkGetMacro(UseSubtraction, bool); - /** THIS METHOD IS DEPRECATED AND SHOULD NOT BE USED. */ - virtual bool GetUseSubstraction() - { - otbWarningMacro( - << "GetUseSubstraction has been deprecated. Please use GetUseSubtraction() instead"); - return GetUseSubtraction(); - } - void UseAddition() { m_UseAddition = true; diff --git a/Modules/Core/Common/include/otbSystem.h b/Modules/Core/Common/include/otbSystem.h index 1a009cc805627c0ea68620c1f6e63fe153d28885..87d22f93794bd39c4653ee06225c5aee50bd6f5f 100644 --- a/Modules/Core/Common/include/otbSystem.h +++ b/Modules/Core/Common/include/otbSystem.h @@ -61,13 +61,6 @@ public: /** Parse a filename with additional information */ static bool ParseFileNameForAdditionalInfo(const std::string& id, std::string& file, unsigned int& addNum); - - /** THIS METHOD IS DEPRECATED AND SHOULD NOT BE USED. use -* ParseFileNameForAdditionalInfo instead*/ - static bool ParseFileNameForAdditonalInfo (const std::string& id, std::string& file, unsigned int& addNum) - { - return ParseFileNameForAdditionalInfo(id, file, addNum); - } }; } // namespace otb diff --git a/Modules/Core/Common/include/otbUtils.h b/Modules/Core/Common/include/otbUtils.h index 7b1b21f4ded2f7074ff8cbc9b9594b0951c9764c..da2ecc286ed4abf8e175a700b69f9e14a8483fb4 100644 --- a/Modules/Core/Common/include/otbUtils.h +++ b/Modules/Core/Common/include/otbUtils.h @@ -48,6 +48,9 @@ namespace Utils return s.str(); } + /** Function that prints nothing (useful to disable libsvm logs)*/ + void OTBCommon_EXPORT PrintNothing(const char *s); + } } // namespace otb diff --git a/Modules/Core/Common/src/otbUtils.cxx b/Modules/Core/Common/src/otbUtils.cxx index 533a599caacc5a026627cebad2ad8328ddb3abb0..f837789ba6ee406bb6739f527dc2ef103f780f9a 100644 --- a/Modules/Core/Common/src/otbUtils.cxx +++ b/Modules/Core/Common/src/otbUtils.cxx @@ -37,6 +37,10 @@ bool IsLonLatValid(double lon, double lat) return true; } +void PrintNothing(const char * /* s */) +{ +} + } } diff --git a/Modules/Core/Transform/include/otbGenericMapProjection.h b/Modules/Core/Transform/include/otbGenericMapProjection.h index fa1c8fac33fe700b459f425795268326b6b52403..d7030760b47399069b2b16309ce06847b04a1d40 100644 --- a/Modules/Core/Transform/include/otbGenericMapProjection.h +++ b/Modules/Core/Transform/include/otbGenericMapProjection.h @@ -102,14 +102,6 @@ public: virtual bool InstantiateProjection(); - /** THIS METHOD IS DEPRECATED AND SHOULD NOT BE USED. */ - virtual bool InstanciateProjection() - { - otbWarningMacro( - << "InstanciateProjection has been deprecated. Please use InstantiateProjection() instead"); - return this->InstantiateProjection(); - } - const MapProjectionAdapter* GetMapProjection() const; virtual bool IsProjectionDefined() const; diff --git a/Modules/Core/Transform/include/otbGenericRSTransform.h b/Modules/Core/Transform/include/otbGenericRSTransform.h index 3e734dab4a7ba7b3a053a86b6e8e42736616ffdf..09a8ed37867f476b0e28c6632680a437f712748a 100644 --- a/Modules/Core/Transform/include/otbGenericRSTransform.h +++ b/Modules/Core/Transform/include/otbGenericRSTransform.h @@ -171,13 +171,6 @@ public: OutputPointType TransformPoint(const InputPointType& point) const ITK_OVERRIDE; virtual void InstantiateTransform(); - - /** THIS METHOD IS DEPRECATED AND SHOULD NOT BE USED. */ - void InstanciateTransform() - { - otbWarningMacro(<< "InstanciateTransform has been deprecated. Please use InstantiateTransform instead"); - this->InstantiateTransform(); - } // Get inverse methods bool GetInverse(Self * inverseTransform) const; diff --git a/Modules/Core/Transform/include/otbStreamingWarpImageFilter.h b/Modules/Core/Transform/include/otbStreamingWarpImageFilter.h index ade6a29676a7cb5623ea8a080893ff01e68291e4..ee6c50cf54cadde092cdb603e7020d74aa92bf6b 100644 --- a/Modules/Core/Transform/include/otbStreamingWarpImageFilter.h +++ b/Modules/Core/Transform/include/otbStreamingWarpImageFilter.h @@ -21,14 +21,14 @@ #ifndef otbStreamingWarpImageFilter_h #define otbStreamingWarpImageFilter_h -#include "otbWarpImageFilter.h" +#include "itkWarpImageFilter.h" #include "otbStreamingTraits.h" namespace otb { /** \class StreamingWarpImageFilter - * \brief This class acts like the otb::WarpImageFilter, but it does not request the largest possible region of the image to warp. + * \brief This class acts like the itk::WarpImageFilter, but it does not request the largest possible region of the image to warp. * * Instead, the user should assess the maximum displacement in the displacement field and set it via the SetMaximumDisplacement() method. * @@ -50,12 +50,12 @@ namespace otb template <class TInputImage, class TOutputImage, class TDisplacementField> class ITK_EXPORT StreamingWarpImageFilter - : public otb::WarpImageFilter<TInputImage, TOutputImage, TDisplacementField> + : public itk::WarpImageFilter<TInputImage, TOutputImage, TDisplacementField> { public: /** Standard class typedefs. */ typedef StreamingWarpImageFilter Self; - typedef otb::WarpImageFilter<TInputImage, TOutputImage, TDisplacementField> Superclass; + typedef itk::WarpImageFilter<TInputImage, TOutputImage, TDisplacementField> Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; diff --git a/Modules/Core/Transform/include/otbStreamingWarpImageFilter.txx b/Modules/Core/Transform/include/otbStreamingWarpImageFilter.txx index eca2711fc238cf8271992b09e527dd6f06f18449..60dc825d3db73c67f68d62713a93e9c5b82c3ec6 100644 --- a/Modules/Core/Transform/include/otbStreamingWarpImageFilter.txx +++ b/Modules/Core/Transform/include/otbStreamingWarpImageFilter.txx @@ -44,6 +44,8 @@ void StreamingWarpImageFilter<TInputImage, TOutputImage, TDisplacementField> ::GenerateInputRequestedRegion() { + Superclass::GenerateInputRequestedRegion(); + // Get the input and displacement field pointers InputImageType * inputPtr = const_cast<InputImageType *>(this->GetInput()); @@ -228,6 +230,11 @@ StreamingWarpImageFilter<TInputImage, TOutputImage, TDisplacementField> noDataValue.resize(this->GetOutput()->GetNumberOfComponentsPerPixel(),0.0); } PixelType edgePadding = this->GetEdgePaddingValue(); + if (itk::NumericTraits<PixelType>::GetLength(edgePadding) != this->GetOutput()->GetNumberOfComponentsPerPixel()) + { + itk::NumericTraits<PixelType>::SetLength(edgePadding,this->GetOutput()->GetNumberOfComponentsPerPixel()); + this->SetEdgePaddingValue(edgePadding); + } for (unsigned int i=0; i<noDataValueAvailable.size() ; ++i) { if (!noDataValueAvailable[i]) diff --git a/Modules/Core/Transform/test/otbStreamingWarpImageFilter.cxx b/Modules/Core/Transform/test/otbStreamingWarpImageFilter.cxx index b3a28dee2845bc5c3e7ab4661d96f8c70e6f1987..3f075a782944bab9cff0dbf4b23a8ea8dd86da23 100644 --- a/Modules/Core/Transform/test/otbStreamingWarpImageFilter.cxx +++ b/Modules/Core/Transform/test/otbStreamingWarpImageFilter.cxx @@ -46,6 +46,10 @@ int otbStreamingWarpImageFilter(int argc, char* argv[]) typedef itk::Vector<PixelType, 2> DisplacementValueType; typedef otb::Image<DisplacementValueType, Dimension> DisplacementFieldType; + // Change default output origin + ImageType::PointType origin; + origin.Fill(0.5); + // Warper typedef otb::StreamingWarpImageFilter<ImageType, ImageType, DisplacementFieldType> ImageWarperType; @@ -70,6 +74,7 @@ int otbStreamingWarpImageFilter(int argc, char* argv[]) warper->SetMaximumDisplacement(maxDisplacement); warper->SetInput(reader->GetOutput()); warper->SetDisplacementField(displacementReader->GetOutput()); + warper->SetOutputOrigin(origin); // Writing writer->SetInput(warper->GetOutput()); diff --git a/Modules/Core/VectorDataBase/include/otbPolygon.h b/Modules/Core/VectorDataBase/include/otbPolygon.h index 7af5337034e1507aa300257e655882ea1e3587c1..a85c8a138a1c8e4e68a32141b02b170f7c2c50ef 100644 --- a/Modules/Core/VectorDataBase/include/otbPolygon.h +++ b/Modules/Core/VectorDataBase/include/otbPolygon.h @@ -122,16 +122,6 @@ public: */ virtual double GetArea() const; - /** - * Return the polygon area. - * \return The area. - * \deprecated - */ - virtual double GetSurface() const - { - return this->GetArea(); - } - /** * Return the polygon length (perimeter). * \return The length. diff --git a/Modules/Learning/SVMLearning/include/otbObjectDetectionClassifier.h b/Modules/Detection/ObjectDetection/include/otbObjectDetectionClassifier.h similarity index 92% rename from Modules/Learning/SVMLearning/include/otbObjectDetectionClassifier.h rename to Modules/Detection/ObjectDetection/include/otbObjectDetectionClassifier.h index 1fe2ac9f00d6b4b98bb58d49f46ce4e8898f6eab..c051b33997673d423c5c306dc0b6aa2026313c9c 100644 --- a/Modules/Learning/SVMLearning/include/otbObjectDetectionClassifier.h +++ b/Modules/Detection/ObjectDetection/include/otbObjectDetectionClassifier.h @@ -32,7 +32,7 @@ #include "itkFunctionBase.h" #include "otbVectorData.h" -#include "otbSVMModel.h" +#include "otbMachineLearningModel.h" #include "otbPersistentImageFilter.h" #include "otbPersistentFilterStreamingDecorator.h" @@ -54,7 +54,7 @@ public: * plus the ThreadedGenerateData function implementing the image function evaluation * * - * \ingroup OTBSVMLearning + * \ingroup OTBObjectDetection */ template <class TInputImage, class TOutputVectorData, class TLabel, class TFunctionType> class ITK_EXPORT PersistentObjectDetectionClassifier : @@ -117,9 +117,9 @@ public: /** TLabel output */ typedef TLabel LabelType; - typedef SVMModel<DescriptorPrecision, LabelType> SVMModelType; - typedef typename SVMModelType::Pointer SVMModelPointerType; - typedef typename SVMModelType::MeasurementType SVMModelMeasurementType; + typedef MachineLearningModel<DescriptorPrecision, LabelType> ModelType; + typedef typename ModelType::Pointer ModelPointerType; + typedef typename ModelType::InputSampleType ModelMeasurementType; typedef itk::Statistics::ListSample<DescriptorType> ListSampleType; @@ -128,8 +128,10 @@ public: this->Superclass::AddInput(dataObject); } - /** SVM model used for classification */ - void SetSVMModel(SVMModelType * model); + /** learning model used for classification */ + void SetModel(ModelType * model); + + const ModelType* GetModel(void) const; VectorDataType* GetOutputVectorData(void); @@ -235,13 +237,16 @@ private: /** Step of the detection grid */ unsigned int m_GridStep; + /** classification model */ + ModelPointerType m_Model; + }; /** \class ObjectDetectionClassifier - * \brief This class detects object in an image, given a SVM model and a local descriptors function + * \brief This class detects object in an image, given a ML model and a local descriptors function * - * Given an image (by SetInputImage()), a SVM model (by SetSVMModel) and an local descriptors ImageFunction + * Given an image (by SetInputImage()), a ML model (by SetModel) and an local descriptors ImageFunction * (set by SetDescriptorsFunction()), this class computes the local descriptors on a regular grid * over the image, and evaluates the class label of the corresponding sample. * It outputs a vector data with the points for which the descriptors are not classified as "negative", @@ -249,7 +254,7 @@ private: * * This class is streaming capable and multithreaded * - * \ingroup OTBSVMLearning + * \ingroup OTBObjectDetection */ template <class TInputImage, class TOutputVectorData, class TLabel, class TFunctionPrecision = double, class TCoordRep = double> class ITK_EXPORT ObjectDetectionClassifier : @@ -299,8 +304,8 @@ public: typedef typename Superclass::FilterType PersistentFilterType; - typedef typename PersistentFilterType::SVMModelType SVMModelType; - typedef typename PersistentFilterType::SVMModelPointerType SVMModelPointerType; + typedef typename PersistentFilterType::ModelType ModelType; + typedef typename PersistentFilterType::ModelPointerType ModelPointerType; /** Input image to extract feature */ void SetInputImage(InputImageType* input) @@ -332,15 +337,15 @@ public: } /** The function to evaluate */ - void SetSVMModel(SVMModelType* model) + void SetModel(ModelType* model) { - this->GetFilter()->SetSVMModel(model); + this->GetFilter()->SetModel(model); } - /** The function to evaluate */ - SVMModelType* GetSVMModel() + /** The classification model */ + const ModelType* GetModel() { - return this->GetFilter()->GetSVMModel(); + return this->GetFilter()->GetModel(); } otbSetObjectMemberMacro(Filter, NeighborhoodRadius, unsigned int); diff --git a/Modules/Learning/SVMLearning/include/otbObjectDetectionClassifier.txx b/Modules/Detection/ObjectDetection/include/otbObjectDetectionClassifier.txx similarity index 93% rename from Modules/Learning/SVMLearning/include/otbObjectDetectionClassifier.txx rename to Modules/Detection/ObjectDetection/include/otbObjectDetectionClassifier.txx index 6b6c12034dc7e06b1da0ca52e5cc25ef3792538b..884cf3f07645b43b1dd0b6f93ce1c9a92ff4b9a6 100644 --- a/Modules/Learning/SVMLearning/include/otbObjectDetectionClassifier.txx +++ b/Modules/Detection/ObjectDetection/include/otbObjectDetectionClassifier.txx @@ -36,8 +36,7 @@ PersistentObjectDetectionClassifier<TInputImage, TOutputVectorData, TLabel, TFun m_NoClassLabel(0), m_GridStep(10) { - // Need 2 inputs : a vector image, and a SVMModel - this->SetNumberOfRequiredInputs(2); + this->SetNumberOfRequiredInputs(1); // Have 2 outputs : the image created by Superclass, a vector data with points this->SetNumberOfRequiredOutputs(3); @@ -84,9 +83,21 @@ PersistentObjectDetectionClassifier<TInputImage, TOutputVectorData, TLabel, TFun template <class TInputImage, class TOutputVectorData, class TLabel, class TFunctionType> void PersistentObjectDetectionClassifier<TInputImage, TOutputVectorData, TLabel, TFunctionType> -::SetSVMModel(SVMModelType* model) +::SetModel(ModelType* model) { - this->SetNthInput(1, model); + if (model != m_Model) + { + m_Model = model; + this->Modified(); + } +} + +template <class TInputImage, class TOutputVectorData, class TLabel, class TFunctionType> +const typename PersistentObjectDetectionClassifier<TInputImage, TOutputVectorData, TLabel, TFunctionType>::ModelType* +PersistentObjectDetectionClassifier<TInputImage, TOutputVectorData, TLabel, TFunctionType> +::GetModel(void) const +{ + return m_Model; } template <class TInputImage, class TOutputVectorData, class TLabel, class TFunctionType> @@ -245,7 +256,7 @@ PersistentObjectDetectionClassifier<TInputImage, TOutputVectorData, TLabel, TFun itk::ThreadIdType threadId) { InputImageType* input = static_cast<InputImageType*>(this->itk::ProcessObject::GetInput(0)); - SVMModelType* model = static_cast<SVMModelType*>(this->itk::ProcessObject::GetInput(1)); + const ModelType* model = this->GetModel(); typedef typename RegionType::IndexType IndexType; IndexType begin = outputRegionForThread.GetIndex(); @@ -266,12 +277,12 @@ PersistentObjectDetectionClassifier<TInputImage, TOutputVectorData, TLabel, TFun input->TransformIndexToPhysicalPoint(current, point); DescriptorType descriptor = m_DescriptorsFunction->Evaluate(point); - SVMModelMeasurementType modelMeasurement(descriptor.GetSize()); + ModelMeasurementType modelMeasurement(descriptor.GetSize()); for (unsigned int i = 0; i < descriptor.GetSize(); ++i) { modelMeasurement[i] = (descriptor[i] - m_Shifts[i]) * m_InvertedScales[i]; } - LabelType label = model->EvaluateLabel(modelMeasurement); + LabelType label = (model->Predict(modelMeasurement))[0]; if (label != m_NoClassLabel) { diff --git a/Modules/Detection/ObjectDetection/otb-module.cmake b/Modules/Detection/ObjectDetection/otb-module.cmake index e7cde79ffbc1c1460bff1b11020d5748cd1f18a6..40728f4ab1f9c138123dbc2bcace6633e9c9dba3 100644 --- a/Modules/Detection/ObjectDetection/otb-module.cmake +++ b/Modules/Detection/ObjectDetection/otb-module.cmake @@ -30,13 +30,14 @@ otb_module(OTBObjectDetection OTBObjectList OTBStatistics OTBStreaming + OTBSupervised OTBTextures OTBVectorDataBase TEST_DEPENDS OTBIOXML OTBImageIO - OTBSVMLearning + OTBLibSVM OTBTestKernel OTBVectorDataIO diff --git a/Modules/Detection/ObjectDetection/test/CMakeLists.txt b/Modules/Detection/ObjectDetection/test/CMakeLists.txt index 88857c53f7d956c1eae4b5a89afcb326839dabb1..3408fe2a0eb5d1e9225599e2e043c77807a1da60 100644 --- a/Modules/Detection/ObjectDetection/test/CMakeLists.txt +++ b/Modules/Detection/ObjectDetection/test/CMakeLists.txt @@ -25,6 +25,7 @@ otbObjectDetectionTestDriver.cxx otbLabeledSampleLocalizationGenerator.cxx otbStandardMetaImageFunctionBuilder.cxx otbDescriptorsListSampleGenerator.cxx +otbObjectDetectionClassifier.cxx ) add_executable(otbObjectDetectionTestDriver ${OTBObjectDetectionTests}) @@ -97,3 +98,32 @@ otb_add_test(NAME odTuDescriptorsListSampleGeneratorNew COMMAND otbObjectDetecti otbDescriptorsListSampleGeneratorNew ) +otb_add_test(NAME odTuObjectDetectionClassifierNew COMMAND otbObjectDetectionTestDriver + otbObjectDetectionClassifierNew + ) + +otb_add_test(NAME odTvObjectDetectionClassifierStreaming COMMAND otbObjectDetectionTestDriver + --compare-ascii ${NOTOL} + ${BASELINE_FILES}/TvObjectDetectionClassifierOutput.txt + ${TEMP}/TvObjectDetectionClassifierOutputStreaming.txt + otbObjectDetectionClassifier + ${INPUTDATA}/ObjectReco/Boats/maur_B010202_01_extract_amplitude.tif + ${INPUTDATA}/ObjectReco/Boats/FeatureStats_RadiometricMoments_amplitude.xml + ${BASELINE_FILES}/TvDescriptorsSVMModelCreation.svm + ${TEMP}/TvObjectDetectionClassifierOutputStreaming.txt + 50 # streaming + 5 # neighborhood radius + ) + +otb_add_test(NAME odTvObjectDetectionClassifier COMMAND otbObjectDetectionTestDriver + --compare-ascii ${NOTOL} + ${BASELINE_FILES}/TvObjectDetectionClassifierOutput.txt + ${TEMP}/TvObjectDetectionClassifierOutput.txt + otbObjectDetectionClassifier + ${INPUTDATA}/ObjectReco/Boats/maur_B010202_01_extract_amplitude.tif + ${INPUTDATA}/ObjectReco/Boats/FeatureStats_RadiometricMoments_amplitude.xml + ${BASELINE_FILES}/TvDescriptorsSVMModelCreation.svm + ${TEMP}/TvObjectDetectionClassifierOutput.txt + 0 # streaming + 5 # neighborhood radius + ) diff --git a/Modules/Detection/ObjectDetection/test/otbDescriptorsListSampleGenerator.cxx b/Modules/Detection/ObjectDetection/test/otbDescriptorsListSampleGenerator.cxx index 66ae810d6a78fc92a0d73929bdcd49913c0b8252..2996c1ef79cc5866379db747dd7b2e030ff23e0a 100644 --- a/Modules/Detection/ObjectDetection/test/otbDescriptorsListSampleGenerator.cxx +++ b/Modules/Detection/ObjectDetection/test/otbDescriptorsListSampleGenerator.cxx @@ -17,9 +17,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - - - #include <iterator> #include "otbImage.h" @@ -31,7 +28,7 @@ #include "otbStatisticsXMLFileReader.h" #include "otbShiftScaleSampleListFilter.h" -#include "otbSVMSampleListModelEstimator.h" +#include "otbLibSVMMachineLearningModel.h" const unsigned int Dimension = 2; typedef int LabelType; @@ -60,17 +57,10 @@ typedef otb::DescriptorsListSampleGenerator typedef otb::ImageFileReader<ImageType> ImageReaderType; typedef otb::VectorDataFileReader<VectorDataType> VectorDataReaderType; -typedef otb::Functor::VariableLengthVectorToMeasurementVectorFunctor<SampleType> - MeasurementVectorFunctorType; - typedef otb::StatisticsXMLFileReader<SampleType> StatisticsReader; typedef otb::Statistics::ShiftScaleSampleListFilter<ListSampleType> ShiftScaleListSampleFilterType; -typedef otb::SVMSampleListModelEstimator< - ListSampleType, - LabelListSampleType, - MeasurementVectorFunctorType> SVMEstimatorType; - +typedef otb::LibSVMMachineLearningModel<FunctionPrecisionType, LabelType> SVMType; typedef FunctionType::PointType PointType; typedef DescriptorsListSampleGeneratorType::SamplesPositionType SamplesPositionType; @@ -243,11 +233,11 @@ int otbDescriptorsSVMModelCreation(int argc, char* argv[]) shiftscaleFilter->SetScales(varianceMeasurentVector); shiftscaleFilter->Update(); - SVMEstimatorType::Pointer svmEstimator = SVMEstimatorType::New(); - svmEstimator->SetInputSampleList(shiftscaleFilter->GetOutput()); - svmEstimator->SetTrainingSampleList(descriptorsGenerator->GetLabelListSample()); - svmEstimator->Update(); - svmEstimator->GetModel()->SaveModel(outputFileName); + SVMType::Pointer svmEstimator = SVMType::New(); + svmEstimator->SetInputListSample(shiftscaleFilter->GetOutput()); + svmEstimator->SetTargetListSample(descriptorsGenerator->GetLabelListSample()); + svmEstimator->Train(); + svmEstimator->Save(outputFileName); return EXIT_SUCCESS; } diff --git a/Modules/Learning/SVMLearning/test/otbObjectDetectionClassifier.cxx b/Modules/Detection/ObjectDetection/test/otbObjectDetectionClassifier.cxx similarity index 95% rename from Modules/Learning/SVMLearning/test/otbObjectDetectionClassifier.cxx rename to Modules/Detection/ObjectDetection/test/otbObjectDetectionClassifier.cxx index 011310acc46985fc4fe7ba48070d12a22605b626..8d12d62a618130ad4524ad274a74d5c197259d8f 100644 --- a/Modules/Learning/SVMLearning/test/otbObjectDetectionClassifier.cxx +++ b/Modules/Detection/ObjectDetection/test/otbObjectDetectionClassifier.cxx @@ -32,6 +32,7 @@ #include "otbImageFunctionAdaptor.h" #include "otbStatisticsXMLFileReader.h" #include "itkPreOrderTreeIterator.h" +#include "otbLibSVMMachineLearningModel.h" const unsigned int Dimension = 2; typedef int LabelType; @@ -56,8 +57,8 @@ typedef otb::ImageFunctionAdaptor<FunctionType, FunctionPrecisionType> AdaptedF typedef otb::ImageFileReader<ImageType> ImageReaderType; -typedef ObjectDetectionClassifierType::SVMModelType SVMModelType; -typedef ObjectDetectionClassifierType::SVMModelPointerType SVMModelPointerType; +typedef otb::LibSVMMachineLearningModel<PixelType,LabelType> SVMModelType; +typedef SVMModelType::Pointer SVMModelPointerType; typedef otb::StatisticsXMLFileReader<AdaptedFunctionType::OutputType> StatisticsXMLFileReaderType; @@ -118,7 +119,7 @@ int otbObjectDetectionClassifier(int argc, char* argv[]) SVMModelPointerType svmModel = SVMModelType::New(); - svmModel->LoadModel(inputSVMModel); + svmModel->Load(inputSVMModel); AdaptedFunctionType::Pointer descriptorsFunction = AdaptedFunctionType::New(); descriptorsFunction->SetInputImage(imageReader->GetOutput()); @@ -127,7 +128,7 @@ int otbObjectDetectionClassifier(int argc, char* argv[]) ObjectDetectionClassifierType::Pointer classifier = ObjectDetectionClassifierType::New(); classifier->SetInputImage(imageReader->GetOutput()); classifier->SetNeighborhoodRadius(neighborhood); - classifier->SetSVMModel(svmModel); + classifier->SetModel(svmModel); classifier->SetDescriptorsFunction(descriptorsFunction); classifier->SetNoClassLabel(0); classifier->SetClassKey("Class"); diff --git a/Modules/Detection/ObjectDetection/test/otbObjectDetectionTestDriver.cxx b/Modules/Detection/ObjectDetection/test/otbObjectDetectionTestDriver.cxx index 055b0aa4b871bfefd76f6804eb8619f162b24591..afed2f209e643e5dde468565067defbfcc18175e 100644 --- a/Modules/Detection/ObjectDetection/test/otbObjectDetectionTestDriver.cxx +++ b/Modules/Detection/ObjectDetection/test/otbObjectDetectionTestDriver.cxx @@ -29,4 +29,6 @@ void RegisterTests() REGISTER_TEST(otbDescriptorsListSampleGeneratorNew); REGISTER_TEST(otbDescriptorsListSampleGenerator); REGISTER_TEST(otbDescriptorsSVMModelCreation); + REGISTER_TEST(otbObjectDetectionClassifierNew); + REGISTER_TEST(otbObjectDetectionClassifier); } diff --git a/Modules/Feature/Edge/include/otbAssymmetricFusionOfLineDetectorImageFilter.h b/Modules/Feature/Edge/include/otbAssymmetricFusionOfLineDetectorImageFilter.h deleted file mode 100644 index 58999b47bb9f98c26380106553f271f8ddc07749..0000000000000000000000000000000000000000 --- a/Modules/Feature/Edge/include/otbAssymmetricFusionOfLineDetectorImageFilter.h +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef otbAssymmetricFusionOfLineDetectorImageFilter_h -#define otbAssymmetricFusionOfLineDetectorImageFilter_h - -#include "itkImageToImageFilter.h" - -#include "otbLineRatioDetectorImageFilter.h" -#include "otbLineCorrelationDetectorImageFilter.h" -#include "otbAssociativeSymmetricalSumImageFilter.h" - -#include "vcl_deprecated_header.h" - -namespace otb -{ - -/** \class AssymmetricFusionOfLineDetectorImageFilter - * - * This class implements a composite filter that combines three filters: - * two filters of line detector ( a line detector by ratio and a line - * detector by croos-correlation) and a filter that produces a fusion of - * those two line detector filters. - * - * - * \ingroup OTBEdge - */ - -template <class TInputImage, - class TOutputImage, - class TOutputImageDirection = TOutputImage, - class TInterpolator = itk::LinearInterpolateImageFunction<TInputImage> > -class ITK_EXPORT AssymmetricFusionOfLineDetectorImageFilter : - public LineDetectorImageFilterBase<TInputImage, TOutputImage, TOutputImageDirection, TInterpolator> -{ -public: - - itkStaticConstMacro(InputImageDimension, - unsigned int, - TInputImage::ImageDimension); - itkStaticConstMacro(OutputImageDimension, - unsigned int, - TOutputImage::ImageDimension); - - typedef AssymmetricFusionOfLineDetectorImageFilter Self; - typedef LineDetectorImageFilterBase<TInputImage, TOutputImage, TOutputImageDirection, TInterpolator> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - itkNewMacro(Self); - - itkTypeMacro(AssymmetricFusionOfLineDetectorImageFilter, LineDetectorImageFilterBase); - - typedef typename Superclass::InputImageType InputImageType; - typedef typename Superclass::OutputImageType OutputImageType; - typedef typename Superclass::OutputImageDirectionType OutputImageDirectionType; - typedef typename Superclass::InterpolatorType InterpolatorType; - - typedef OutputImageType InputImageType1; - typedef OutputImageType InputImageType2; - - typedef typename InputImageType::PixelType InputPixelType; - typedef typename InputImageType::SizeType SizeType; - - typedef typename OutputImageType::PixelType OutputPixelType; - -protected: - AssymmetricFusionOfLineDetectorImageFilter(); - ~AssymmetricFusionOfLineDetectorImageFilter() ITK_OVERRIDE {} - - typedef otb::LineRatioDetectorImageFilter<InputImageType, OutputImageType, OutputImageDirectionType, - InterpolatorType> LineRatioType; - typedef otb::LineCorrelationDetectorImageFilter<InputImageType, OutputImageType, OutputImageDirectionType, - InterpolatorType> LineCorrelationType; - typedef otb::AssociativeSymmetricalSumImageFilter<InputImageType1, InputImageType2, - OutputImageType> AssSymSumType; - - void GenerateData() ITK_OVERRIDE; - - void PrintSelf(std::ostream& os, itk::Indent indent) const ITK_OVERRIDE; - -private: - AssymmetricFusionOfLineDetectorImageFilter(const Self &); //purposely not implemented - void operator =(const Self&); //purposely not implemented - - typename LineRatioType::Pointer m_LineRatio; - typename LineCorrelationType::Pointer m_LineCorrelation; - typename AssSymSumType::Pointer m_AssSymSum; -}; -} // end namespace otb - -#ifndef OTB_MANUAL_INSTANTIATION -#include "otbAssymmetricFusionOfLineDetectorImageFilter.txx" -#endif - -#endif diff --git a/Modules/Feature/Edge/include/otbAssymmetricFusionOfLineDetectorImageFilter.txx b/Modules/Feature/Edge/include/otbAssymmetricFusionOfLineDetectorImageFilter.txx deleted file mode 100644 index f3ce4d2d7918141f51790254a7e133f644cf0477..0000000000000000000000000000000000000000 --- a/Modules/Feature/Edge/include/otbAssymmetricFusionOfLineDetectorImageFilter.txx +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef otbAssymmetricFusionOfLineDetectorImageFilter_txx -#define otbAssymmetricFusionOfLineDetectorImageFilter_txx - -#include "otbAssymmetricFusionOfLineDetectorImageFilter.h" - -namespace otb -{ - -/** - * - */ -template <class TInputImage, class TOutputImage, class TOutputImageDirection, class TInterpolator> -AssymmetricFusionOfLineDetectorImageFilter<TInputImage, TOutputImage, TOutputImageDirection, TInterpolator> -::AssymmetricFusionOfLineDetectorImageFilter() -{ - this->m_Radius.Fill(1); - this->m_LengthLine = 1; - this->m_WidthLine = 0; - this->m_NumberOfDirections = 8; - - m_LineRatio = LineRatioType::New(); - m_LineCorrelation = LineCorrelationType::New(); - m_AssSymSum = AssSymSumType::New(); -} - -template <class TInputImage, class TOutputImage, class TOutputImageDirection, class TInterpolator> -void -AssymmetricFusionOfLineDetectorImageFilter<TInputImage, TOutputImage, TOutputImageDirection, TInterpolator> -::GenerateData() -{ - m_LineRatio->SetInput( this->GetInput() ); - m_LineRatio->SetLengthLine( this->m_LengthLine ); - m_LineRatio->SetWidthLine( this->m_WidthLine ); - m_LineRatio->SetNumberOfDirections( this->m_NumberOfDirections ); - - m_LineCorrelation->SetInput( this->GetInput() ); - m_LineCorrelation->SetLengthLine( this->m_LengthLine ); - m_LineCorrelation->SetWidthLine( this->m_WidthLine ); - m_LineCorrelation->SetNumberOfDirections( this->m_NumberOfDirections ); - - m_AssSymSum->SetInput1( m_LineRatio->GetOutput() ); - m_AssSymSum->SetInput2( m_LineCorrelation->GetOutput() ); - - m_AssSymSum->GraftOutput(this->GetOutput() ); - m_AssSymSum->Update(); - this->GraftOutput(m_AssSymSum->GetOutput() ); -} - -/** - * Standard "PrintSelf" method - */ -template <class TInputImage, class TOutputImage, class TOutputImageDirection, class TInterpolator> -void -AssymmetricFusionOfLineDetectorImageFilter<TInputImage, TOutputImage, TOutputImageDirection, TInterpolator> -::PrintSelf(std::ostream& os, itk::Indent indent) const -{ - Superclass::PrintSelf(os, indent); -} -} //namespace otb -#endif - - diff --git a/Modules/Filtering/ColorMap/include/otbScalarToRainbowRGBPixelFunctor.h b/Modules/Filtering/ColorMap/include/otbScalarToRainbowRGBPixelFunctor.h index 5fbfe452965ea31b41b0e873cef36ae6df484d6f..ba1e0cb6e9f2d3c7423ba45b40a7413873f80ebb 100644 --- a/Modules/Filtering/ColorMap/include/otbScalarToRainbowRGBPixelFunctor.h +++ b/Modules/Filtering/ColorMap/include/otbScalarToRainbowRGBPixelFunctor.h @@ -156,20 +156,6 @@ public: RGBPixelType operator ()(const TScalar&) const ITK_OVERRIDE; - /** Set the input maximum to be mapped to red - * \deprecated use SetMaximumInputValue() */ - void SetMaximum(ScalarType max) - { - this->SetMaximumInputValue(max); - } - - /** Set the input minimum to be mapped to blue - * \deprecated use SetMinimumInputValue() */ - void SetMinimum(ScalarType min) - { - this->SetMinimumInputValue(min); - } - protected: RGBPixelType HSVToRGB(double h, double s, double v) const; diff --git a/Modules/Filtering/ColorMap/test/otbScalarToRainbowRGBPixelFunctorNew.cxx b/Modules/Filtering/ColorMap/test/otbScalarToRainbowRGBPixelFunctorNew.cxx index 842c9e751bbd5989a3967519bdd0f5737e0188c3..5046235a62e85f44ea3051588b96a13e7376a52c 100644 --- a/Modules/Filtering/ColorMap/test/otbScalarToRainbowRGBPixelFunctorNew.cxx +++ b/Modules/Filtering/ColorMap/test/otbScalarToRainbowRGBPixelFunctorNew.cxx @@ -39,8 +39,8 @@ int otbScalarToRainbowRGBPixelFunctorNew(int itkNotUsed(argc), char * itkNotUsed typedef itk::UnaryFunctorImageFilter<ImageType, RGBImageType, ColorMapFunctorType> ColorMapFilterType; ColorMapFilterType::Pointer colormapper = ColorMapFilterType::New(); - colormapper->GetFunctor().SetMaximum(150); - colormapper->GetFunctor().SetMinimum(70); + colormapper->GetFunctor().SetMaximumInputValue(150); + colormapper->GetFunctor().SetMinimumInputValue(70); std::cout << colormapper << std::endl; diff --git a/Modules/Filtering/DEM/include/otbDEMToImageGenerator.h b/Modules/Filtering/DEM/include/otbDEMToImageGenerator.h index de4bc2d68330d348ab6c4e6abc12f2d32f2a9822..04ad63740fcbbd8d0e04e5c7a38360dbcdb8c5e8 100644 --- a/Modules/Filtering/DEM/include/otbDEMToImageGenerator.h +++ b/Modules/Filtering/DEM/include/otbDEMToImageGenerator.h @@ -110,14 +110,6 @@ public: void InstantiateTransform(); - /** THIS METHOD IS DEPRECATED AND SHOULD NOT BE USED. */ - void InstanciateTransform() - { - otbWarningMacro( - << "InstanciateTransform has been deprecated. Please use InstanciateTransform() instead"); - this->InstantiateTransform(); - } - /** * Set/Get input & output projections. * Set/Get input & output keywordlist diff --git a/Modules/Filtering/ImageManipulation/include/otbChangeInformationImageFilter.h b/Modules/Filtering/ImageManipulation/include/otbChangeInformationImageFilter.h index 2f11a329a3620eb883b1455026373eb5f9d91621..7ae72a4706b5b5c90a1dc6cbf3b78e4895e23f5a 100644 --- a/Modules/Filtering/ImageManipulation/include/otbChangeInformationImageFilter.h +++ b/Modules/Filtering/ImageManipulation/include/otbChangeInformationImageFilter.h @@ -78,11 +78,6 @@ private: ChangeInformationImageFilter(const Self &); //purposely not implemented void operator =(const Self&); //purposely not implemented - /** Removes a field from a metadata dictionary - * After ITK 4.6, an Erase() method has been added to - * itk::MetaDataDictionary, so this function could be tagged as deprecated */ - bool RemoveKeyFromDictionary(itk::MetaDataDictionary & dict, const std::string & key); - /** List of metadata keys to change */ std::set<std::string> m_ChangedKeys; diff --git a/Modules/Filtering/ImageManipulation/include/otbChangeInformationImageFilter.txx b/Modules/Filtering/ImageManipulation/include/otbChangeInformationImageFilter.txx index 1fb1b3d3e58ded8370d10ca1ac8997d61c567fad..83f2c74772d1302edd50b27d8529d03c1e4a5766 100644 --- a/Modules/Filtering/ImageManipulation/include/otbChangeInformationImageFilter.txx +++ b/Modules/Filtering/ImageManipulation/include/otbChangeInformationImageFilter.txx @@ -81,7 +81,7 @@ ChangeInformationImageFilter<TInputImage> if (value == ITK_NULLPTR) { // Remove meta-data from dictionary - this->RemoveKeyFromDictionary(dict,key); + dict.Erase(key); } else { @@ -113,41 +113,11 @@ ChangeInformationImageFilter<TInputImage> else { // Remove metadata from output dictionary - this->RemoveKeyFromDictionary(outputDict,*it); + outputDict.Erase(*it); } } } -template< typename TInputImage > -bool -ChangeInformationImageFilter<TInputImage> -::RemoveKeyFromDictionary(itk::MetaDataDictionary & dict, const std::string & key) -{ - std::vector<std::string> keyList = dict.GetKeys(); - std::vector<std::string>::iterator pos = keyList.begin(); - while (pos != keyList.end()) - { - if (key.compare(*pos) == 0) - { - break; - } - ++pos; - } - if (pos != keyList.end()) - { - itk::MetaDataDictionary copyDict; - keyList.erase(pos); - pos = keyList.begin(); - for ( ; pos != keyList.end();++pos) - { - copyDict.Set(*pos, const_cast<itk::MetaDataObjectBase*>(dict.Get(*pos))); - } - dict = copyDict; - return true; - } - return false; -} - } // End of namespace OTB #endif diff --git a/Modules/Filtering/ImageManipulation/include/otbStreamingShrinkImageFilter.h b/Modules/Filtering/ImageManipulation/include/otbStreamingShrinkImageFilter.h index 5f37427f9f4260ad13bbf2c52b51551788dc30b0..c00878892f2d0c7aa0950e835dc3f39264ae12b1 100644 --- a/Modules/Filtering/ImageManipulation/include/otbStreamingShrinkImageFilter.h +++ b/Modules/Filtering/ImageManipulation/include/otbStreamingShrinkImageFilter.h @@ -202,13 +202,6 @@ public: { return m_ShrunkOutput; } - - /** THIS METHOD IS DEPRECATED AND SHOULD NOT BE USED. */ - OutputImageType * GetShrinkedOutput() - { - otbWarningMacro(<< "GetShrinkedOutput has been deprecated. Please use GetShrunkOutput instead"); - return GetShrunkOutput(); - } void Synthetize(void) ITK_OVERRIDE; diff --git a/Modules/Filtering/ImageManipulation/include/otbVectorRescaleIntensityImageFilter.h b/Modules/Filtering/ImageManipulation/include/otbVectorRescaleIntensityImageFilter.h index 4fedd2357e8c904377fd958f0a63e9a07be9f7d6..8b5633863c1097a95560600945f7d704f113c066 100644 --- a/Modules/Filtering/ImageManipulation/include/otbVectorRescaleIntensityImageFilter.h +++ b/Modules/Filtering/ImageManipulation/include/otbVectorRescaleIntensityImageFilter.h @@ -206,7 +206,7 @@ private: * * This filter differ from itk::VectorRescaleIntensityImageFilter. * Instead of setting only the OutputMaximumMagnitude, you can set the minimum and maximum values for the input and output images. - * There is also the possibilty to set a Gamma value and change the clamp percentage. + * There is also the possibility to set a Gamma value and change the clamp percentage. * * \ingroup IntensityImageFilters * \ingroup MultiThreaded diff --git a/Modules/Filtering/Projection/include/otbGeometriesProjectionFilter.h b/Modules/Filtering/Projection/include/otbGeometriesProjectionFilter.h index e81803df67a8d54ea2a6cea4795c7502a93ac92c..50e7ea5b2ff20c75e2bbfc5abf2e136767994921 100644 --- a/Modules/Filtering/Projection/include/otbGeometriesProjectionFilter.h +++ b/Modules/Filtering/Projection/include/otbGeometriesProjectionFilter.h @@ -214,14 +214,6 @@ private: * the last moment from \c DoProcessLayer(). */ void DoFinalizeInitialization() ITK_OVERRIDE; - - /** THIS METHOD IS DEPRECATED AND SHOULD NOT BE USED. */ - void DoFinalizeInitialisation() - { - otbWarningMacro( - << "DoFinalizeInitialisation has been deprecated. Please use DoFinalizeInitialization() instead"); - this->DoFinalizeInitialization(); - } /** * Hook used to define the fields of the new layer. diff --git a/Modules/Filtering/Projection/include/otbMapProjectionDeprecated.h b/Modules/Filtering/Projection/include/otbMapProjectionDeprecated.h deleted file mode 100644 index 0423ddc1001c3cd26b385da40f97ba6fa50e9890..0000000000000000000000000000000000000000 --- a/Modules/Filtering/Projection/include/otbMapProjectionDeprecated.h +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef otbMapProjectionDeprecated_h -#define otbMapProjectionDeprecated_h - -#include "otbGenericMapProjection.h" - - -namespace otb -{ - -namespace MapProjectionType -{ -enum MapProj -{ - ALBERS, - AZIMEQUDIST, - BNG, - BONNE, - CADRG, - CASSINI, - CYLEQUAREA, - ECKERT6, - GNOMONIC, - LLXY, - EQUDISTCYL, - MERCATOR, - MILLER, - NEWZEALANDMAPGRID, - OBLIQUEMERCATOR, - ORTHOGRAPHIC, - POLARSTEREO, - POLYCONIC, - SPACEOBLIQUEMERCATOR, - STEREOGRAPHIC, - TRANSCYLEQUAREA, - UPS, - VANDERGRINTEN, -}; -} - -/** \class MapProjectionDeprecated - * \brief The only purpose of this class is to maintain backward compatibility. - * - * GenericMapProjection should be used instead. - * - * - * - * \ingroup OTBProjection - */ -template <MapProjectionType::MapProj TMapProj, - TransformDirection::TransformationDirection TTransform> -class ITK_EXPORT MapProjectionDeprecated : public GenericMapProjection<TTransform> -{ -public: - - /** Standard class typedefs. */ - typedef MapProjectionDeprecated Self; - typedef GenericMapProjection<TTransform> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - typedef typename Superclass::ScalarType ScalarType; - typedef itk::Point<ScalarType, 2> InputPointType; - typedef itk::Point<ScalarType, 2> OutputPointType; - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - /** Run-time type information (and related methods). */ - itkTypeMacro(MapProjectionDeprecated, GenericMapProjection); - -protected: - MapProjectionDeprecated(); - ~MapProjectionDeprecated() ITK_OVERRIDE {}; - -private: - MapProjectionDeprecated(const Self &); //purposely not implemented - void operator =(const Self&); //purposely not implemented -}; - -} // namespace otb - -#ifndef OTB_MANUAL_INSTANTIATION -#include "otbMapProjectionDeprecated.txx" -#endif - -#endif diff --git a/Modules/Filtering/Projection/include/otbMapProjectionDeprecated.txx b/Modules/Filtering/Projection/include/otbMapProjectionDeprecated.txx deleted file mode 100644 index 810ae2bcf1daf48284ffed3ef1bf4ef16a393c9d..0000000000000000000000000000000000000000 --- a/Modules/Filtering/Projection/include/otbMapProjectionDeprecated.txx +++ /dev/null @@ -1,186 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef otbMapProjectionDeprecated_txx -#define otbMapProjectionDeprecated_txx - -#include "otbMapProjectionDeprecated.h" - -namespace otb -{ - -template<MapProjectionType::MapProj TMapProj> -inline std::string GetMapProjectionDeprecatedString() -{ - return ""; -} - -template<> -inline std::string GetMapProjectionDeprecatedString<MapProjectionType::ALBERS>() -{ - return "Albers"; -} - -template<> -inline std::string GetMapProjectionDeprecatedString<MapProjectionType::AZIMEQUDIST>() -{ - return "AzimEquDist"; -} - -template<> -inline std::string GetMapProjectionDeprecatedString<MapProjectionType::BNG>() -{ - return "Bng"; -} - -template<> -inline std::string GetMapProjectionDeprecatedString<MapProjectionType::BONNE>() -{ - return "Bonne"; -} - -template<> -inline std::string GetMapProjectionDeprecatedString<MapProjectionType::CADRG>() -{ - return "Cadrg"; -} - -template<> -inline std::string GetMapProjectionDeprecatedString<MapProjectionType::CASSINI>() -{ - return "Cassini"; -} - -template<> -inline std::string GetMapProjectionDeprecatedString<MapProjectionType::CYLEQUAREA>() -{ - return "CylEquArea"; -} - -template<> -inline std::string GetMapProjectionDeprecatedString<MapProjectionType::ECKERT6>() -{ - return "Eckert6"; -} - -template<> -inline std::string GetMapProjectionDeprecatedString<MapProjectionType::GNOMONIC>() -{ - return "Gnomonic"; -} - -template<> -inline std::string GetMapProjectionDeprecatedString<MapProjectionType::LLXY>() -{ - return "Llxy"; -} - -template<> -inline std::string GetMapProjectionDeprecatedString<MapProjectionType::EQUDISTCYL>() -{ - return "EquDistCyl"; -} - -template<> -inline std::string GetMapProjectionDeprecatedString<MapProjectionType::MERCATOR>() -{ - return "Mercator"; -} - -template<> -inline std::string GetMapProjectionDeprecatedString<MapProjectionType::MILLER>() -{ - return "Miller"; -} - -template<> -inline std::string GetMapProjectionDeprecatedString<MapProjectionType::NEWZEALANDMAPGRID>() -{ - return "NewZealandMapGrid"; -} - -template<> -inline std::string GetMapProjectionDeprecatedString<MapProjectionType::OBLIQUEMERCATOR>() -{ - return "ObliqueMercator"; -} - -template<> -inline std::string GetMapProjectionDeprecatedString<MapProjectionType::ORTHOGRAPHIC>() -{ - return "OrthoGraphic"; -} - -template<> -inline std::string GetMapProjectionDeprecatedString<MapProjectionType::POLARSTEREO>() -{ - return "PolarStereo"; -} - -template<> -inline std::string GetMapProjectionDeprecatedString<MapProjectionType::POLYCONIC>() -{ - return "Polyconic"; -} - -template<> -inline std::string GetMapProjectionDeprecatedString<MapProjectionType::SPACEOBLIQUEMERCATOR>() -{ - return "SpaceObliqueMercator"; -} - -template<> -inline std::string GetMapProjectionDeprecatedString<MapProjectionType::STEREOGRAPHIC>() -{ - return "Stereographic"; -} - -template<> -inline std::string GetMapProjectionDeprecatedString<MapProjectionType::TRANSCYLEQUAREA>() -{ - return "TransCylEquArea"; -} - - -template<> -inline std::string GetMapProjectionDeprecatedString<MapProjectionType::UPS>() -{ - return "Ups"; -} - - -template<> -inline std::string GetMapProjectionDeprecatedString<MapProjectionType::VANDERGRINTEN>() -{ - return "VanDerGrinten"; -} - - -template <MapProjectionType::MapProj TMapProj, - TransformDirection::TransformationDirection TTransform> -MapProjectionDeprecated<TMapProj, TTransform> -::MapProjectionDeprecated() -{ - this->SetWkt(GetMapProjectionDeprecatedString<TMapProj>()); -} - -} - -#endif diff --git a/Modules/Filtering/Projection/include/otbMapProjections.h b/Modules/Filtering/Projection/include/otbMapProjections.h index fab1fb513bc05cd1dfd9348ad07f3792477f6866..70655b0531d6f3aa88e1f26a7da852325f3dc60e 100644 --- a/Modules/Filtering/Projection/include/otbMapProjections.h +++ b/Modules/Filtering/Projection/include/otbMapProjections.h @@ -21,8 +21,6 @@ #ifndef otbMapProjections_h #define otbMapProjections_h -#include "otbMapProjectionDeprecated.h" - #include "otbUtmMapProjection.h" #include "otbLambert2EtenduProjection.h" #include "otbLambert3CartoSudProjection.h" @@ -56,54 +54,5 @@ typedef TransMercatorMapProjection<TransformDirection::FORWARD> typedef UtmMapProjection<TransformDirection::INVERSE> UtmInverseProjection; typedef UtmMapProjection<TransformDirection::FORWARD> UtmForwardProjection; -// Definitions to maintain backward compatibility, but the GenericMapProjection -// should be used instead. -typedef MapProjectionDeprecated<MapProjectionType::ALBERS, TransformDirection::INVERSE> AlbersInverseProjection; -typedef MapProjectionDeprecated<MapProjectionType::ALBERS, TransformDirection::FORWARD> AlbersForwardProjection; -typedef MapProjectionDeprecated<MapProjectionType::AZIMEQUDIST, TransformDirection::INVERSE> AzimEquDistInverseProjection; -typedef MapProjectionDeprecated<MapProjectionType::AZIMEQUDIST, TransformDirection::FORWARD> AzimEquDistForwardProjection; -typedef MapProjectionDeprecated<MapProjectionType::BNG, TransformDirection::INVERSE> BngInverseProjection; -typedef MapProjectionDeprecated<MapProjectionType::BNG, TransformDirection::FORWARD> BngForwardProjection; -typedef MapProjectionDeprecated<MapProjectionType::BONNE, TransformDirection::INVERSE> BonneInverseProjection; -typedef MapProjectionDeprecated<MapProjectionType::BONNE, TransformDirection::FORWARD> BonneForwardProjection; -typedef MapProjectionDeprecated<MapProjectionType::CADRG, TransformDirection::INVERSE> CadrgInverseProjection; -typedef MapProjectionDeprecated<MapProjectionType::CADRG, TransformDirection::FORWARD> CadrgForwardProjection; -typedef MapProjectionDeprecated<MapProjectionType::CASSINI, TransformDirection::INVERSE> CassiniInverseProjection; -typedef MapProjectionDeprecated<MapProjectionType::CASSINI, TransformDirection::FORWARD> CassiniForwardProjection; -typedef MapProjectionDeprecated<MapProjectionType::CYLEQUAREA, TransformDirection::INVERSE> CylEquAreaInverseProjection; -typedef MapProjectionDeprecated<MapProjectionType::CYLEQUAREA, TransformDirection::FORWARD> CylEquAreaForwardProjection; -typedef MapProjectionDeprecated<MapProjectionType::ECKERT6, TransformDirection::INVERSE> Eckert6InverseProjection; -typedef MapProjectionDeprecated<MapProjectionType::ECKERT6, TransformDirection::FORWARD> Eckert6ForwardProjection; -typedef MapProjectionDeprecated<MapProjectionType::GNOMONIC, TransformDirection::INVERSE> GnomonicInverseProjection; -typedef MapProjectionDeprecated<MapProjectionType::GNOMONIC, TransformDirection::FORWARD> GnomonicForwardProjection; -typedef MapProjectionDeprecated<MapProjectionType::LLXY, TransformDirection::INVERSE> LlxyInverseProjection; -typedef MapProjectionDeprecated<MapProjectionType::LLXY, TransformDirection::FORWARD> LlxyForwardProjection; -typedef MapProjectionDeprecated<MapProjectionType::EQUDISTCYL, TransformDirection::INVERSE> EquDistCylInverseProjection; -typedef MapProjectionDeprecated<MapProjectionType::EQUDISTCYL, TransformDirection::FORWARD> EquDistCylForwardProjection; -typedef MapProjectionDeprecated<MapProjectionType::MERCATOR, TransformDirection::INVERSE> MercatorInverseProjection; -typedef MapProjectionDeprecated<MapProjectionType::MERCATOR, TransformDirection::FORWARD> MercatorForwardProjection; -typedef MapProjectionDeprecated<MapProjectionType::MILLER, TransformDirection::INVERSE> MillerInverseProjection; -typedef MapProjectionDeprecated<MapProjectionType::MILLER, TransformDirection::FORWARD> MillerForwardProjection; -typedef MapProjectionDeprecated<MapProjectionType::NEWZEALANDMAPGRID, TransformDirection::INVERSE> NewZealandMapGridInverseProjection; -typedef MapProjectionDeprecated<MapProjectionType::NEWZEALANDMAPGRID, TransformDirection::FORWARD> NewZealandMapGridForwardProjection; -typedef MapProjectionDeprecated<MapProjectionType::OBLIQUEMERCATOR, TransformDirection::INVERSE> ObliqueMercatorInverseProjection; -typedef MapProjectionDeprecated<MapProjectionType::OBLIQUEMERCATOR, TransformDirection::FORWARD> ObliqueMercatorForwardProjection; -typedef MapProjectionDeprecated<MapProjectionType::ORTHOGRAPHIC, TransformDirection::INVERSE> OrthoGraphicInverseProjection; -typedef MapProjectionDeprecated<MapProjectionType::ORTHOGRAPHIC, TransformDirection::FORWARD> OrthoGraphicForwardProjection; -typedef MapProjectionDeprecated<MapProjectionType::POLARSTEREO, TransformDirection::INVERSE> PolarStereoInverseProjection; -typedef MapProjectionDeprecated<MapProjectionType::POLARSTEREO, TransformDirection::FORWARD> PolarStereoForwardProjection; -typedef MapProjectionDeprecated<MapProjectionType::POLYCONIC, TransformDirection::INVERSE> PolyconicInverseProjection; -typedef MapProjectionDeprecated<MapProjectionType::POLYCONIC, TransformDirection::FORWARD> PolyconicForwardProjection; -typedef MapProjectionDeprecated<MapProjectionType::SPACEOBLIQUEMERCATOR, TransformDirection::INVERSE> SpaceObliqueMercatorInverseProjection; -typedef MapProjectionDeprecated<MapProjectionType::SPACEOBLIQUEMERCATOR, TransformDirection::FORWARD> SpaceObliqueMercatorForwardProjection; -typedef MapProjectionDeprecated<MapProjectionType::STEREOGRAPHIC, TransformDirection::INVERSE> StereographicInverseProjection; -typedef MapProjectionDeprecated<MapProjectionType::STEREOGRAPHIC, TransformDirection::FORWARD> StereographicForwardProjection; -typedef MapProjectionDeprecated<MapProjectionType::TRANSCYLEQUAREA, TransformDirection::INVERSE> TransCylEquAreaInverseProjection; -typedef MapProjectionDeprecated<MapProjectionType::TRANSCYLEQUAREA, TransformDirection::FORWARD> TransCylEquAreaForwardProjection; -typedef MapProjectionDeprecated<MapProjectionType::UPS, TransformDirection::INVERSE> UpsInverseProjection; -typedef MapProjectionDeprecated<MapProjectionType::UPS, TransformDirection::FORWARD> UpsForwardProjection; -typedef MapProjectionDeprecated<MapProjectionType::VANDERGRINTEN, TransformDirection::INVERSE> VanDerGrintenInverseProjection; -typedef MapProjectionDeprecated<MapProjectionType::VANDERGRINTEN, TransformDirection::FORWARD> VanDerGrintenForwardProjection; - } //namespace otb #endif diff --git a/Modules/Filtering/Projection/include/otbVectorDataProjectionFilter.h b/Modules/Filtering/Projection/include/otbVectorDataProjectionFilter.h index 978ba4d46d88f30de1d0820651064915da1cfb09..18fc93404ae46febf4fcd730c942ce0c76720a63 100644 --- a/Modules/Filtering/Projection/include/otbVectorDataProjectionFilter.h +++ b/Modules/Filtering/Projection/include/otbVectorDataProjectionFilter.h @@ -184,14 +184,6 @@ protected: virtual void InstantiateTransform(void); - /** THIS METHOD IS DEPRECATED AND SHOULD NOT BE USED. */ - void InstanciateTransform() - { - otbWarningMacro( - << "InstanciateTransform has been deprecated. Please use InstanciateTransform() instead"); - this->InstantiateTransform(); - } - void GenerateOutputInformation(void) ITK_OVERRIDE; void GenerateData(void) ITK_OVERRIDE; diff --git a/Modules/Filtering/Projection/test/CMakeLists.txt b/Modules/Filtering/Projection/test/CMakeLists.txt index dd71babbce34ea7cd1dd58463f2ef161fa8b505d..022daa7b56d1c82b62f3118785246c1807c3cb74 100644 --- a/Modules/Filtering/Projection/test/CMakeLists.txt +++ b/Modules/Filtering/Projection/test/CMakeLists.txt @@ -44,7 +44,6 @@ otbOrthoRectificationFilterNew.cxx otbImageToGenericRSOutputParameters.cxx otbGeometriesProjectionFilterFromMapToGeo.cxx otbROIdataConversion.cxx -otbProjectionBaseNew.cxx otbVectorDataProjectionFilterFromMapToGeo.cxx otbPhysicalToRPCSensorModelImageFilter.cxx otbGeometriesProjectionFilterFromGeoToMap.cxx @@ -536,8 +535,6 @@ otb_add_test(NAME leTvROIdataConversion COMMAND otbProjectionTestDriver ${TEMP}/leTvROIdataConversion.txt ) -otb_add_test(NAME prTuProjectionBaseNew COMMAND otbProjectionTestDriver otbProjectionBaseNew ) - otb_add_test(NAME prTvVectorDataProjectionFilterFromMapToGeo COMMAND otbProjectionTestDriver --compare-ogr ${NOTOL} ${BASELINE_FILES}/prTvVectorDataProjectionFilterFromMapToGeo.kml diff --git a/Modules/Filtering/Projection/test/otbMapProjection.cxx b/Modules/Filtering/Projection/test/otbMapProjection.cxx index a245fc4f1de823dcaaa6a4f6d3d05695f5cbb047..b98e839787448e3e66c4c811a09f5820de145009 100644 --- a/Modules/Filtering/Projection/test/otbMapProjection.cxx +++ b/Modules/Filtering/Projection/test/otbMapProjection.cxx @@ -87,9 +87,9 @@ int otbMapProjection(int itkNotUsed(argc), char* argv[]) file << lLambert93->TransformPoint(point2); file << std::endl << std::endl; - - - otb::MercatorForwardProjection::Pointer lMercatorProjection2 = otb::MercatorForwardProjection::New(); + typedef otb::GenericMapProjection<otb::TransformDirection::FORWARD> MercatorForwardProjection; + MercatorForwardProjection::Pointer lMercatorProjection2 = MercatorForwardProjection::New(); + lMercatorProjection2->SetWkt(std::string("Mercator")); point2 = lMercatorProjection2->TransformPoint(point); file << lMercatorProjection2->GetWkt() << std::endl << std::endl; file << "Forward projection: " << std::endl; @@ -97,8 +97,9 @@ int otbMapProjection(int itkNotUsed(argc), char* argv[]) file << point2; file << std::endl << std::endl; - - otb::MercatorInverseProjection::Pointer lMercatorProjection = otb::MercatorInverseProjection::New(); + typedef otb::GenericMapProjection<otb::TransformDirection::INVERSE> MercatorInverseProjection; + MercatorInverseProjection::Pointer lMercatorProjection = MercatorInverseProjection::New(); + lMercatorProjection->SetWkt(std::string("Mercator")); file << lMercatorProjection->GetWkt() << std::endl << std::endl; file << "Inverse projection: " << std::endl; file << point2 << " -> "; diff --git a/Modules/Filtering/Projection/test/otbMapProjectionsNew.cxx b/Modules/Filtering/Projection/test/otbMapProjectionsNew.cxx index 38ceab4477c31fc83ca5c9fed04bdbb3fc427e7d..f29644125f041f53e74452508beb949a7d929d3c 100644 --- a/Modules/Filtering/Projection/test/otbMapProjectionsNew.cxx +++ b/Modules/Filtering/Projection/test/otbMapProjectionsNew.cxx @@ -29,90 +29,31 @@ int otbMapProjectionsNew(int itkNotUsed(argc), char* itkNotUsed(argv)[]) { - otb::AlbersInverseProjection::Pointer lAlbersProjection = otb::AlbersInverseProjection::New(); - otb::AlbersForwardProjection::Pointer lAlbersProjection2 = otb::AlbersForwardProjection::New(); - otb::AzimEquDistInverseProjection::Pointer lAzimEquDistProjection = otb::AzimEquDistInverseProjection::New(); - otb::AzimEquDistForwardProjection::Pointer lAzimEquDistProjection2 = otb::AzimEquDistForwardProjection::New(); - //Comment for OTB 2.2.0 because OSSIM error code -> generate Exception Fault on VS 7.1 only on Debug mode. - // otb::BngInverseProjection::Pointer lBngProjection = otb::BngInverseProjection::New(); - // otb::BngForwardProjection::Pointer lBngProjection2 = otb::BngForwardProjection::New(); - otb::BonneInverseProjection::Pointer lBonneProjection = otb::BonneInverseProjection::New(); - otb::BonneForwardProjection::Pointer lBonneProjection2 = otb::BonneForwardProjection::New(); - otb::CadrgInverseProjection::Pointer lCadrgProjection = otb::CadrgInverseProjection::New(); - otb::CadrgForwardProjection::Pointer lCadrgProjection2 = otb::CadrgForwardProjection::New(); - otb::CassiniInverseProjection::Pointer lCassiniProjection = otb::CassiniInverseProjection::New(); - otb::CassiniForwardProjection::Pointer lCassiniProjection2 = otb::CassiniForwardProjection::New(); - otb::CylEquAreaInverseProjection::Pointer lCylEquAreaProjection = otb::CylEquAreaInverseProjection::New(); - otb::CylEquAreaForwardProjection::Pointer lCylEquAreaProjection2 = otb::CylEquAreaForwardProjection::New(); otb::Eckert4InverseProjection::Pointer lEckert4Projection = otb::Eckert4InverseProjection::New(); otb::Eckert4ForwardProjection::Pointer lEckert4Projection2 = otb::Eckert4ForwardProjection::New(); - otb::Eckert6InverseProjection::Pointer lEckert6Projection = otb::Eckert6InverseProjection::New(); - otb::Eckert6ForwardProjection::Pointer lEckert6Projection2 = otb::Eckert6ForwardProjection::New(); - otb::GnomonicInverseProjection::Pointer lGnomonicProjection = otb::GnomonicInverseProjection::New(); - otb::GnomonicForwardProjection::Pointer lGnomonicProjection2 = otb::GnomonicForwardProjection::New(); otb::LambertConformalConicInverseProjection::Pointer lLambertConformalConicProjection = otb::LambertConformalConicInverseProjection::New(); otb::LambertConformalConicForwardProjection::Pointer lLambertConformalConicProjection2 = otb::LambertConformalConicForwardProjection::New(); - otb::LlxyInverseProjection::Pointer lLlxyProjection = otb::LlxyInverseProjection::New(); - otb::LlxyForwardProjection::Pointer lLlxyProjection2 = otb::LlxyForwardProjection::New(); - otb::EquDistCylInverseProjection::Pointer lEquDistCylProjection = otb::EquDistCylInverseProjection::New(); - otb::EquDistCylForwardProjection::Pointer lEquDistCylProjection2 = otb::EquDistCylForwardProjection::New(); - otb::MercatorInverseProjection::Pointer lMercatorProjection = otb::MercatorInverseProjection::New(); - otb::MercatorForwardProjection::Pointer lMercatorProjection2 = otb::MercatorForwardProjection::New(); - otb::MillerInverseProjection::Pointer lMillerProjection = otb::MillerInverseProjection::New(); - otb::MillerForwardProjection::Pointer lMillerProjection2 = otb::MillerForwardProjection::New(); + otb::Lambert2EtenduInverseProjection::Pointer lLambert2Etendu = otb::Lambert2EtenduInverseProjection::New(); + otb::Lambert2EtenduForwardProjection::Pointer lLambert2Etendu2 = otb::Lambert2EtenduForwardProjection::New(); + otb::Lambert3CartoSudInverseProjection::Pointer lLambert3CartoSud = otb::Lambert3CartoSudInverseProjection::New(); + otb::Lambert3CartoSudForwardProjection::Pointer lLambert3CartoSud2 = otb::Lambert3CartoSudForwardProjection::New(); + otb::Lambert93InverseProjection::Pointer lLambert93 = otb::Lambert93InverseProjection::New(); + otb::Lambert93ForwardProjection::Pointer lLambert93_2 = otb::Lambert93ForwardProjection::New(); otb::MollweidInverseProjection::Pointer lMollweidProjection = otb::MollweidInverseProjection::New(); otb::MollweidForwardProjection::Pointer lMollweidProjection2 = otb::MollweidForwardProjection::New(); - otb::NewZealandMapGridInverseProjection::Pointer lNewZealandMapGridProjection = - otb::NewZealandMapGridInverseProjection::New(); - otb::NewZealandMapGridForwardProjection::Pointer lNewZealandMapGridProjection2 = - otb::NewZealandMapGridForwardProjection::New(); - otb::ObliqueMercatorInverseProjection::Pointer lObliqueMercatorProjection = - otb::ObliqueMercatorInverseProjection::New(); - otb::ObliqueMercatorForwardProjection::Pointer lObliqueMercatorProjection2 = - otb::ObliqueMercatorForwardProjection::New(); - otb::OrthoGraphicInverseProjection::Pointer lOrthoGraphicProjection = - otb::OrthoGraphicInverseProjection::New(); - otb::OrthoGraphicForwardProjection::Pointer lOrthoGraphicProjection2 = - otb::OrthoGraphicForwardProjection::New(); - otb::PolarStereoInverseProjection::Pointer lPolarStereoProjection = otb::PolarStereoInverseProjection::New(); - otb::PolarStereoForwardProjection::Pointer lPolarStereoProjection2 = otb::PolarStereoForwardProjection::New(); - otb::PolyconicInverseProjection::Pointer lPolyconicProjection = otb::PolyconicInverseProjection::New(); - otb::PolyconicForwardProjection::Pointer lPolyconicProjection2 = otb::PolyconicForwardProjection::New(); otb::SinusoidalInverseProjection::Pointer lSinusoidalProjection = otb::SinusoidalInverseProjection::New(); otb::SinusoidalForwardProjection::Pointer lSinusoidalProjection2 = otb::SinusoidalForwardProjection::New(); - otb::SpaceObliqueMercatorInverseProjection::Pointer lSpaceObliqueMercatorProjection = - otb::SpaceObliqueMercatorInverseProjection::New(); - otb::SpaceObliqueMercatorForwardProjection::Pointer lSpaceObliqueMercatorProjection2 = - otb::SpaceObliqueMercatorForwardProjection::New(); - otb::StereographicInverseProjection::Pointer lStereographicProjection = - otb::StereographicInverseProjection::New(); - otb::StereographicForwardProjection::Pointer lStereographicProjection2 = - otb::StereographicForwardProjection::New(); - otb::TransCylEquAreaInverseProjection::Pointer lTransCylEquAreaProjection = - otb::TransCylEquAreaInverseProjection::New(); - otb::TransCylEquAreaForwardProjection::Pointer lTransCylEquAreaProjection2 = - otb::TransCylEquAreaForwardProjection::New(); + otb::SVY21InverseProjection::Pointer lSVY21 = otb::SVY21InverseProjection::New(); + otb::SVY21ForwardProjection::Pointer lSVY21_2 = otb::SVY21ForwardProjection::New(); otb::TransMercatorInverseProjection::Pointer lTransMercatorProjection = otb::TransMercatorInverseProjection::New(); otb::TransMercatorForwardProjection::Pointer lTransMercatorProjection2 = otb::TransMercatorForwardProjection::New(); - otb::UpsInverseProjection::Pointer lUpsProjection = otb::UpsInverseProjection::New(); - otb::UpsForwardProjection::Pointer lUpsProjection2 = otb::UpsForwardProjection::New(); otb::UtmInverseProjection::Pointer lUtmProjection = otb::UtmInverseProjection::New(); otb::UtmForwardProjection::Pointer lUtmProjection2 = otb::UtmForwardProjection::New(); - otb::VanDerGrintenInverseProjection::Pointer lVanDerGrintenProjection = - otb::VanDerGrintenInverseProjection::New(); - otb::VanDerGrintenForwardProjection::Pointer lVanDerGrintenProjection2 = - otb::VanDerGrintenForwardProjection::New(); - otb::Lambert2EtenduInverseProjection::Pointer lLambert2Etendu = otb::Lambert2EtenduInverseProjection::New(); - otb::Lambert2EtenduForwardProjection::Pointer lLambert2Etendu2 = otb::Lambert2EtenduForwardProjection::New(); - otb::Lambert93InverseProjection::Pointer lLambert93 = otb::Lambert93InverseProjection::New(); - otb::Lambert93ForwardProjection::Pointer lLambert93_2 = otb::Lambert93ForwardProjection::New(); - otb::SVY21InverseProjection::Pointer lSVY21 = otb::SVY21InverseProjection::New(); - otb::SVY21ForwardProjection::Pointer lSVY21_2 = otb::SVY21ForwardProjection::New(); - + return EXIT_SUCCESS; } diff --git a/Modules/Filtering/Projection/test/otbProjectionBaseNew.cxx b/Modules/Filtering/Projection/test/otbProjectionBaseNew.cxx deleted file mode 100644 index 53e3e6a917bd846f43ff4d7edf043aa5151d3e15..0000000000000000000000000000000000000000 --- a/Modules/Filtering/Projection/test/otbProjectionBaseNew.cxx +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - - -#include "itkMacro.h" -#include <iostream> - -#include "otbMapProjections.h" - -int otbProjectionBaseNew(int itkNotUsed(argc), char * itkNotUsed(argv)[]) -{ - otb::AlbersInverseProjection::Pointer lAlbersProjection = otb::AlbersInverseProjection::New(); - otb::AzimEquDistForwardProjection::Pointer lAzimEquDistProjection = otb::AzimEquDistForwardProjection::New(); - - return EXIT_SUCCESS; -} diff --git a/Modules/Filtering/Projection/test/otbProjectionTestDriver.cxx b/Modules/Filtering/Projection/test/otbProjectionTestDriver.cxx index d5b90afcebb8152a7304b33fe580e0bc776716f5..1f249676ab2ef6a796052c400d3b3e33390b57c4 100644 --- a/Modules/Filtering/Projection/test/otbProjectionTestDriver.cxx +++ b/Modules/Filtering/Projection/test/otbProjectionTestDriver.cxx @@ -51,7 +51,6 @@ void RegisterTests() REGISTER_TEST(otbImageToGenericRSOutputParameters); REGISTER_TEST(otbGeometriesProjectionFilterFromMapToGeo); REGISTER_TEST(otbROIdataConversion); - REGISTER_TEST(otbProjectionBaseNew); REGISTER_TEST(otbVectorDataProjectionFilterFromMapToGeo); REGISTER_TEST(otbPhysicalToRPCSensorModelImageFilter); REGISTER_TEST(otbGeometriesProjectionFilterFromGeoToMap); diff --git a/Modules/Filtering/VectorDataRendering/include/otbVectorDataToImageFilter.h b/Modules/Filtering/VectorDataRendering/include/otbVectorDataToImageFilter.h deleted file mode 100644 index 86f4d110cd950c4f1fd9f329b77ccc667cb26a6c..0000000000000000000000000000000000000000 --- a/Modules/Filtering/VectorDataRendering/include/otbVectorDataToImageFilter.h +++ /dev/null @@ -1,244 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -#ifndef otbVectorDataToImageFilter_h -#define otbVectorDataToImageFilter_h - -#include "itkImageSource.h" -#include "otbRGBAPixelConverter.h" -#include "otbVectorDataExtractROI.h" - -#if defined(__GNUC__) || defined(__clang__) -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wshadow" -#pragma GCC diagnostic ignored "-Wunused-parameter" -#include <mapnik/memory_datasource.hpp> -#include <mapnik/map.hpp> -#pragma GCC diagnostic pop -#else -#include <mapnik/memory_datasource.hpp> -#include <mapnik/map.hpp> -#endif - - -namespace otb -{ -/** \class VectorDataToImageFilter - * \brief <b>DEPRECATED</b>: See VectorDataToImageFilter - * \deprecated use VectorDataToImageFilter instead - * \sa VectorDataToImageFilter - * - * \ingroup OTBVectorDataRendering - */ - -template <class TVectorData, class TImage> -class ITK_EXPORT VectorDataToImageFilter : public itk::ImageSource<TImage> -{ -public: - /** Standard class typedefs. */ - typedef VectorDataToImageFilter Self; - typedef itk::ImageSource<TImage> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - /** Run-time type information (and related methods). */ - itkTypeMacro(VectorDataToImageFilter, ImageSource); - - /** Some typedefs. */ - typedef TVectorData VectorDataType; - typedef TImage ImageType; - typedef typename ImageType::PixelType PixelType; - typedef typename ImageType::Pointer ImagePointer; - typedef typename VectorDataType::ConstPointer VectorDataConstPointer; - typedef typename VectorDataType::DataTreeType::TreeNodeType InternalTreeNodeType; - typedef typename InternalTreeNodeType::ChildrenListType ChildrenListType; - typedef VectorDataExtractROI<VectorDataType> VectorDataExtractROIType; - typedef RemoteSensingRegion<double> RemoteSensingRegionType; - typedef typename RemoteSensingRegionType::SizeType SizePhyType; - - /** Number of dimensions. */ - itkStaticConstMacro(ImageDimension, unsigned int, - TImage::ImageDimension); - - /** Image size typedef. */ - typedef itk::Size<itkGetStaticConstMacro(ImageDimension)> SizeType; - - /** Image index typedef. */ - typedef typename TImage::IndexType IndexType; - - /** Image spacing, origin and direction typedef */ - typedef typename TImage::SpacingType SpacingType; - typedef typename TImage::PointType OriginType; - typedef typename TImage::DirectionType DirectionType; - - /** Region typedef */ - typedef typename TImage::RegionType RegionType; - - /** RGBA Converter typedef */ - typedef RGBAPixelConverter<unsigned char, PixelType> RGBAConverterType; - - /** typedef specific to mapnik */ - typedef boost::shared_ptr<mapnik::memory_datasource> datasource_ptr; - - /** */ - typedef enum - { - OSM, - Binary - } RenderingStyleType; - - /** Set/Get the vector data input of this process object. */ - using Superclass::SetInput; - virtual void SetInput(const VectorDataType *input); - virtual void SetInput(unsigned int idx, const VectorDataType *input); - const VectorDataType * GetInput(void); - const VectorDataType * GetInput(unsigned int idx); - - /** Set the size of the output image. */ - itkSetMacro(Size, SizeType); - - /** Get the size of the output image. */ - itkGetConstReferenceMacro(Size, SizeType); - - /** Set the origin of the vector data. - * \sa GetOrigin() */ - itkSetMacro(Origin, OriginType); - virtual void SetOrigin(const double origin[2]); - virtual void SetOrigin(const float origin[2]); - - itkGetConstReferenceMacro(Origin, OriginType); - - /** Set the spacing (size of a pixel) of the vector data. - * \sa GetSpacing() */ - virtual void SetSpacing(const SpacingType& spacing); - virtual void SetSpacing(const double spacing[2]); - virtual void SetSpacing(const float spacing[2]); - - itkGetConstReferenceMacro(Spacing, SpacingType); - - /** Get/Set methods for the scale factor */ - itkSetMacro(ScaleFactor, double); - itkGetMacro(ScaleFactor, double); - - /** */ - void AddStyle(const std::string& style) - { - m_StyleList.push_back(style); - } - - /** Clear the style list */ - void ClearStyleList() - { - m_StyleList.clear(); - } - - /** Specify if the output image is to be uses as an overlar - * (with transparent background) or not (with blue background). - */ - itkSetMacro(UseAsOverlay, bool); - itkGetMacro(UseAsOverlay, bool); - itkBooleanMacro(UseAsOverlay); - - /** Get/Set methods for the rendering style type (OSM or Binary) */ - itkSetMacro(RenderingStyleType, RenderingStyleType); - itkGetMacro(RenderingStyleType, RenderingStyleType); - - /** Add accessors to the font filename */ - itkSetStringMacro(FontFileName); - itkGetStringMacro(FontFileName); - - /** Add accessors to the Projection in the WKT format */ - itkSetStringMacro(VectorDataProjectionWKT); - itkGetStringMacro(VectorDataProjectionWKT); - -protected: - /** Constructor */ - VectorDataToImageFilter(); - /** Destructor */ - virtual ~VectorDataToImageFilter() {} - /**PrintSelf method */ - virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; - - virtual void GenerateOutputInformation(); - - virtual void GenerateData(void); - - virtual void BeforeThreadedGenerateData(); - -private: - VectorDataToImageFilter(const Self &); //purposely not implemented - void operator =(const Self&); //purposely not implemented - - void ProcessNode(InternalTreeNodeType * source, datasource_ptr mDatasource); - - SpacingType m_Spacing; - OriginType m_Origin; - SizeType m_Size; - IndexType m_StartIndex; - DirectionType m_Direction; - - // font file name - std::string m_FontFileName; - - //This factor is used to flip the data on the Y axis when using a - //sensor model geometry (where the Y coordinate increases top-down) - int m_SensorModelFlip; - - //this parameter is used only in the case of sensor geometry - //to adjust the scale - double m_ScaleFactor; - - //style list - std::vector<std::string> m_StyleList; - - //Overlay option: change the backgroup (blue or transparent) - bool m_UseAsOverlay; - - //Projection in the proj.4 format (for mapnik) - std::string m_VectorDataProjectionProj4; - - //Projection in the WKT format - std::string m_VectorDataProjectionWKT; - - //Rendering style type - RenderingStyleType m_RenderingStyleType; - - //RGBA Converter - typename RGBAConverterType::Pointer m_RGBAConverter; - - //Internal Tiling - unsigned int m_NbTile; - std::vector<RegionType> m_TilingRegions; - std::vector<mapnik::Map> m_Maps; - std::vector< std::vector<typename VectorDataExtractROIType::Pointer> > - m_VectorDataExtractors; - -}; // end class -} // end namespace otb - -#ifndef OTB_MANUAL_INSTANTIATION -#include "otbVectorDataToImageFilter.txx" -#endif - -#endif diff --git a/Modules/Filtering/VectorDataRendering/include/otbVectorDataToImageFilter.txx b/Modules/Filtering/VectorDataRendering/include/otbVectorDataToImageFilter.txx deleted file mode 100644 index 582bec8cc028bdcee75dec72c0d7a5751bff1f5c..0000000000000000000000000000000000000000 --- a/Modules/Filtering/VectorDataRendering/include/otbVectorDataToImageFilter.txx +++ /dev/null @@ -1,663 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -#ifndef otbVectorDataToImageFilter_txx -#define otbVectorDataToImageFilter_txx - -#include <sstream> -#include "otbVectorDataToImageFilter.h" -#include "itkImageRegionIterator.h" -#include "itkImageIteratorWithIndex.h" -#include "otbVectorDataStyle.h" -#include "itkRGBAPixel.h" - -#include "ogr_spatialref.h" - -#include "otbMapnikAdapter.h" - -namespace otb -{ - -/** - * Constructor - */ -template <class TVectorData, class TImage> -VectorDataToImageFilter<TVectorData, TImage> -::VectorDataToImageFilter() : - m_StyleList(), - m_UseAsOverlay(true), - m_RenderingStyleType(OSM) -{ - this->SetNumberOfRequiredInputs(1); - m_Spacing.Fill(1.0); - m_Origin.Fill(0.0); - m_Direction.SetIdentity(); - m_Size.Fill(0); - m_StartIndex.Fill(0); - m_SensorModelFlip = 1; - m_ScaleFactor = 1.0; - m_VectorDataProjectionProj4 = ""; - m_VectorDataProjectionWKT = ""; -} - -template <class TVectorData, class TImage> -void -VectorDataToImageFilter<TVectorData, TImage> -::SetInput(const VectorDataType *input) -{ - // Process object is not const-correct so the const_cast is required here - this->itk::ProcessObject::SetNthInput(0, - const_cast<VectorDataType *>(input)); -} - -template <class TVectorData, class TImage> -void -VectorDataToImageFilter<TVectorData, TImage> -::SetInput(unsigned int idx, const VectorDataType *input) -{ - // Process object is not const-correct so the const_cast is required here - this->itk::ProcessObject::SetNthInput(idx, - const_cast<VectorDataType *>(input)); -} - -template <class TVectorData, class TImage> -const typename VectorDataToImageFilter<TVectorData, TImage>::VectorDataType * -VectorDataToImageFilter<TVectorData, TImage> -::GetInput(void) -{ - if (this->GetNumberOfInputs() < 1) - { - return 0; - } - - return static_cast<const TVectorData *> - (this->itk::ProcessObject::GetInput(0)); -} - -template <class TVectorData, class TImage> -const typename VectorDataToImageFilter<TVectorData, TImage>::VectorDataType * -VectorDataToImageFilter<TVectorData, TImage> -::GetInput(unsigned int idx) -{ - return static_cast<const TVectorData *> - (this->itk::ProcessObject::GetInput(idx)); -} - -//---------------------------------------------------------------------------- -template <class TVectorData, class TImage> -void -VectorDataToImageFilter<TVectorData, TImage> -::SetSpacing(const SpacingType& spacing) -{ - if (this->m_Spacing != spacing) - { - this->m_Spacing = spacing; - this->Modified(); - } -} - -//---------------------------------------------------------------------------- -template <class TVectorData, class TImage> -void -VectorDataToImageFilter<TVectorData, TImage> -::SetSpacing(const double spacing[2]) -{ - SpacingType s(spacing); - this->SetSpacing(s); -} - -//---------------------------------------------------------------------------- -template <class TVectorData, class TImage> -void -VectorDataToImageFilter<TVectorData, TImage> -::SetSpacing(const float spacing[2]) -{ - itk::Vector<float, 2> sf(spacing); - SpacingType s; - s.CastFrom(sf); - this->SetSpacing(s); -} - -//---------------------------------------------------------------------------- -template <class TVectorData, class TImage> -void -VectorDataToImageFilter<TVectorData, TImage> -::SetOrigin(const double origin[2]) -{ - OriginType p(origin); - this->SetOrigin(p); -} - -//---------------------------------------------------------------------------- -template <class TVectorData, class TImage> -void -VectorDataToImageFilter<TVectorData, TImage> -::SetOrigin(const float origin[2]) -{ - itk::Point<float, 2> of(origin); - OriginType p; - p.CastFrom(of); - this->SetOrigin(p); -} - -/** -* Inform pipeline of required output region -*/ -template <class TVectorData, class TImage> -void -VectorDataToImageFilter<TVectorData, TImage> -::GenerateOutputInformation() -{ - // we can't call the superclass method here. - - // get pointers to the input and output - ImagePointer outputPtr = this->GetOutput(); - if (!outputPtr) - { - return; - } - - // Set the size of the output region - typename TImage::RegionType outputLargestPossibleRegion; - outputLargestPossibleRegion.SetSize(m_Size); - outputLargestPossibleRegion.SetIndex(m_StartIndex); - outputPtr->SetLargestPossibleRegion(outputLargestPossibleRegion); - - // Set spacing and origin - outputPtr->SetSpacing(m_Spacing); - outputPtr->SetOrigin(m_Origin); - outputPtr->SetDirection(m_Direction); - - itk::MetaDataDictionary& dict = outputPtr->GetMetaDataDictionary(); - itk::EncapsulateMetaData<std::string> (dict, MetaDataKey::ProjectionRefKey, - static_cast<std::string>(m_VectorDataProjectionWKT)); - - //TODO update or check the projection information - - return; -} - -/** -* BeforeThreadedGenerateData -*/ -template <class TVectorData, class TImage> -void -VectorDataToImageFilter<TVectorData, TImage> -::BeforeThreadedGenerateData(void) -{ - - Superclass::BeforeThreadedGenerateData(); - - //Font Handling - if(!m_FontFileName.empty()) - mapnik::freetype_engine::register_font(m_FontFileName); - - //Handle the style type using helper class - otb::VectorDataStyle::Pointer styleLoader = otb::VectorDataStyle::New(); - styleLoader->SetScaleFactor(m_ScaleFactor); - - //We assume that all the data are reprojected before using OTB. - VectorDataConstPointer input = this->GetInput(); - //Converting the projection string to the proj.4 format - itk::ExposeMetaData<std::string>( - input->GetMetaDataDictionary(), MetaDataKey::ProjectionRefKey, m_VectorDataProjectionWKT); - otbMsgDebugMacro(<< "WKT -> " << m_VectorDataProjectionWKT); - - m_SensorModelFlip = 1; - - if (m_VectorDataProjectionWKT == "") - { - //We assume that it is an image in sensor model geometry - //and tell mapnik that this is utm - //(with a resolution of 1m per unit) - m_VectorDataProjectionProj4 = "+proj=utm +zone=31 +ellps=WGS84"; - m_SensorModelFlip = -1; - otbMsgDevMacro(<< "The output map will be in sensor geometry"); - } - else - { - OGRSpatialReferenceH oSRS = OSRNewSpatialReference(m_VectorDataProjectionWKT.c_str()); - char * pszProj4; - OSRExportToProj4(oSRS, &pszProj4); - m_VectorDataProjectionProj4 = pszProj4; - CPLFree(pszProj4); - OSRRelease(oSRS); - m_SensorModelFlip = 1; - otbMsgDevMacro(<< "The output map will be carto/geo geometry"); - } - otbMsgDebugMacro(<< "Proj.4 -> " << m_VectorDataProjectionProj4); - - //Internal Tiling Support - //Workaround to overcome mapnik maximum tile size limitation - ImagePointer output = this->GetOutput(); - RegionType requestedRegion = output->GetRequestedRegion(); - otbMsgDevMacro("requestedRegion: " << requestedRegion); - - m_NbTile = (vcl_pow(std::max(vcl_floor((double)requestedRegion.GetSize()[0] / 16000), - vcl_floor((double)requestedRegion.GetSize()[1] / 16000))+1, 2)); - - //std::cout << "nbTile: " << m_NbTile << std::endl; - //std::cout << "requestedRegion: " << requestedRegion << std::endl; - - m_TilingRegions.resize(m_NbTile); - m_Maps.resize(m_NbTile); - m_VectorDataExtractors.resize(m_NbTile); - - unsigned int tilingRegionsIdx = 0; - unsigned int stdXOffset; - unsigned int stdYOffset; - - stdXOffset = vcl_floor((double)requestedRegion.GetSize()[0]/ (m_NbTile/2))+1; - stdYOffset = vcl_floor((double)requestedRegion.GetSize()[1]/ (m_NbTile/2))+1; - - for(unsigned int i=0; i < vcl_floor((double)(m_NbTile)/2 + 0.5); ++i) - { - for(unsigned int j=0; j < vcl_floor((double)(m_NbTile)/2 + 0.5); ++j) - { - //Set Regions - SizeType size; - IndexType index; - if(m_NbTile == 1) - { - index = requestedRegion.GetIndex(); - size = requestedRegion.GetSize(); - } - else - { - index[0] = requestedRegion.GetIndex()[0] + i * stdXOffset; - index[1] = requestedRegion.GetIndex()[1] + j * stdYOffset; - - size[0] = std::min((unsigned int)(requestedRegion.GetSize()[0] - index[0]), stdXOffset); - size[1] = std::min((unsigned int)(requestedRegion.GetSize()[1] - index[1]), stdYOffset); - } - m_TilingRegions[tilingRegionsIdx].SetIndex(index); - m_TilingRegions[tilingRegionsIdx].SetSize(size); - - //std::cout << "tileRegions[" << tilingRegionsIdx << "] : " - // << m_TilingRegions[tilingRegionsIdx] << std::endl; - - //Set Maps - m_Maps[tilingRegionsIdx] = mapnik::Map(); - - ////Load the style type - switch (m_RenderingStyleType) - { - case OSM: - { - styleLoader->LoadOSMStyle(m_Maps[tilingRegionsIdx]); - if (m_UseAsOverlay) - { - //Set the default backgroup to transparent - m_Maps[tilingRegionsIdx].set_background(mapnik::color(255, 255, 255, 0)); - } - else - { - m_Maps[tilingRegionsIdx].set_background(mapnik::color("#b5d0d0")); - } - break; - } - case Binary: - { - styleLoader->LoadBinaryRasterizationStyle(m_Maps[tilingRegionsIdx]); - //Set the backgroup to white - m_Maps[tilingRegionsIdx].set_background(mapnik::color("#ffffff")); - break; - } - default: - { - itkExceptionMacro(<< "Style Type Not Supported!"); - break; - } - } - - ////Set Mapnik projection information - m_Maps[tilingRegionsIdx].set_srs(m_VectorDataProjectionProj4); - - //Set VectorData extracts - m_VectorDataExtractors[tilingRegionsIdx].resize(this->GetNumberOfInputs()); - for (unsigned int idx = 0; idx < this->GetNumberOfInputs(); ++idx) - { - if (this->GetInput(idx)) - { - RemoteSensingRegionType rsRegion; - SizePhyType sizePhy; - sizePhy[0] = size[0] * m_Spacing[0]; - sizePhy[1] = size[1] * m_Spacing[1]; - rsRegion.SetSize(sizePhy); - OriginType origin; - origin[0] = m_Origin[0] + (static_cast<double>(index[0]) - 0.5) * m_Spacing[0]; - origin[1] = m_Origin[1] + (static_cast<double>(index[1]) - 0.5) * m_Spacing[1]; - rsRegion.SetOrigin(origin); - rsRegion.SetRegionProjection(m_VectorDataProjectionWKT); - - //std::cout << "m_SensorModelFlip: " << m_SensorModelFlip << std::endl; - //std::cout << "rsTileRegions[" << tilingRegionsIdx << "] : " - // << rsRegion << std::endl; - - m_VectorDataExtractors[tilingRegionsIdx][idx] = VectorDataExtractROIType::New(); - m_VectorDataExtractors[tilingRegionsIdx][idx]->SetRegion(rsRegion); - m_VectorDataExtractors[tilingRegionsIdx][idx]->SetInput(this->GetInput(idx)); - } - } - - tilingRegionsIdx ++; - } - } -} - -/** - * Generate Data - */ -template <class TVectorData, class TImage> -void -VectorDataToImageFilter<TVectorData, TImage> -::GenerateData(void) -{ - - this->AllocateOutputs(); - - this->BeforeThreadedGenerateData(); - - if (m_StyleList.size() == 0) - { - switch (m_RenderingStyleType) - { - case OSM: - { - //Add default styles - itkExceptionMacro(<< "No style is provided for the vector data"); - break; - } - case Binary: - { - //Add default styles - this->AddStyle("binary-rasterization"); - break; - } - default: - { - itkExceptionMacro(<< "No style is provided for the vector data"); - break; - } - } - } - - ImagePointer output = this->GetOutput(); - - for (unsigned int tileIdx = 0; tileIdx < m_NbTile; ++tileIdx) - { - //Delete the previous layers from the map - int numberLayer = mapnik_otb::get_num_layer(m_Maps[tileIdx]); - for (int i = numberLayer - 1; i >= 0; i--) //yes, int. - { - m_Maps[tileIdx].removeLayer(i); - } - m_Maps[tileIdx].resize(m_TilingRegions[tileIdx].GetSize()[0], m_TilingRegions[tileIdx].GetSize()[1]); - - RemoteSensingRegionType rsRegion; - - for (unsigned int vdIdx = 0; vdIdx < this->GetNumberOfInputs(); ++vdIdx) - { - if (this->GetInput(vdIdx)) - { - datasource_ptr mDatasource = datasource_ptr(new mapnik::memory_datasource); - - rsRegion = m_VectorDataExtractors[tileIdx][vdIdx]->GetRegion(); - - m_VectorDataExtractors[tileIdx][vdIdx]->Update(); - VectorDataConstPointer input = m_VectorDataExtractors[tileIdx][vdIdx]->GetOutput(); - InternalTreeNodeType * inputRoot = const_cast<InternalTreeNodeType *>(input->GetDataTree()->GetRoot()); - - ProcessNode(inputRoot, mDatasource); - otbMsgDevMacro("Datasource size: " << mDatasource->size()); - - std::stringstream layerName; - layerName << "layer-" << tileIdx; - mapnik::layer lyr(layerName.str()); - lyr.set_srs(m_VectorDataProjectionProj4); - lyr.set_datasource(mDatasource); - - for (unsigned int i = 0; i < m_StyleList.size(); ++i) - { - lyr.add_style(m_StyleList[i]); - } - - m_Maps[tileIdx].addLayer(lyr); - } - } - assert((m_SensorModelFlip == 1) || (m_SensorModelFlip == -1)); - - mapnik_otb::box2d envelope( - rsRegion.GetOrigin(0), - m_SensorModelFlip*(rsRegion.GetOrigin(1) + rsRegion.GetSize(1)), - rsRegion.GetOrigin(0) + rsRegion.GetSize(0), - m_SensorModelFlip*(rsRegion.GetOrigin(1)) - ); - - mapnik_otb::zoom_to_box(&m_Maps[tileIdx], envelope); - otbMsgDebugMacro(<< "Envelope: " << envelope); - - otbMsgDebugMacro(<< "Map scale: " << m_Maps[tileIdx].scale_denominator()); - mapnik::image_32 buf(mapnik_otb::get_width(m_Maps[tileIdx]), - mapnik_otb::get_height(m_Maps[tileIdx])); - mapnik::agg_renderer<mapnik::image_32> ren(m_Maps[tileIdx], buf); - ren.apply(); - - const unsigned char * src = buf.raw_data(); - - itk::ImageRegionIterator<ImageType> it(output, m_TilingRegions[tileIdx]); - - for (it.GoToBegin(); !it.IsAtEnd(); ++it) - { - itk::RGBAPixel<unsigned char> pix; - pix[0] = *src; - pix[1] = *(src+1); - pix[2] = *(src+2); - pix[3] = *(src+3); - src += 4; - - it.Set(m_RGBAConverter->Convert(pix)); - } - } -} - -template <class TVectorData, class TImage> -void -VectorDataToImageFilter<TVectorData, TImage> -::ProcessNode(InternalTreeNodeType * source, datasource_ptr mDatasource) -{ - typedef typename VectorDataType::DataNodeType DataNodeType; - typedef typename DataNodeType::Pointer DataNodePointerType; - - // Get the children list from the input node - ChildrenListType children = source->GetChildrenList(); - - // For each child - for (typename ChildrenListType::iterator it = children.begin(); it != children.end(); ++it) - { - // Copy input DataNode info - DataNodePointerType dataNode = (*it)->Get(); - - switch (dataNode->GetNodeType()) - { - case otb::ROOT: - { - ProcessNode((*it), mDatasource); - break; - } - case otb::DOCUMENT: - { - ProcessNode((*it), mDatasource); - break; - } - case otb::FOLDER: - { - ProcessNode((*it), mDatasource); - break; - } - case FEATURE_POINT: - { - mapnik_otb::geom* point = mapnik_otb::create_geom(mapnik::Point); - - point->move_to(dataNode->GetPoint()[0], m_SensorModelFlip * dataNode->GetPoint()[1]); -// std::cout << dataNode->GetPoint()[0] << ", " << dataNode->GetPoint()[1] << std::endl; - - typedef boost::shared_ptr<mapnik::raster> raster_ptr; - typedef mapnik::feature<mapnik_otb::geom, raster_ptr> Feature; - typedef boost::shared_ptr<Feature> feature_ptr; - - feature_ptr mfeature = feature_ptr(new Feature(1)); - mfeature->add_geometry(point); - - mapnik::transcoder tr("ISO-8859-15"); - - if (dataNode->HasField("place_name")) - boost::put(*mfeature, "name", - tr.transcode((dataNode->GetFieldAsString("place_name")).c_str())); - - boost::put(*mfeature, "place", tr.transcode("city")); - boost::put(*mfeature, "capital", tr.transcode("yes")); //FIXME more a question of style - - boost::put(*mfeature, "geometry", tr.transcode("point")); - - mDatasource->push(mfeature); - - break; - } - case otb::FEATURE_LINE: - { - mapnik_otb::geom* line = mapnik_otb::create_geom(mapnik::LineString); - - typedef typename DataNodeType::LineType::VertexListConstIteratorType VertexIterator; - VertexIterator itVertex = dataNode->GetLine()->GetVertexList()->Begin(); - while (itVertex != dataNode->GetLine()->GetVertexList()->End()) - { -// std::cout << itVertex.Value()[0] << ", " << itVertex.Value()[1] << std::endl; - line->line_to(itVertex.Value()[0], m_SensorModelFlip * itVertex.Value()[1]); - ++itVertex; - } - -// std::cout << "Num points: " << line->num_points() << std::endl; - - typedef boost::shared_ptr<mapnik::raster> raster_ptr; - typedef mapnik::feature<mapnik_otb::geom, raster_ptr> Feature; - typedef boost::shared_ptr<Feature> feature_ptr; - - feature_ptr mfeature = feature_ptr(new Feature(1)); - mfeature->add_geometry(line); - - mapnik::transcoder tr("ISO-8859-15"); - - if (dataNode->HasField("name")) - boost::put(*mfeature, "name", - tr.transcode((dataNode->GetFieldAsString("name")).c_str())); - if (dataNode->HasField("NAME")) - boost::put(*mfeature, "name", - tr.transcode((dataNode->GetFieldAsString("NAME")).c_str())); - -// std::cout << mfeature->props().size() << std::endl; -// std::cout << " -> " << (*mfeature)["name"] << std::endl; - -// std::cout << "Name: " << dataNode->GetFieldAsString("NAME") << std::endl; -// std::cout << "Type: " << dataNode->GetFieldAsString("TYPE") << std::endl; -// std::cout << "OSM ID: " << dataNode->GetFieldAsString("osm_id") << std::endl; - - if (dataNode->HasField("type")) - boost::put(*mfeature, "highway", - tr.transcode((dataNode->GetFieldAsString("type")).c_str())); - if (dataNode->HasField("TYPE")) - boost::put(*mfeature, "highway", - tr.transcode((dataNode->GetFieldAsString("TYPE")).c_str())); - - boost::put(*mfeature, "geometry", tr.transcode("line")); - - mDatasource->push(mfeature); - - break; - } - case FEATURE_POLYGON: - { - mapnik_otb::geom* polygon = mapnik_otb::create_geom(mapnik::Polygon); - - typedef typename DataNodeType::PolygonType::VertexListConstIteratorType VertexIterator; - VertexIterator itVertex = dataNode->GetPolygonExteriorRing()->GetVertexList()->Begin(); - while (itVertex != dataNode->GetPolygonExteriorRing()->GetVertexList()->End()) - { - polygon->line_to(itVertex.Value()[0], m_SensorModelFlip * itVertex.Value()[1]); - ++itVertex; - } - - typedef boost::shared_ptr<mapnik::raster> raster_ptr; - typedef mapnik::feature<mapnik_otb::geom, raster_ptr> Feature; - typedef boost::shared_ptr<Feature> feature_ptr; - - feature_ptr mfeature = feature_ptr(new Feature(1)); - mfeature->add_geometry(polygon); - - mapnik::transcoder tr("ISO-8859-15"); - - boost::put(*mfeature, "geometry", tr.transcode("polygon")); - - mDatasource->push(mfeature); - - break; - } - case FEATURE_MULTIPOINT: - { - itkExceptionMacro( - << "This type (FEATURE_MULTIPOINT) is not handle (yet) by VectorDataToImageFilter(), please request for it"); - break; - } - case FEATURE_MULTILINE: - { - itkExceptionMacro( - << "This type (FEATURE_MULTILINE) is not handle (yet) by VectorDataToImageFilter(), please request for it"); - break; - } - case FEATURE_MULTIPOLYGON: - { - itkExceptionMacro( - << "This type (FEATURE_MULTIPOLYGON) is not handle (yet) by VectorDataToImageFilter(), please request for it"); - break; - } - case FEATURE_COLLECTION: - { - itkExceptionMacro( - << "This type (FEATURE_COLLECTION) is not handle (yet) by VectorDataToImageFilter(), please request for it"); - break; - } - } - } -} - -/** - * PrintSelf Method - */ -template <class TVectorData, class TImage> -void -VectorDataToImageFilter<TVectorData, TImage> -::PrintSelf(std::ostream& os, itk::Indent indent) const -{ - Superclass::PrintSelf(os, indent); -} -} - -#endif diff --git a/Modules/Filtering/VectorDataRendering/test/CMakeLists.txt b/Modules/Filtering/VectorDataRendering/test/CMakeLists.txt index fe429bd54e92e0ef0028f4497fbfb4a72ecebf4d..60f81b059887a5801dcd583000613a8d0279f200 100644 --- a/Modules/Filtering/VectorDataRendering/test/CMakeLists.txt +++ b/Modules/Filtering/VectorDataRendering/test/CMakeLists.txt @@ -26,7 +26,6 @@ otbVectorDataToMapFilterWorld.cxx otbVectorDataToMapFilter.cxx otbVectorDataToMapFilterNew.cxx otbVectorDataToMapFilterNoFonts.cxx -otbVectorDataToImageFilter.cxx otbVectorDataToMapFilterSensorModel.cxx ) @@ -82,25 +81,6 @@ otb_add_test(NAME coTvVectorDataToMapFilterNoFonts COMMAND otbVectorDataRenderin ${TEMP}/coTvVectorDataToMapFilterNoFonts.png ) -otb_add_test(NAME coTvVectorDataToImageFilter COMMAND otbVectorDataRenderingTestDriver - --compare-image ${NOTOL} - ${BASELINE}/coTvVectorDataToMapFilter.png - ${TEMP}/coTvVectorDataToImageFilter.png - otbVectorDataToImageFilter - LARGEINPUT{VECTOR/MidiPyrenees/roads.shp} - ${TEMP}/coTvVectorDataToImageFilter.png - ${INPUTDATA}/DejaVuSans.ttf # font - ) - -otb_add_test(NAME coTvVectorDataToImageFilterBinary COMMAND otbVectorDataRenderingTestDriver - --compare-image ${NOTOL} - ${BASELINE}/coTvVectorDataToMapFilterBinary.png - ${TEMP}/coTvVectorDataToImageFilterBinary.png - otbVectorDataToImageFilterBinary - LARGEINPUT{VECTOR/MidiPyrenees/roads.shp} - ${TEMP}/coTvVectorDataToImageFilterBinary.png - ) - otb_add_test(NAME coTvVectorDataToMapFilterSensorModel COMMAND otbVectorDataRenderingTestDriver --compare-image ${NOTOL} ${BASELINE}/coTvVectorDataToMapFilterSensorModel.png diff --git a/Modules/Filtering/VectorDataRendering/test/otbVectorDataRenderingTestDriver.cxx b/Modules/Filtering/VectorDataRendering/test/otbVectorDataRenderingTestDriver.cxx index dfa75da9b49267eb3ea4947a0cb2e4281dbefea4..ceba95df4d5b612bdf08e29ae96fc9574c08704c 100644 --- a/Modules/Filtering/VectorDataRendering/test/otbVectorDataRenderingTestDriver.cxx +++ b/Modules/Filtering/VectorDataRendering/test/otbVectorDataRenderingTestDriver.cxx @@ -27,7 +27,5 @@ void RegisterTests() REGISTER_TEST(otbVectorDataToMapFilterBinary); REGISTER_TEST(otbVectorDataToMapFilterNew); REGISTER_TEST(otbVectorDataToMapFilterNoFonts); - REGISTER_TEST(otbVectorDataToImageFilter); - REGISTER_TEST(otbVectorDataToImageFilterBinary); REGISTER_TEST(otbVectorDataToMapFilterSensorModel); } diff --git a/Modules/Filtering/VectorDataRendering/test/otbVectorDataToImageFilter.cxx b/Modules/Filtering/VectorDataRendering/test/otbVectorDataToImageFilter.cxx deleted file mode 100644 index ccb0b62143b13f1fe8f778ccb03399475fdd0622..0000000000000000000000000000000000000000 --- a/Modules/Filtering/VectorDataRendering/test/otbVectorDataToImageFilter.cxx +++ /dev/null @@ -1,185 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -#include "otbVectorDataFileReader.h" -#include "otbImageFileWriter.h" -#include "otbVectorData.h" -#include "otbVectorDataProjectionFilter.h" -#include <fstream> -#include <iostream> - -#include "itkRGBAPixel.h" -#include "otbImage.h" -#include "otbVectorDataToImageFilter.h" - -int otbVectorDataToImageFilter(int argc, char * argv []) -{ - - if (argc < 4) - { - std::cout << argv[0] << " <input vector filename> <input image filename> <font filename>" << std::endl; - - return EXIT_FAILURE; - } - - //Read the vector data - typedef otb::VectorData<> VectorDataType; - typedef otb::VectorDataFileReader<VectorDataType> VectorDataFileReaderType; - VectorDataFileReaderType::Pointer reader = VectorDataFileReaderType::New(); - - reader->SetFileName(argv[1]); - - //Reproject the vector data in the proper projection - typedef otb::VectorDataProjectionFilter<VectorDataType, VectorDataType> ProjectionFilterType; - ProjectionFilterType::Pointer projection = ProjectionFilterType::New(); - projection->SetInput(reader->GetOutput()); - - std::string projectionRefWkt = - "PROJCS[\"UTM Zone 31, Northern Hemisphere\", GEOGCS[\"WGS 84\", DATUM[\"WGS_1984\", SPHEROID[\"WGS 84\", 6378137, 298.257223563, AUTHORITY[\"EPSG\",\"7030\"]], TOWGS84[0, 0, 0, 0, 0, 0, 0], AUTHORITY[\"EPSG\",\"6326\"]], PRIMEM[\"Greenwich\", 0, AUTHORITY[\"EPSG\",\"8901\"]], UNIT[\"degree\", 0.0174532925199433, AUTHORITY[\"EPSG\",\"9108\"]], AXIS[\"Lat\", NORTH], AXIS[\"Long\", EAST], AUTHORITY[\"EPSG\",\"4326\"]], PROJECTION[\"Transverse_Mercator\"], PARAMETER[\"latitude_of_origin\", 0], PARAMETER[\"central_meridian\", 3], PARAMETER[\"scale_factor\", 0.9996], PARAMETER[\"false_easting\", 500000], PARAMETER[\"false_northing\", 0], UNIT[\"Meter\", 1]]"; - - projection->SetOutputProjectionRef(projectionRefWkt); - - //Convert the vector data into an image - typedef itk::RGBAPixel<unsigned char> PixelType; - typedef otb::Image<PixelType, 2> ImageType; - - ImageType::SizeType size; - size[0] = 500; - size[1] = 500; - - ImageType::PointType origin; - origin[0] = 374149.980555821; //UL easting - origin[1] = 4829183.99443839; //UL northing - - ImageType::SpacingType spacing; - spacing[0] = 0.6; - spacing[1] = -0.6; - - typedef otb::RemoteSensingRegion<double> RegionType; - RegionType region; - RegionType::SizeType sizeInUnit; - sizeInUnit[0] = size[0] * spacing[0]; - sizeInUnit[1] = size[1] * spacing[1]; - region.SetSize(sizeInUnit); - region.SetOrigin(origin); - region.SetRegionProjection(projectionRefWkt); - - typedef otb::VectorDataExtractROI<VectorDataType> ExtractROIType; - ExtractROIType::Pointer extractROI = ExtractROIType::New(); - extractROI->SetRegion(region); - extractROI->SetInput(projection->GetOutput()); - - typedef otb::VectorDataToImageFilter<VectorDataType, ImageType> VectorDataToImageFilterType; - VectorDataToImageFilterType::Pointer vectorDataRendering = VectorDataToImageFilterType::New(); - vectorDataRendering->SetInput(extractROI->GetOutput()); - - vectorDataRendering->SetSize(size); - vectorDataRendering->SetOrigin(origin); - vectorDataRendering->SetSpacing(spacing); - vectorDataRendering->SetFontFileName(argv[3]); - vectorDataRendering->AddStyle("minor-roads-casing"); - vectorDataRendering->AddStyle("roads-text"); - - //Save the image in a file - typedef otb::ImageFileWriter<ImageType> WriterType; - WriterType::Pointer writer = WriterType::New(); - writer->SetInput(vectorDataRendering->GetOutput()); - writer->SetFileName(argv[2]); - writer->Update(); - - return EXIT_SUCCESS; -} - -int otbVectorDataToImageFilterBinary(int argc, char * argv []) -{ - - if (argc < 3) - { - std::cout << argv[0] << " <input vector filename> <input image filename>" << std::endl; - - return EXIT_FAILURE; - } - - //Read the vector data - typedef otb::VectorData<> VectorDataType; - typedef otb::VectorDataFileReader<VectorDataType> VectorDataFileReaderType; - VectorDataFileReaderType::Pointer reader = VectorDataFileReaderType::New(); - - reader->SetFileName(argv[1]); - - //Reproject the vector data in the proper projection - typedef otb::VectorDataProjectionFilter<VectorDataType, VectorDataType> ProjectionFilterType; - ProjectionFilterType::Pointer projection = ProjectionFilterType::New(); - projection->SetInput(reader->GetOutput()); - - std::string projectionRefWkt = - "PROJCS[\"UTM Zone 31, Northern Hemisphere\", GEOGCS[\"WGS 84\", DATUM[\"WGS_1984\", SPHEROID[\"WGS 84\", 6378137, 298.257223563, AUTHORITY[\"EPSG\",\"7030\"]], TOWGS84[0, 0, 0, 0, 0, 0, 0], AUTHORITY[\"EPSG\",\"6326\"]], PRIMEM[\"Greenwich\", 0, AUTHORITY[\"EPSG\",\"8901\"]], UNIT[\"degree\", 0.0174532925199433, AUTHORITY[\"EPSG\",\"9108\"]], AXIS[\"Lat\", NORTH], AXIS[\"Long\", EAST], AUTHORITY[\"EPSG\",\"4326\"]], PROJECTION[\"Transverse_Mercator\"], PARAMETER[\"latitude_of_origin\", 0], PARAMETER[\"central_meridian\", 3], PARAMETER[\"scale_factor\", 0.9996], PARAMETER[\"false_easting\", 500000], PARAMETER[\"false_northing\", 0], UNIT[\"Meter\", 1]]"; - - projection->SetOutputProjectionRef(projectionRefWkt); - - //Convert the vector data into an image - typedef itk::RGBAPixel<unsigned char> PixelType; - typedef otb::Image<PixelType, 2> ImageType; - - ImageType::SizeType size; - size[0] = 500; - size[1] = 500; - - ImageType::PointType origin; - origin[0] = 374149.980555821; //UL easting - origin[1] = 4829183.99443839; //UL northing - - ImageType::SpacingType spacing; - spacing[0] = 0.6; - spacing[1] = -0.6; - - typedef otb::RemoteSensingRegion<double> RegionType; - RegionType region; - RegionType::SizeType sizeInUnit; - sizeInUnit[0] = size[0] * spacing[0]; - sizeInUnit[1] = size[1] * spacing[1]; - region.SetSize(sizeInUnit); - region.SetOrigin(origin); - region.SetRegionProjection(projectionRefWkt); - - typedef otb::VectorDataExtractROI<VectorDataType> ExtractROIType; - ExtractROIType::Pointer extractROI = ExtractROIType::New(); - extractROI->SetRegion(region); - extractROI->SetInput(projection->GetOutput()); - - typedef otb::VectorDataToImageFilter<VectorDataType, ImageType> VectorDataToImageFilterType; - VectorDataToImageFilterType::Pointer vectorDataRendering = VectorDataToImageFilterType::New(); - vectorDataRendering->SetInput(extractROI->GetOutput()); - - vectorDataRendering->SetSize(size); - vectorDataRendering->SetOrigin(origin); - vectorDataRendering->SetSpacing(spacing); - vectorDataRendering->SetRenderingStyleType(VectorDataToImageFilterType::Binary); - - //Save the image in a file - typedef otb::ImageFileWriter<ImageType> WriterType; - WriterType::Pointer writer = WriterType::New(); - writer->SetInput(vectorDataRendering->GetOutput()); - writer->SetFileName(argv[2]); - writer->Update(); - - return EXIT_SUCCESS; -} diff --git a/Modules/IO/IOGDAL/src/otbGDALImageIO.cxx b/Modules/IO/IOGDAL/src/otbGDALImageIO.cxx index c06cdd83acf3bd09fd2cd55cedf2114258e950a2..968ec2a5fff7a52fb1aa9292a7b85aaf9a4728c6 100644 --- a/Modules/IO/IOGDAL/src/otbGDALImageIO.cxx +++ b/Modules/IO/IOGDAL/src/otbGDALImageIO.cxx @@ -1205,7 +1205,23 @@ void GDALImageIO::InternalReadImageInformation() if ((GDALGetRasterColorInterpretation(hBand) == GCI_PaletteIndex) && (hTable = GDALGetRasterColorTable(hBand)) != ITK_NULLPTR) { - m_IsIndexed = true; + + // Mantis: 1049 : OTB does not handle tif with NBITS=1 properly + // When a palette is available and pixel type is Byte, the image is + // automatically read as a color image (using the palette). Perhaps this + // behaviour should be restricted. Comment color table interpretation in + // gdalimageio + + // FIXME: Better support of color table in OTB + // - disable palette conversion in GDALImageIO (the comments in this part + // of the code are rather careful) + // - GDALImageIO should report the palette to ImageFileReader (as a metadata ? + // a kind of LUT ?). + // - ImageFileReader should use a kind of adapter filter to convert the mono + // image into color. + + // Do not set indexed image attribute to true + //m_IsIndexed = true; unsigned int ColorEntryCount = GDALGetColorEntryCount(hTable); diff --git a/Modules/IO/ImageIO/test/CMakeLists.txt b/Modules/IO/ImageIO/test/CMakeLists.txt index 5f720d46cb8607683bb9794d94c1943a10efeff8..d8374f8955993381a7db0634300990f485c57964 100644 --- a/Modules/IO/ImageIO/test/CMakeLists.txt +++ b/Modules/IO/ImageIO/test/CMakeLists.txt @@ -790,7 +790,7 @@ set_property(TEST ioTvImageFileReaderFloatHDR2LUM PROPERTY DEPENDS ioTvImageFile otb_add_test(NAME ioTvCheckNbBandsPNGIndexee COMMAND otbImageIOTestDriver otbPNGIndexedNbBandsTest ${INPUTDATA}/sbuv_indexee.png - 4 ) + 1 ) otb_add_test(NAME ioTvImageFileReaderENVI2PNG COMMAND otbImageIOTestDriver --compare-image ${EPSILON_9} ${INPUTDATA}/cthead1.png diff --git a/Modules/Learning/LearningBase/include/otbMachineLearningModel.h b/Modules/Learning/LearningBase/include/otbMachineLearningModel.h index 12e0e4dbf924b15a02c17a302443edb5855d9205..e3b1b8bdea72138fa72c2d49e66d7257d5b1ba7d 100644 --- a/Modules/Learning/LearningBase/include/otbMachineLearningModel.h +++ b/Modules/Learning/LearningBase/include/otbMachineLearningModel.h @@ -127,9 +127,6 @@ public: */ typename TargetListSampleType::Pointer PredictBatch(const InputListSampleType * input, ConfidenceListSampleType * quality = ITK_NULLPTR) const; - /** THIS METHOD IS DEPRECATED AND SHOULD NOT BE USED. */ - void PredictAll(); - /**\name Classification model file manipulation */ //@{ /** Save the model to file */ @@ -162,7 +159,7 @@ public: //@{ /** Set the target labels (to be used before training) */ itkSetObjectMacro(TargetListSample,TargetListSampleType); - /** Get the target labels (to be used after PredictAll) */ + /** Get the target labels */ itkGetObjectMacro(TargetListSample,TargetListSampleType); //@} diff --git a/Modules/Learning/LearningBase/include/otbMachineLearningModel.txx b/Modules/Learning/LearningBase/include/otbMachineLearningModel.txx index 0c89a19d817789c03ddc50c43cecc051d9b2ebf5..678974e9d4f23525783842b860548dfc8b5ad4a9 100644 --- a/Modules/Learning/LearningBase/include/otbMachineLearningModel.txx +++ b/Modules/Learning/LearningBase/include/otbMachineLearningModel.txx @@ -63,21 +63,6 @@ MachineLearningModel<TInputValue,TOutputValue,TConfidenceValue> } } -template <class TInputValue, class TOutputValue, class TConfidenceValue> -void -MachineLearningModel<TInputValue,TOutputValue,TConfidenceValue> -::PredictAll() -{ - itkWarningMacro("MachineLearningModel::PredictAll() has been DEPRECATED. Use MachineLearningModel::PredictBatch() instead."); - - typename TargetListSampleType::Pointer targets = this->GetTargetListSample(); - targets->Clear(); - - typename TargetListSampleType::Pointer tmpTargets = this->PredictBatch(this->GetInputListSample()); - - targets->Graft(tmpTargets); -} - template <class TInputValue, class TOutputValue, class TConfidenceValue> typename MachineLearningModel<TInputValue,TOutputValue,TConfidenceValue> ::TargetSampleType diff --git a/Modules/Learning/SVMLearning/CMakeLists.txt b/Modules/Learning/SVMLearning/CMakeLists.txt deleted file mode 100644 index d840d129bd83175f3883d6d558209c6ff8ae5e33..0000000000000000000000000000000000000000 --- a/Modules/Learning/SVMLearning/CMakeLists.txt +++ /dev/null @@ -1,24 +0,0 @@ -# -# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) -# -# This file is part of Orfeo Toolbox -# -# https://www.orfeo-toolbox.org/ -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -project(OTBSVMLearning) - -set(OTBSVMLearning_LIBRARIES OTBSVMLearning) -otb_module_impl() diff --git a/Modules/Learning/SVMLearning/include/otbSVMClassifier.h b/Modules/Learning/SVMLearning/include/otbSVMClassifier.h deleted file mode 100644 index 731ea2b5a519310fed1f5f1859c0acc21843d229..0000000000000000000000000000000000000000 --- a/Modules/Learning/SVMLearning/include/otbSVMClassifier.h +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef otbSVMClassifier_h -#define otbSVMClassifier_h - -#include "vcl_deprecated_header.h" - -#include "itkSampleClassifierFilter.h" -#include "otbSVMModel.h" -#include "itkVectorImage.h" -#include "itkListSample.h" - -namespace otb -{ - -/** \class SVMClassifier - * \brief SVM-based classifier - * - * The first template argument is the type of the target sample data - * that this classifier will assign a class label for each measurement - * vector. The second one is the pixel type of the labels to be - * produced by the classifier. - * - * Before you call the GenerateData method to start the classification - * process, you should plug in all necessary parts ( a SVM model and a - * target sample data). - * - * The classification result is stored in a vector of Subsample object. - * Each class has its own class sample (Subsample object) that has - * InstanceIdentifiers for all measurement vectors belong to the class. - * The InstanceIdentifiers come from the target sample data. Therefore, - * the Subsample objects act as separate class masks. - * - * \deprecated - * - * \sa MachineLearningModel - * \sa LibSVMMachineLearningModel - * \sa ImageClassificationFilter - * - * - * \ingroup OTBSVMLearning - */ - -template<class TSample, class TLabel> -class ITK_EXPORT SVMClassifier : - public itk::Statistics::SampleClassifierFilter<TSample> -{ -public: - /** Standard class typedef*/ - typedef SVMClassifier Self; - typedef itk::Statistics::SampleClassifierFilter<TSample> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** Standard macros */ - itkTypeMacro(SVMClassifier, itk::Statistics::SampleClassifier); - itkNewMacro(Self); - - /** Output type for GetClassSample method */ - typedef itk::Statistics::MembershipSample<TSample> OutputType; - typedef itk::VariableLengthVector<float> HyperplanesDistancesType; - typedef itk::Statistics::ListSample<HyperplanesDistancesType> HyperplanesDistancesListSampleType; - - /** typedefs from TSample object */ - typedef typename TSample::MeasurementType MeasurementType; - typedef typename TSample::MeasurementVectorType MeasurementVectorType; - - /** typedefs from Superclass */ - typedef typename Superclass::MembershipFunctionVectorObjectPointer - MembershipFunctionPointerVector; //FIXME adopt new naming convention - - /** typedef for label type */ - typedef TLabel ClassLabelType; - - /** Returns the classification result */ - OutputType* GetOutput(); - void SetOutput(OutputType* output); - using Superclass::SetOutput; - - /** Returns the hyperplanes distances */ - HyperplanesDistancesListSampleType * GetHyperplanesDistancesOutput(); - - /** Type definitions for the SVM Model. */ - typedef SVMModel<MeasurementType, ClassLabelType> SVMModelType; - typedef typename SVMModelType::Pointer SVMModelPointer; - - /** Set the model */ - itkSetObjectMacro(Model, SVMModelType); - - /** Get the number of classes. */ - itkGetObjectMacro(Model, SVMModelType); - - void Update() ITK_OVERRIDE; - -protected: - SVMClassifier(); - ~SVMClassifier() ITK_OVERRIDE {} - void PrintSelf(std::ostream& os, itk::Indent indent) const ITK_OVERRIDE; - - /** Starts the classification process */ - void GenerateData() ITK_OVERRIDE; - virtual void DoClassification(); - -private: - - /** Output pointer (MembershipSample) */ - typename OutputType::Pointer m_Output; - - /** Hyperplanes distances output */ - typename HyperplanesDistancesListSampleType::Pointer m_HyperplanesDistancesOutput; - - SVMModelPointer m_Model; -}; // end of class - -} // end of namespace otb - -#ifndef OTB_MANUAL_INSTANTIATION -#include "otbSVMClassifier.txx" -#endif - -#endif diff --git a/Modules/Learning/SVMLearning/include/otbSVMClassifier.txx b/Modules/Learning/SVMLearning/include/otbSVMClassifier.txx deleted file mode 100644 index 832cfbca8c502bd401ec17da771ca61fb80a5b19..0000000000000000000000000000000000000000 --- a/Modules/Learning/SVMLearning/include/otbSVMClassifier.txx +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef otbSVMClassifier_txx -#define otbSVMClassifier_txx - -#include "otbSVMClassifier.h" -#include "otbMacro.h" - -namespace otb -{ - -template<class TSample, class TLabel> -SVMClassifier<TSample, TLabel> -::SVMClassifier() -{ - m_Output = OutputType::New(); - m_HyperplanesDistancesOutput = HyperplanesDistancesListSampleType::New(); -} - -template<class TSample, class TLabel> -void -SVMClassifier<TSample, TLabel> -::PrintSelf(std::ostream& os, itk::Indent indent) const -{ - Superclass::PrintSelf(os, indent); -} - -template<class TSample, class TLabel> -void -SVMClassifier<TSample, TLabel> -::Update() -{ - this->GenerateData(); -} - -template<class TSample, class TLabel> -void -SVMClassifier<TSample, TLabel> -::GenerateData() -{ - if (!m_Model) - { - itkExceptionMacro("No model, can not do classification."); - } - - if (m_Model->GetNumberOfSupportVectors() == 0) - { - itkExceptionMacro(<< "SVM model does not contain any support vector, can not perform classification."); - } - - m_Output->SetSample(this->GetInput()); -// m_Output->Resize(this->GetSample()->Size()); - //FIXME check if this is necessary (work at the decision rule - //Evaluate() level?) - - unsigned int numberOfClasses = this->GetNumberOfClasses(); - - m_Output->SetNumberOfClasses(numberOfClasses); - - this->DoClassification(); -} - -template<class TSample, class TLabel> -typename SVMClassifier<TSample, TLabel>::OutputType* -SVMClassifier<TSample, TLabel> -::GetOutput() -{ - return m_Output; -} - -template<class TSample, class TLabel> -void -SVMClassifier<TSample, TLabel> -::SetOutput(OutputType * output) -{ - m_Output = output; -} - -template<class TSample, class TLabel> -typename SVMClassifier<TSample, TLabel>::HyperplanesDistancesListSampleType * -SVMClassifier<TSample, TLabel> -::GetHyperplanesDistancesOutput() -{ - return m_HyperplanesDistancesOutput; -} - -template<class TSample, class TLabel> -void -SVMClassifier<TSample, TLabel> -::DoClassification() -{ - itk::TimeProbe probe; - - typename TSample::ConstIterator iter = this->GetInput()->Begin(); - typename TSample::ConstIterator end = this->GetInput()->End(); - - typename OutputType::ConstIterator iterO = m_Output->Begin(); - typename OutputType::ConstIterator endO = m_Output->End(); - typename TSample::MeasurementVectorType measurements; - - // sample Measurement vector size - int numberOfComponentsPerSample = iter.GetMeasurementVector().Size(); - - // The size of the hyperplane distance vector is the number of hyperplanes - m_HyperplanesDistancesOutput->SetMeasurementVectorSize(m_Model->GetNumberOfHyperplane()); - - otbMsgDevMacro(<< "Starting iterations "); - while (iter != end && iterO != endO) - { - int i = 0; - typename SVMModelType::MeasurementType modelMeasurement; - - measurements = iter.GetMeasurementVector(); - // otbMsgDevMacro( << "Loop on components " << svm_type ); - for (i = 0; i < numberOfComponentsPerSample; ++i) - { - modelMeasurement.push_back(measurements[i]); - } - - ClassLabelType classLabel = m_Model->EvaluateLabel(modelMeasurement); - typename SVMModelType::DistancesVectorType hdistances = m_Model->EvaluateHyperplanesDistances(modelMeasurement); - HyperplanesDistancesType distances = hdistances; - m_HyperplanesDistancesOutput->PushBack(distances); - // Julien: Event if we support larger type for class labels, - // the AddInstance method wait for an unsigned int, so we cast it here. - m_Output->AddInstance(static_cast<unsigned int>(classLabel), iterO.GetInstanceIdentifier()); - - ++iter; - ++iterO; - } -} - -} // end of namespace otb - -#endif diff --git a/Modules/Learning/SVMLearning/include/otbSVMImageClassificationFilter.h b/Modules/Learning/SVMLearning/include/otbSVMImageClassificationFilter.h deleted file mode 100644 index eb818a4c4005391dfbbf4ce99cbdc95df81fdf0a..0000000000000000000000000000000000000000 --- a/Modules/Learning/SVMLearning/include/otbSVMImageClassificationFilter.h +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef otbSVMImageClassificationFilter_h -#define otbSVMImageClassificationFilter_h - -#include "vcl_deprecated_header.h" - -#include "itkInPlaceImageFilter.h" -#include "otbSVMModel.h" - -namespace otb -{ -/** \class SVMImageClassificationFilter - * \brief This filter performs the classification of a VectorImage using a SVM Model. - * - * This filter is streamed and threaded, allowing to classify huge images - * while fully using several core. - * - * \deprecated - * - * \sa MachineLearningModel - * \sa LibSVMMachineLearningModel - * \sa ImageClassificationFilter - * - * \ingroup Streamed - * \ingroup Threaded - * - * \ingroup OTBSVMLearning - */ -template <class TInputImage, class TOutputImage, class TMaskImage = TOutputImage> -class ITK_EXPORT SVMImageClassificationFilter - : public itk::InPlaceImageFilter<TInputImage, TOutputImage> -{ -public: - /** Standard typedefs */ - typedef SVMImageClassificationFilter Self; - typedef itk::InPlaceImageFilter<TInputImage, TOutputImage> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** Type macro */ - itkNewMacro(Self); - - /** Creation through object factory macro */ - itkTypeMacro(SVMImageClassificationFilter, InPlaceImageFilter); - - /** The max dimension of the sample to classify. - * This filter internally uses itk::FixedArray as input for the classifier, - * so the max sample size has to be fixed at compilation time. - */ - - typedef TInputImage InputImageType; - typedef typename InputImageType::ConstPointer InputImageConstPointerType; - typedef typename InputImageType::InternalPixelType ValueType; - - typedef TMaskImage MaskImageType; - typedef typename MaskImageType::ConstPointer MaskImageConstPointerType; - typedef typename MaskImageType::Pointer MaskImagePointerType; - - typedef TOutputImage OutputImageType; - typedef typename OutputImageType::Pointer OutputImagePointerType; - typedef typename OutputImageType::RegionType OutputImageRegionType; - typedef typename OutputImageType::PixelType LabelType; - - typedef SVMModel<ValueType, LabelType> ModelType; - typedef typename ModelType::Pointer ModelPointerType; - - /** Set/Get the svm model */ - itkSetObjectMacro(Model, ModelType); - itkGetObjectMacro(Model, ModelType); - - /** Set/Get the default label */ - itkSetMacro(DefaultLabel, LabelType); - itkGetMacro(DefaultLabel, LabelType); - - /** - * If set, only pixels within the mask will be classified. - * \param mask The input mask. - */ - void SetInputMask(const MaskImageType * mask); - - /** - * Get the input mask. - * \return The mask. - */ - const MaskImageType * GetInputMask(void); - -protected: - /** Constructor */ - SVMImageClassificationFilter(); - /** Destructor */ - ~SVMImageClassificationFilter() ITK_OVERRIDE {} - - /** Threaded generate data */ - void ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, itk::ThreadIdType threadId) ITK_OVERRIDE; - /** Before threaded generate data */ - void BeforeThreadedGenerateData() ITK_OVERRIDE; - /**PrintSelf method */ - void PrintSelf(std::ostream& os, itk::Indent indent) const ITK_OVERRIDE; - -private: - SVMImageClassificationFilter(const Self &); //purposely not implemented - void operator =(const Self&); //purposely not implemented - - /** The SVM model used for classification */ - ModelPointerType m_Model; - /** Default label for invalid pixels (when using a mask) */ - LabelType m_DefaultLabel; - -}; -} // End namespace otb -#ifndef OTB_MANUAL_INSTANTIATION -#include "otbSVMImageClassificationFilter.txx" -#endif - -#endif diff --git a/Modules/Learning/SVMLearning/include/otbSVMImageClassificationFilter.txx b/Modules/Learning/SVMLearning/include/otbSVMImageClassificationFilter.txx deleted file mode 100644 index 5e4d7e5c0879d8576a3d8a5a86f979c6d2a5590f..0000000000000000000000000000000000000000 --- a/Modules/Learning/SVMLearning/include/otbSVMImageClassificationFilter.txx +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef otbSVMImageClassificationFilter_txx -#define otbSVMImageClassificationFilter_txx - -#include "otbSVMImageClassificationFilter.h" -#include "itkImageRegionIterator.h" -#include "itkProgressReporter.h" - -namespace otb -{ -/** - * Constructor - */ -template <class TInputImage, class TOutputImage, class TMaskImage> -SVMImageClassificationFilter<TInputImage, TOutputImage, TMaskImage> -::SVMImageClassificationFilter() -{ - this->SetNumberOfRequiredInputs(2); - this->SetNumberOfRequiredInputs(1); - m_DefaultLabel = itk::NumericTraits<LabelType>::ZeroValue(); -} - -template <class TInputImage, class TOutputImage, class TMaskImage> -void -SVMImageClassificationFilter<TInputImage, TOutputImage, TMaskImage> -::SetInputMask(const MaskImageType * mask) -{ - this->itk::ProcessObject::SetNthInput(1, const_cast<MaskImageType *>(mask)); -} - -template <class TInputImage, class TOutputImage, class TMaskImage> -const typename SVMImageClassificationFilter<TInputImage, TOutputImage, TMaskImage> -::MaskImageType * -SVMImageClassificationFilter<TInputImage, TOutputImage, TMaskImage> -::GetInputMask() -{ - if (this->GetNumberOfInputs() < 2) - { - return ITK_NULLPTR; - } - return static_cast<const MaskImageType *>(this->itk::ProcessObject::GetInput(1)); -} - -template <class TInputImage, class TOutputImage, class TMaskImage> -void -SVMImageClassificationFilter<TInputImage, TOutputImage, TMaskImage> -::BeforeThreadedGenerateData() -{ - if (!m_Model) - { - itkGenericExceptionMacro(<< "No model for classification"); - } -} - -template <class TInputImage, class TOutputImage, class TMaskImage> -void -SVMImageClassificationFilter<TInputImage, TOutputImage, TMaskImage> -::ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, itk::ThreadIdType threadId) -{ - // Get the input pointers - InputImageConstPointerType inputPtr = this->GetInput(); - MaskImageConstPointerType inputMaskPtr = this->GetInputMask(); - OutputImagePointerType outputPtr = this->GetOutput(); - - // Progress reporting - itk::ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels()); - - // Define iterators - typedef itk::ImageRegionConstIterator<InputImageType> InputIteratorType; - typedef itk::ImageRegionConstIterator<MaskImageType> MaskIteratorType; - typedef itk::ImageRegionIterator<OutputImageType> OutputIteratorType; - - InputIteratorType inIt(inputPtr, outputRegionForThread); - OutputIteratorType outIt(outputPtr, outputRegionForThread); - - // Eventually iterate on masks - MaskIteratorType maskIt; - if (inputMaskPtr) - { - maskIt = MaskIteratorType(inputMaskPtr, outputRegionForThread); - maskIt.GoToBegin(); - } - - bool validPoint = true; - - // Walk the part of the image - for (inIt.GoToBegin(), outIt.GoToBegin(); !inIt.IsAtEnd() && !outIt.IsAtEnd(); ++inIt, ++outIt) - { - // Check pixel validity - if (inputMaskPtr) - { - validPoint = maskIt.Get() > 0; - ++maskIt; - } - // If point is valid - if (validPoint) - { - // Classifify - typename ModelType::MeasurementType measure; - for (unsigned int i = 0; i < inIt.Get().Size(); ++i) - { - measure.push_back(inIt.Get()[i]); - } - outIt.Set(m_Model->EvaluateLabel(measure)); - } - else - { - // else, set default value - outIt.Set(m_DefaultLabel); - } - progress.CompletedPixel(); - } - -} -/** - * PrintSelf Method - */ -template <class TInputImage, class TOutputImage, class TMaskImage> -void -SVMImageClassificationFilter<TInputImage, TOutputImage, TMaskImage> -::PrintSelf(std::ostream& os, itk::Indent indent) const -{ - Superclass::PrintSelf(os, indent); -} -} // End namespace otb -#endif diff --git a/Modules/Learning/SVMLearning/include/otbSVMImageClassificationWithRuleFilter.h b/Modules/Learning/SVMLearning/include/otbSVMImageClassificationWithRuleFilter.h deleted file mode 100644 index 82a5e2785f709fe1d4d967630b4766d4dd59612e..0000000000000000000000000000000000000000 --- a/Modules/Learning/SVMLearning/include/otbSVMImageClassificationWithRuleFilter.h +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * Copyright (C) 2007-2012 Institut Mines Telecom / Telecom Bretagne - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -#ifndef otbSVMImageClassificationWithRuleFilter_h -#define otbSVMImageClassificationWithRuleFilter_h - -#include "otbSVMImageClassificationFilter.h" -#include "otbVectorImage.h" - -namespace otb { - -/** \class SVMImageClassificationWithRuleFilter - * \brief SVM Image Classification that yield distance to hyperplanes - * - * This class comes from SVMImageClassificationFilter that performs - * SVM classification on image. Here, the class add in ThreadedGenerateData an other output - * (a VectorImage) that gives the value for \f$ f(x) \f$ without the majority - * vote decision on class belonging. - * - * \sa SVMImageClassificationFilter - * \ingroup Streamed - * \ingroup Threaded - * - * \ingroup OTBSVMLearning - */ -template <class TInputImage, class TOutputImage, class TMaskImage = TOutputImage> -class ITK_EXPORT SVMImageClassificationWithRuleFilter - : public SVMImageClassificationFilter<TInputImage, TOutputImage, TMaskImage> -{ -public: - /** Standard typedefs */ - typedef SVMImageClassificationWithRuleFilter Self; - typedef SVMImageClassificationFilter<TInputImage, - TOutputImage, TMaskImage> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** Type macro */ - itkNewMacro(Self); - - /** Creation through object factory macro */ - itkTypeMacro(SVMImageClassificationWithRuleFilter, SVMImageClassificationFilter); - - typedef typename Superclass::InputImageType InputImageType; - typedef typename Superclass::InputImageConstPointerType InputImageConstPointerType; - typedef typename Superclass::ValueType ValueType; - - typedef typename Superclass::MaskImageType MaskImageType; - typedef typename Superclass::MaskImageConstPointerType MaskImageConstPointerType; - typedef typename Superclass::MaskImagePointerType MaskImagePointerType; - - typedef typename Superclass::OutputImageType OutputImageType; - typedef typename Superclass::OutputImagePointerType OutputImagePointerType; - typedef typename Superclass::OutputImageRegionType OutputImageRegionType; - typedef typename Superclass::LabelType LabelType; - - typedef typename Superclass::ModelType ModelType; - typedef typename Superclass::ModelPointerType ModelPointerType; - typedef typename ModelType::NodeCacheType NodeCacheType; - typedef typename ModelType::MeasurementType MeasurementType; - typedef typename ModelType::DistancesVectorType DistanceValueType; - typedef typename DistanceValueType::ValueType RuleValueType; - - typedef VectorImage<RuleValueType, OutputImageType::ImageDimension> - OutputRuleImageType; - typedef typename OutputRuleImageType::Pointer OutputRuleImagePointerType; - typedef typename OutputRuleImageType::RegionType OutputRuleImageRegionType; - typedef typename OutputRuleImageType::PixelType RuleType; - - /** Access to the Rule image */ - itkGetObjectMacro(OutputRule, OutputRuleImageType); - -protected: - /** Constructor */ - SVMImageClassificationWithRuleFilter(); - /** Destructor */ - ~SVMImageClassificationWithRuleFilter() ITK_OVERRIDE {} - - /** GenerateOutputInformation - * Set the number of bands of the output rule image. - * Copy information from the input image if existing. - **/ - void GenerateOutputInformation() ITK_OVERRIDE; - - /** AllocateOutputs - * Output allocation redefinition for VectorImage (used in TOutputRuleImage) - **/ - void AllocateOutputs() ITK_OVERRIDE; - - /** Threaded generate data */ - void ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, itk::ThreadIdType threadId) ITK_OVERRIDE; - -private: - SVMImageClassificationWithRuleFilter(const Self &); //purposely not implemented - void operator =(const Self&); //purposely not implemented - - OutputRuleImagePointerType m_OutputRule; - -}; // end of class - -} // end of namespace otb - -#ifndef OTB_MANUAL_INSTANTIATION -#include "otbSVMImageClassificationWithRuleFilter.txx" -#endif - -#endif diff --git a/Modules/Learning/SVMLearning/include/otbSVMImageClassificationWithRuleFilter.txx b/Modules/Learning/SVMLearning/include/otbSVMImageClassificationWithRuleFilter.txx deleted file mode 100644 index 4ddea5cc0c6b0eb03a4b326d4487785f60835126..0000000000000000000000000000000000000000 --- a/Modules/Learning/SVMLearning/include/otbSVMImageClassificationWithRuleFilter.txx +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * Copyright (C) 2007-2012 Institut Mines Telecom / Telecom Bretagne - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -#ifndef otbSVMImageClassificationWithRuleFilter_txx -#define otbSVMImageClassificationWithRuleFilter_txx -#include "otbSVMImageClassificationWithRuleFilter.h" - -#include "itkNumericTraits.h" - -namespace otb { - -template <class TInputImage, class TOutputImage, class TMaskImage> -SVMImageClassificationWithRuleFilter<TInputImage, TOutputImage, TMaskImage> -::SVMImageClassificationWithRuleFilter() -{ - m_OutputRule = OutputRuleImageType::New(); -} - -template <class TInputImage, class TOutputImage, class TMaskImage> -void -SVMImageClassificationWithRuleFilter<TInputImage, TOutputImage, TMaskImage> -::GenerateOutputInformation() -{ - Superclass::GenerateOutputInformation(); - - if (this->GetModel() == ITK_NULLPTR) - { - itkGenericExceptionMacro(<< "No model for classification"); - } - - // add output information on the rule image - this->GetOutputRule()->SetNumberOfComponentsPerPixel( - this->GetModel()->GetNumberOfClasses() * (this->GetModel()->GetNumberOfClasses() - 1) / 2); - - this->GetOutputRule()->CopyInformation(this->GetInput()); - this->GetOutputRule()->SetRegions(this->GetInput()->GetLargestPossibleRegion()); -} - -template <class TInputImage, class TOutputImage, class TMaskImage> -void -SVMImageClassificationWithRuleFilter<TInputImage, TOutputImage, TMaskImage> -::AllocateOutputs() -{ - Superclass::AllocateOutputs(); - - if (this->GetModel() == ITK_NULLPTR) - { - itkGenericExceptionMacro(<< "No model for classification"); - } - - // add allocation for the rule image - OutputRuleImageType * output = this->GetOutputRule(); - output->SetNumberOfComponentsPerPixel( - this->GetModel()->GetNumberOfClasses() * (this->GetModel()->GetNumberOfClasses() - 1) / 2); - output->Allocate(); -} - -template <class TInputImage, class TOutputImage, class TMaskImage> -void -SVMImageClassificationWithRuleFilter<TInputImage, TOutputImage, TMaskImage> -::ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, itk::ThreadIdType threadId) -{ - // Get the input pointers - InputImageConstPointerType inputPtr = this->GetInput(); - MaskImageConstPointerType inputMaskPtr = this->GetInputMask(); - OutputImagePointerType outputPtr = this->GetOutput(); - OutputRuleImagePointerType outputRulePtr = this->GetOutputRule(); - - // Progress reporting - itk::ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels()); - - // Define iterators - typedef itk::ImageRegionConstIterator<InputImageType> InputIteratorType; - typedef itk::ImageRegionConstIterator<MaskImageType> MaskIteratorType; - typedef itk::ImageRegionIterator<OutputImageType> OutputIteratorType; - typedef itk::ImageRegionIterator<OutputRuleImageType> OutputRuleIteratorType; - - InputIteratorType inIt(inputPtr, outputRegionForThread); - OutputIteratorType outIt(outputPtr, outputRegionForThread); - OutputRuleIteratorType outRuleIt(outputRulePtr, outputRegionForThread); - - // Eventually iterate on masks - MaskIteratorType maskIt; - if (inputMaskPtr) - { - maskIt = MaskIteratorType(inputMaskPtr, outputRegionForThread); - maskIt.GoToBegin(); - } - - bool validPoint = true; - typename ModelType::DistancesVectorType defaultDistancesVector - (outputRulePtr->GetNumberOfComponentsPerPixel()); - defaultDistancesVector.Fill(itk::NumericTraits<RuleValueType>::ZeroValue()); - - // Walk the part of the images - for (inIt.GoToBegin(), outIt.GoToBegin(), outRuleIt.GoToBegin(); - !inIt.IsAtEnd() && !outIt.IsAtEnd() && !outRuleIt.IsAtEnd(); - ++inIt, ++outIt, ++outRuleIt) - { - // Check pixel validity - if (inputMaskPtr) - { - validPoint = maskIt.Get() > 0; - ++maskIt; - } - // If point is valid - if (validPoint) - { - // Classifify - MeasurementType measure; - for (unsigned int i = 0; i < inIt.Get().Size(); ++i) - { - measure.push_back(inIt.Get()[i]); - } - outIt.Set(this->GetModel()->EvaluateLabel(measure)); - // And get rules - outRuleIt.Set(this->GetModel()->EvaluateHyperplanesDistances(measure)); - } - else - { - // else, set default value - outIt.Set(this->GetDefaultLabel()); - outRuleIt.Set(defaultDistancesVector); - } - progress.CompletedPixel(); - } -} - -} // end of namespace otb - -#endif diff --git a/Modules/Learning/SVMLearning/include/otbSVMImageModelEstimator.h b/Modules/Learning/SVMLearning/include/otbSVMImageModelEstimator.h deleted file mode 100644 index fd148667565d858ef706691aed93251194c141df..0000000000000000000000000000000000000000 --- a/Modules/Learning/SVMLearning/include/otbSVMImageModelEstimator.h +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef otbSVMImageModelEstimator_h -#define otbSVMImageModelEstimator_h - -#include "vcl_deprecated_header.h" - -#include "itkImageModelEstimatorBase.h" -#include "itkImageRegionIterator.h" -#include "otbSVMModelEstimator.h" - -namespace otb -{ - -/** \class SVMImageModelEstimator - * \brief Class for SVM model estimation from images used for classification. - * - * - * The basic functionality of the SVMImageModelEstimator is to - * generate the models used in SVM classification. It - * requires input images and a training image to be provided by the - * user. This object supports data handling of multiband images. The - * object accepts the input image as a VectorImage only, where each - * pixel is a vector and each element of the vector corresponds to an - * entry from 1 particular band of a multiband dataset. A single band - * image is treated as a vector image with a single element for every - * vector. The classified image is treated as a single band scalar - * image. - * - * \deprecated - * - * \sa MachineLearningModel - * \sa LibSVMMachineLearningModel - * \sa ImageClassificationFilter - * - * \ingroup ClassificationFilters - * - * \ingroup OTBSVMLearning - */ -template <class TInputImage, class TTrainingImage> -class ITK_EXPORT SVMImageModelEstimator : - public SVMModelEstimator<typename TInputImage::InternalPixelType, typename TTrainingImage::PixelType> -{ -public: - /** Standard class typedefs. */ - typedef SVMImageModelEstimator Self; - typedef SVMModelEstimator<typename TInputImage::PixelType::ComponentType, - typename TTrainingImage::PixelType> - Superclass; - - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - /** Run-time type information (and related methods). */ - itkTypeMacro(SVMImageModelEstimator, otb::SVMModelEstimator); - - /** Type definition for the input image. */ - typedef typename TInputImage::Pointer InputImagePointer; - - /** Type definitions for the training image. */ - typedef typename TTrainingImage::Pointer TrainingImagePointer; - - /** Type definition for the vector associated with - * input image pixel type. */ - typedef typename TInputImage::PixelType InputImagePixelType; - - /** Type definitions for the vector holding - * training image pixel type. */ - typedef typename TTrainingImage::PixelType TrainingImagePixelType; - - /** Type definitions for the iterators for the input and training images. */ - typedef - itk::ImageRegionIterator<TInputImage> InputImageIterator; - typedef - itk::ImageRegionIterator<TTrainingImage> TrainingImageIterator; - - /** Set the input image */ - void SetInputImage(const TInputImage * inputImage); - - /** Set the training image */ - void SetTrainingImage(const TTrainingImage * trainingImage); - - /** Get the input image */ - const TInputImage * GetInputImage(); - - /** Get the training image */ - const TTrainingImage * GetTrainingImage(); - -protected: - /** Constructor */ - SVMImageModelEstimator(); - /** Destructor */ - ~SVMImageModelEstimator() ITK_OVERRIDE; - /** PrintSelf */ - void PrintSelf(std::ostream& os, itk::Indent indent) const ITK_OVERRIDE; - - /** Implement the prepare data step from SVMModelEstimator */ - void PrepareData() ITK_OVERRIDE; - -private: - SVMImageModelEstimator(const Self &); //purposely not implemented - void operator =(const Self&); //purposely not implemented - -}; // class SVMImageModelEstimator - -} // namespace otb - -#ifndef OTB_MANUAL_INSTANTIATION -#include "otbSVMImageModelEstimator.txx" -#endif - -#endif diff --git a/Modules/Learning/SVMLearning/include/otbSVMImageModelEstimator.txx b/Modules/Learning/SVMLearning/include/otbSVMImageModelEstimator.txx deleted file mode 100644 index e1b49669fdd780606292ac383ea2f4d0174361e5..0000000000000000000000000000000000000000 --- a/Modules/Learning/SVMLearning/include/otbSVMImageModelEstimator.txx +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef otbSVMImageModelEstimator_txx -#define otbSVMImageModelEstimator_txx - -#include "otbSVMImageModelEstimator.h" -#include "otbMacro.h" - -#include "itkCommand.h" -#include "itkImageRegionConstIterator.h" - -namespace otb -{ - -template<class TInputImage, class TTrainingImage> -SVMImageModelEstimator<TInputImage, TTrainingImage> -::SVMImageModelEstimator() -{ - this->SetNumberOfRequiredInputs(2); -} - -template<class TInputImage, - class TTrainingImage> -SVMImageModelEstimator<TInputImage, TTrainingImage> -::~SVMImageModelEstimator(void) -{} - -/* - * PrintSelf - */ -template<class TInputImage, - class TTrainingImage> -void -SVMImageModelEstimator<TInputImage, TTrainingImage> -::PrintSelf(std::ostream& os, itk::Indent indent) const -{ - Superclass::PrintSelf(os, indent); -} - -template<class TInputImage, class TTrainingImage> -void -SVMImageModelEstimator<TInputImage, TTrainingImage> -::SetInputImage(const TInputImage * inputImage) -{ - this->itk::ProcessObject::SetNthInput(0, const_cast<TInputImage*>(inputImage)); -} - -template<class TInputImage, class TTrainingImage> -void -SVMImageModelEstimator<TInputImage, TTrainingImage> -::SetTrainingImage(const TTrainingImage * trainingImage) -{ - this->itk::ProcessObject::SetNthInput(1, const_cast<TTrainingImage*>(trainingImage)); -} - -template<class TInputImage, class TTrainingImage> -const TInputImage * -SVMImageModelEstimator<TInputImage, TTrainingImage> -::GetInputImage() -{ - if (this->GetNumberOfInputs() < 1) - { - return ITK_NULLPTR; - } - return static_cast<TInputImage *>(this->itk::ProcessObject::GetInput(0)); -} - -template<class TInputImage, class TTrainingImage> -const TTrainingImage * -SVMImageModelEstimator<TInputImage, TTrainingImage> -::GetTrainingImage() -{ - if (this->GetNumberOfInputs() < 2) - { - return ITK_NULLPTR; - } - return static_cast<TTrainingImage *>(this->itk::ProcessObject::GetInput(1)); -} - -/** - * Generate data (start the model building process) - */ -template<class TInputImage, - class TTrainingImage> -void -SVMImageModelEstimator<TInputImage, TTrainingImage> -::PrepareData() -{ - // Get input and output pointers - const TInputImage * inputImage = this->GetInputImage(); - const TTrainingImage * trainingImage = this->GetTrainingImage(); - typename Superclass::ModelType * model = this->GetModel(); - - // Do some error checking - typename TInputImage::SizeType - inputImageSize = inputImage->GetBufferedRegion().GetSize(); - typename TTrainingImage::SizeType - trainingImageSize = trainingImage->GetBufferedRegion().GetSize(); - - // Check if size of the two inputs are same - for (unsigned int i = 0; i < TInputImage::ImageDimension; ++i) - { - if (inputImageSize[i] != trainingImageSize[i]) - throw itk::ExceptionObject( - __FILE__, - __LINE__, - "Input image size is not the same as the training image size.", - ITK_LOCATION); - } - - // Declaration of the iterators on the input and training images - typedef itk::ImageRegionConstIterator<TInputImage> InputIteratorType; - typedef itk::ImageRegionConstIterator<TTrainingImage> TrainingIteratorType; - - InputIteratorType inIt(inputImage, inputImage->GetBufferedRegion()); - TrainingIteratorType trIt(trainingImage, trainingImage->GetBufferedRegion()); - - inIt.GoToBegin(); - trIt.GoToBegin(); - - // Erase previous samples - model->ClearSamples(); - - //This works with Image< itk::Vector > and with VectorImage< scalar >. - unsigned int numberOfComponents = inIt.Get().Size(); - - while (!inIt.IsAtEnd() && !trIt.IsAtEnd()) - { - if (trIt.Get() != 0) - { - typename Superclass::ModelType::MeasurementType v; - - for (unsigned int k = 0; k < numberOfComponents; ++k) - { - v.push_back(inIt.Get()[k]); - } - - model->AddSample(v, trIt.Get()); - } - ++inIt; - ++trIt; - } -} -} //End namespace OTB -#endif diff --git a/Modules/Learning/SVMLearning/include/otbSVMModel.h b/Modules/Learning/SVMLearning/include/otbSVMModel.h deleted file mode 100644 index 27b918bbb41a05ff09627bdd255d280e83a95df2..0000000000000000000000000000000000000000 --- a/Modules/Learning/SVMLearning/include/otbSVMModel.h +++ /dev/null @@ -1,460 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef otbSVMModel_h -#define otbSVMModel_h - -#include "itkObjectFactory.h" -#include "itkDataObject.h" -#include "itkVariableLengthVector.h" -#include "itkTimeProbe.h" -#include "svm.h" - -namespace otb -{ - -/** \class SVMModel - * \brief Class for SVM models. - * - * \TODO update documentation - * - * The basic functionality of the SVMModel framework base class is to - * generate the models used in SVM classification. It requires input - * images and a training image to be provided by the user. - * This object supports data handling of multiband images. The object - * accepts the input image in vector format only, where each pixel is a - * vector and each element of the vector corresponds to an entry from - * 1 particular band of a multiband dataset. A single band image is treated - * as a vector image with a single element for every vector. The classified - * image is treated as a single band scalar image. - * - * A membership function represents a specific knowledge about - * a class. In other words, it should tell us how "likely" is that a - * measurement vector (pattern) belong to the class. - * - * As the method name indicates, you can have more than one membership - * function. One for each classes. The order you put the membership - * calculator becomes the class label for the class that is represented - * by the membership calculator. - * - - * - * \ingroup ClassificationFilters - * - * \ingroup OTBSVMLearning - */ -template <class TValue, class TLabel> -class ITK_EXPORT SVMModel : public itk::DataObject -{ -public: - /** Standard class typedefs. */ - typedef SVMModel Self; - typedef itk::DataObject Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** Value type */ - typedef TValue ValueType; - /** Label Type */ - typedef TLabel LabelType; - typedef std::vector<ValueType> MeasurementType; - typedef std::pair<MeasurementType, LabelType> SampleType; - typedef std::vector<SampleType> SamplesVectorType; - /** Cache vector type */ - typedef std::vector<struct svm_node *> CacheVectorType; - - /** Distances vector */ - typedef itk::VariableLengthVector<double> ProbabilitiesVectorType; - typedef itk::VariableLengthVector<double> DistancesVectorType; - - typedef struct svm_node * NodeCacheType; - - /** Run-time type information (and related methods). */ - itkNewMacro(Self); - itkTypeMacro(SVMModel, itk::DataObject); - - /** Get the number of classes. */ - unsigned int GetNumberOfClasses(void) const - { - if (m_Model) return (unsigned int) (m_Model->nr_class); - return 0; - } - - /** Get the number of hyperplane. */ - unsigned int GetNumberOfHyperplane(void) const - { - if (m_Model) return (unsigned int) (m_Model->nr_class * (m_Model->nr_class - 1) / 2); - return 0; - } - - /** Gets the model */ - const struct svm_model* GetModel() - { - return m_Model; - } - - /** Gets the parameters */ - struct svm_parameter& GetParameters() - { - return m_Parameters; - } - /** Gets the parameters */ - const struct svm_parameter& GetParameters() const - { - return m_Parameters; - } - - /** Saves the model to a file */ - void SaveModel(const char* model_file_name) const; - void SaveModel(const std::string& model_file_name) const - { - //implemented in term of const char * version - this->SaveModel(model_file_name.c_str()); - } - - /** Loads the model from a file */ - void LoadModel(const char* model_file_name); - void LoadModel(const std::string& model_file_name) - { - //implemented in term of const char * version - this->LoadModel(model_file_name.c_str()); - } - - /** Set the SVM type to C_SVC, NU_SVC, ONE_CLASS, EPSILON_SVR, NU_SVR */ - void SetSVMType(int svmtype) - { - m_Parameters.svm_type = svmtype; - m_ModelUpToDate = false; - this->Modified(); - } - - /** Get the SVM type (C_SVC, NU_SVC, ONE_CLASS, EPSILON_SVR, NU_SVR) */ - int GetSVMType(void) const - { - return m_Parameters.svm_type; - } - - /** Set the kernel type to LINEAR, POLY, RBF, SIGMOID - linear: u'*v - polynomial: (gamma*u'*v + coef0)^degree - radial basis function: exp(-gamma*|u-v|^2) - sigmoid: tanh(gamma*u'*v + coef0)*/ - void SetKernelType(int kerneltype) - { - m_Parameters.kernel_type = kerneltype; - m_ModelUpToDate = false; - this->Modified(); - } - - /** Get the kernel type */ - int GetKernelType(void) const - { - return m_Parameters.kernel_type; - } - - /** Set the degree of the polynomial kernel */ - void SetPolynomialKernelDegree(int degree) - { - m_Parameters.degree = degree; - m_ModelUpToDate = false; - this->Modified(); - } - - /** Get the degree of the polynomial kernel */ - int GetPolynomialKernelDegree(void) const - { - return m_Parameters.degree; - } - - /** Set the gamma parameter for poly/rbf/sigmoid kernels */ - virtual void SetKernelGamma(double gamma) - { - m_Parameters.gamma = gamma; - m_ModelUpToDate = false; - this->Modified(); - } - /** Get the gamma parameter for poly/rbf/sigmoid kernels */ - double GetKernelGamma(void) const - { - return m_Parameters.gamma; - } - - /** Set the coef0 parameter for poly/sigmoid kernels */ - void SetKernelCoef0(double coef0) - { - m_Parameters.coef0 = coef0; - m_ModelUpToDate = false; - this->Modified(); - } - - /** Get the coef0 parameter for poly/sigmoid kernels */ - double GetKernelCoef0(void) const - { - //return m_Parameters.coef0; - return m_Parameters.coef0; - } - - /** Set the Nu parameter for the training */ - void SetNu(double nu) - { - m_Parameters.nu = nu; - m_ModelUpToDate = false; - this->Modified(); - } - - /** Set the Nu parameter for the training */ - double GetNu(void) const - { - //return m_Parameters.nu; - return m_Parameters.nu; - } - - /** Set the cache size in MB for the training */ - void SetCacheSize(int cSize) - { - m_Parameters.cache_size = static_cast<double>(cSize); - m_ModelUpToDate = false; - this->Modified(); - } - - /** Get the cache size in MB for the training */ - int GetCacheSize(void) const - { - return static_cast<int>(m_Parameters.cache_size); - } - - /** Set the C parameter for the training for C_SVC, EPSILON_SVR and NU_SVR */ - void SetC(double c) - { - m_Parameters.C = c; - m_ModelUpToDate = false; - this->Modified(); - } - - /** Get the C parameter for the training for C_SVC, EPSILON_SVR and NU_SVR */ - double GetC(void) const - { - return m_Parameters.C; - } - - /** Set the tolerance for the stopping criterion for the training*/ - void SetEpsilon(double eps) - { - m_Parameters.eps = eps; - m_ModelUpToDate = false; - this->Modified(); - } - - /** Get the tolerance for the stopping criterion for the training*/ - double GetEpsilon(void) const - { - return m_Parameters.eps; - } - - /* Set the value of p for EPSILON_SVR */ - void SetP(double p) - { - m_Parameters.p = p; - m_ModelUpToDate = false; - this->Modified(); - } - - /* Get the value of p for EPSILON_SVR */ - double GetP(void) const - { - return m_Parameters.p; - } - - /** Use the shrinking heuristics for the training */ - void DoShrinking(bool s) - { - m_Parameters.shrinking = static_cast<int>(s); - m_ModelUpToDate = false; - this->Modified(); - } - - /** Get Use the shrinking heuristics for the training boolea */ - bool GetDoShrinking(void) const - { - return static_cast<bool>(m_Parameters.shrinking); - } - - /** Do probability estimates */ - void DoProbabilityEstimates(bool prob) - { - m_Parameters.probability = static_cast<int>(prob); - m_ModelUpToDate = false; - this->Modified(); - } - - /** Get Do probability estimates boolean */ - bool GetDoProbabilityEstimates(void) const - { - return static_cast<bool>(m_Parameters.probability); - } - - /** Test if the model has probabilities */ - bool HasProbabilities(void) const - { - return static_cast<bool>(svm_check_probability_model(m_Model)); - } - - /** Return number of support vectors */ - int GetNumberOfSupportVectors(void) const - { - if (m_Model) return m_Model->l; - return 0; - } - - /** Return rho values */ - double * GetRho(void) const - { - if (m_Model) return m_Model->rho; - return ITK_NULLPTR; - } - /** Return the support vectors */ - svm_node ** GetSupportVectors(void) - { - if (m_Model) return m_Model->SV; - return ITK_NULLPTR; - } - /** Set the support vectors and changes the l number of support vectors accordind to sv.*/ - void SetSupportVectors(svm_node ** sv, int nbOfSupportVector); - - /** Return the alphas values (SV Coef) */ - double ** GetAlpha(void) - { - if (m_Model) return m_Model->sv_coef; - return ITK_NULLPTR; - } - /** Set the alphas values (SV Coef) */ - void SetAlpha(double ** alpha, int nbOfSupportVector); - - /** Return the labels lists */ - int * GetLabels() - { - if (m_Model) return m_Model->label; - return ITK_NULLPTR; - } - - /** Get the number of SV per classes */ - int * GetNumberOfSVPerClasse() - { - if (m_Model) return m_Model->nSV; - return ITK_NULLPTR; - } - - struct svm_problem& GetProblem() - { - return m_Problem; - } - - /** Allocate the problem */ - void BuildProblem(); - - /** Check consistency (potentially throws exception) */ - void ConsistencyCheck(); - - /** Estimate the model */ - void Train(); - - /** Cross validation (returns the accuracy) */ - double CrossValidation(unsigned int nbFolders); - - /** Predict (Please note that due to caching this method is not -* thread safe. If you want to run multiple concurrent instances of -* this method, please consider using the GetCopy() method to clone the -* model.)*/ - LabelType EvaluateLabel(const MeasurementType& measure) const; - - /** Evaluate hyperplan distances (Please note that due to caching this method is not -* thread safe. If you want to run multiple concurrent instances of -* this method, please consider using the GetCopy() method to clone the -* model.)**/ - DistancesVectorType EvaluateHyperplanesDistances(const MeasurementType& measure) const; - - /** Evaluate probabilities of each class. Returns a probability vector ordered - * by increasing class label value - * (Please note that due to caching this method is not thread safe. - * If you want to run multiple concurrent instances of - * this method, please consider using the GetCopy() method to clone the - * model.)**/ - ProbabilitiesVectorType EvaluateProbabilities(const MeasurementType& measure) const; - - /** Add a new sample to the list */ - void AddSample(const MeasurementType& measure, const LabelType& label); - - /** Clear all samples */ - void ClearSamples(); - - /** Set the samples vector */ - void SetSamples(const SamplesVectorType& samples); - - /** Reset all the model, leaving it in the same state that just - * before constructor call */ - void Reset(); - -protected: - /** Constructor */ - SVMModel(); - /** Destructor */ - ~SVMModel() ITK_OVERRIDE; - /** Display infos */ - void PrintSelf(std::ostream& os, itk::Indent indent) const ITK_OVERRIDE; - -/** Delete any allocated problem */ - void DeleteProblem(); - - /** Delete any allocated model */ - void DeleteModel(); - - /** Initializes default parameters */ - void Initialize() ITK_OVERRIDE; - -private: - SVMModel(const Self &); //purposely not implemented - void operator =(const Self&); //purposely not implemented - - /** Container to hold the SVM model itself */ - struct svm_model* m_Model; - - /** True if model is up-to-date */ - mutable bool m_ModelUpToDate; - - /** Container of the SVM problem */ - struct svm_problem m_Problem; - - /** Container of the SVM parameters */ - struct svm_parameter m_Parameters; - - /** true if problem is up-to-date */ - bool m_ProblemUpToDate; - - /** Contains the samples */ - SamplesVectorType m_Samples; -}; // class SVMModel - -} // namespace otb - -#ifndef OTB_MANUAL_INSTANTIATION -#include "otbSVMModel.txx" -#endif - -#endif diff --git a/Modules/Learning/SVMLearning/include/otbSVMModel.txx b/Modules/Learning/SVMLearning/include/otbSVMModel.txx deleted file mode 100644 index 23a231bd332bd91f460aaf60f89a5d5ac5a030a5..0000000000000000000000000000000000000000 --- a/Modules/Learning/SVMLearning/include/otbSVMModel.txx +++ /dev/null @@ -1,659 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef otbSVMModel_txx -#define otbSVMModel_txx -#include "otbSVMModel.h" -#include "otbMacro.h" - -#include <algorithm> - -namespace otb -{ -// TODO: Check memory allocation in this class -template <class TValue, class TLabel> -SVMModel<TValue, TLabel>::SVMModel() -{ - // Default parameters - this->SetSVMType(C_SVC); - this->SetKernelType(LINEAR); - this->SetPolynomialKernelDegree(3); - this->SetKernelGamma(1.); // 1/k - this->SetKernelCoef0(1.); - this->SetNu(0.5); - this->SetCacheSize(40); - this->SetC(1); - this->SetEpsilon(1e-3); - this->SetP(0.1); - this->DoShrinking(true); - this->DoProbabilityEstimates(false); - - m_Parameters.nr_weight = 0; - m_Parameters.weight_label = ITK_NULLPTR; - m_Parameters.weight = ITK_NULLPTR; - - m_Model = ITK_NULLPTR; - - this->Initialize(); -} - -template <class TValue, class TLabel> -SVMModel<TValue, TLabel>::~SVMModel() -{ - this->DeleteModel(); - this->DeleteProblem(); -} -template <class TValue, class TLabel> -void -SVMModel<TValue, TLabel>::Initialize() -{ - // Initialize model - /* - if (!m_Model) - { - m_Model = new struct svm_model; - m_Model->l = 0; - m_Model->nr_class = 0; - m_Model->SV = NULL; - m_Model->sv_coef = NULL; - m_Model->rho = NULL; - m_Model->label = NULL; - m_Model->probA = NULL; - m_Model->probB = NULL; - m_Model->nSV = NULL; - - m_ModelUpToDate = false; - - } */ - m_ModelUpToDate = false; - - // Initialize problem - m_Problem.l = 0; - m_Problem.y = ITK_NULLPTR; - m_Problem.x = ITK_NULLPTR; - - m_ProblemUpToDate = false; -} - -template <class TValue, class TLabel> -void -SVMModel<TValue, TLabel>::Reset() -{ - this->DeleteProblem(); - this->DeleteModel(); - - // Clear samples - m_Samples.clear(); - - // Initialize values - this->Initialize(); -} - -template <class TValue, class TLabel> -void -SVMModel<TValue, TLabel>::DeleteModel() -{ - if(m_Model) - { - svm_free_and_destroy_model(&m_Model); - } - m_Model = ITK_NULLPTR; -} - -template <class TValue, class TLabel> -void -SVMModel<TValue, TLabel>::DeleteProblem() -{ -// Deallocate any existing problem - if (m_Problem.y) - { - delete[] m_Problem.y; - m_Problem.y = ITK_NULLPTR; - } - - if (m_Problem.x) - { - for (int i = 0; i < m_Problem.l; ++i) - { - if (m_Problem.x[i]) - { - delete[] m_Problem.x[i]; - } - } - delete[] m_Problem.x; - m_Problem.x = ITK_NULLPTR; - } - m_Problem.l = 0; - m_ProblemUpToDate = false; -} - -template <class TValue, class TLabel> -void -SVMModel<TValue, TLabel>::AddSample(const MeasurementType& measure, const LabelType& label) -{ - SampleType newSample(measure, label); - m_Samples.push_back(newSample); - m_ProblemUpToDate = false; -} - -template <class TValue, class TLabel> -void -SVMModel<TValue, TLabel>::ClearSamples() -{ - m_Samples.clear(); - m_ProblemUpToDate = false; -} - -template <class TValue, class TLabel> -void -SVMModel<TValue, TLabel>::SetSamples(const SamplesVectorType& samples) -{ - m_Samples = samples; - m_ProblemUpToDate = false; -} - -template <class TValue, class TLabel> -void -SVMModel<TValue, TLabel>::BuildProblem() -{ - // Check if problem is up-to-date - if (m_ProblemUpToDate) - { - return; - } - - // Get number of samples - int probl = m_Samples.size(); - - if (probl < 1) - { - itkExceptionMacro(<< "No samples, can not build SVM problem."); - } - otbMsgDebugMacro(<< "Rebuilding problem ..."); - - // Get the size of the samples - long int elements = m_Samples[0].first.size() + 1; - - // Deallocate any previous problem - this->DeleteProblem(); - - // Allocate the problem - m_Problem.l = probl; - m_Problem.y = new double[probl]; - m_Problem.x = new struct svm_node*[probl]; - - for (int i = 0; i < probl; ++i) - { - // Initialize labels to 0 - m_Problem.y[i] = 0; - m_Problem.x[i] = new struct svm_node[elements]; - - // Initialize elements (value = 0; index = -1) - for (unsigned int j = 0; j < static_cast<unsigned int>(elements); ++j) - { - m_Problem.x[i][j].index = -1; - m_Problem.x[i][j].value = 0; - } - } - - // Iterate on the samples - typename SamplesVectorType::const_iterator sIt = m_Samples.begin(); - int sampleIndex = 0; - int maxElementIndex = 0; - - while (sIt != m_Samples.end()) - { - - // Get the sample measurement and label - MeasurementType measure = sIt->first; - LabelType label = sIt->second; - - // Set the label - m_Problem.y[sampleIndex] = label; - - int elementIndex = 0; - - // Populate the svm nodes - for (typename MeasurementType::const_iterator eIt = measure.begin(); - eIt != measure.end() && elementIndex < elements; ++eIt, ++elementIndex) - { - m_Problem.x[sampleIndex][elementIndex].index = elementIndex + 1; - m_Problem.x[sampleIndex][elementIndex].value = (*eIt); - } - - // Get the max index - if (elementIndex > maxElementIndex) - { - maxElementIndex = elementIndex; - } - - ++sampleIndex; - ++sIt; - } - - // Compute the kernel gamma from maxElementIndex if necessary - if (this->GetKernelGamma() == 0) - { - this->SetKernelGamma(1.0 / static_cast<double>(maxElementIndex)); - } - - // problem is up-to-date - m_ProblemUpToDate = true; -} - -template <class TValue, class TLabel> -double -SVMModel<TValue, TLabel>::CrossValidation(unsigned int nbFolders) -{ - // Build problem - this->BuildProblem(); - - // Check consistency - this->ConsistencyCheck(); - - // Get the length of the problem - int length = m_Problem.l; - - // Temporary memory to store cross validation results - double *target = new double[length]; - - // Do cross validation - svm_cross_validation(&m_Problem, &m_Parameters, nbFolders, target); - - // Evaluate accuracy - int i; - double total_correct = 0.; - - for (i = 0; i < length; ++i) - { - if (target[i] == m_Problem.y[i]) - { - ++total_correct; - } - } - double accuracy = total_correct / length; - - // Free temporary memory - delete[] target; - - // return accuracy value - return accuracy; -} - -template <class TValue, class TLabel> -void -SVMModel<TValue, TLabel>::ConsistencyCheck() -{ - if (m_Parameters.svm_type == ONE_CLASS && this->GetDoProbabilityEstimates()) - { - otbMsgDebugMacro(<< "Disabling SVM probability estimates for ONE_CLASS SVM type."); - this->DoProbabilityEstimates(false); - } - - const char* error_msg = svm_check_parameter(&m_Problem, &m_Parameters); - - if (error_msg) - { - throw itk::ExceptionObject(__FILE__, __LINE__, error_msg, ITK_LOCATION); - } -} - -template <class TValue, class TLabel> -void -SVMModel<TValue, TLabel>::Train() -{ - // If the model is already up-to-date, return - if (m_ModelUpToDate) - { - return; - } - - // Build problem - this->BuildProblem(); - - // Check consistency - this->ConsistencyCheck(); - - // train the model - m_Model = svm_train(&m_Problem, &m_Parameters); - - // Set the model as up-to-date - m_ModelUpToDate = true; -} - -template <class TValue, class TLabel> -typename SVMModel<TValue, TLabel>::LabelType -SVMModel<TValue, TLabel>::EvaluateLabel(const MeasurementType& measure) const -{ - // Check if model is up-to-date - if (!m_ModelUpToDate) - { - itkExceptionMacro(<< "Model is not up-to-date, can not predict label"); - } - - // Check probability prediction - bool predict_probability = svm_check_probability_model(m_Model); - - if (this->GetSVMType() == ONE_CLASS) - { - predict_probability = 0; - } - - // Get type and number of classes - int svm_type = svm_get_svm_type(m_Model); - int nr_class = svm_get_nr_class(m_Model); - - // Allocate space for labels - double *prob_estimates = ITK_NULLPTR; - - // Eventually allocate space for probabilities - if (predict_probability) - { - if (svm_type == NU_SVR || svm_type == EPSILON_SVR) - { - otbMsgDevMacro( - << - "Prob. model for test data: target value = predicted value + z,\nz: Laplace distribution e^(-|z|/sigma)/(2sigma), sigma=" - << svm_get_svr_probability(m_Model)); - } - else - { - prob_estimates = new double[nr_class]; - } - } - - // Allocate nodes (/TODO if performances problems are related to too - // many allocations, a cache approach can be set) - struct svm_node * x = new struct svm_node[measure.size() + 1]; - - int valueIndex = 0; - - // Fill the node - for (typename MeasurementType::const_iterator mIt = measure.begin(); mIt != measure.end(); ++mIt, ++valueIndex) - { - x[valueIndex].index = valueIndex + 1; - x[valueIndex].value = (*mIt); - } - - // terminate node - x[measure.size()].index = -1; - x[measure.size()].value = 0; - - LabelType label = 0; - - if (predict_probability && (svm_type == C_SVC || svm_type == NU_SVC)) - { - label = static_cast<LabelType>(svm_predict_probability(m_Model, x, prob_estimates)); - } - else - { - label = static_cast<LabelType>(svm_predict(m_Model, x)); - } - - // Free allocated memory - delete[] x; - - if (prob_estimates) - { - delete[] prob_estimates; - } - - return label; -} - -template <class TValue, class TLabel> -typename SVMModel<TValue, TLabel>::DistancesVectorType -SVMModel<TValue, TLabel>::EvaluateHyperplanesDistances(const MeasurementType& measure) const -{ - // Check if model is up-to-date - if (!m_ModelUpToDate) - { - itkExceptionMacro(<< "Model is not up-to-date, can not predict label"); - } - - // Allocate nodes (/TODO if performances problems are related to too - // many allocations, a cache approach can be set) - struct svm_node * x = new struct svm_node[measure.size() + 1]; - - int valueIndex = 0; - - // Fill the node - for (typename MeasurementType::const_iterator mIt = measure.begin(); mIt != measure.end(); ++mIt, ++valueIndex) - { - x[valueIndex].index = valueIndex + 1; - x[valueIndex].value = (*mIt); - } - - // terminate node - x[measure.size()].index = -1; - x[measure.size()].value = 0; - - // Initialize distances vector - DistancesVectorType distances(m_Model->nr_class*(m_Model->nr_class - 1) / 2); - - // predict distances vector - svm_predict_values(m_Model, x, (double*) (distances.GetDataPointer())); - - // Free allocated memory - delete[] x; - - return (distances); -} - -template <class TValue, class TLabel> -typename SVMModel<TValue, TLabel>::ProbabilitiesVectorType -SVMModel<TValue, TLabel>::EvaluateProbabilities(const MeasurementType& measure) const -{ - // Check if model is up-to-date - if (!m_ModelUpToDate) - { - itkExceptionMacro(<< "Model is not up-to-date, can not predict probabilities"); - } - - if (!this->HasProbabilities()) - { - throw itk::ExceptionObject(__FILE__, __LINE__, - "Model does not support probability estimates", ITK_LOCATION); - } - - // Get number of classes - int nr_class = svm_get_nr_class(m_Model); - - // Allocate nodes (/TODO if performances problems are related to too - // many allocations, a cache approach can be set) - struct svm_node * x = new struct svm_node[measure.size() + 1]; - - int valueIndex = 0; - - // Fill the node - for (typename MeasurementType::const_iterator mIt = measure.begin(); mIt != measure.end(); ++mIt, ++valueIndex) - { - x[valueIndex].index = valueIndex + 1; - x[valueIndex].value = (*mIt); - } - - // Termination node - x[measure.size()].index = -1; - x[measure.size()].value = 0; - - double* dec_values = new double[nr_class]; - svm_predict_probability(m_Model, x, dec_values); - - // Reorder values in increasing class label - int* labels = m_Model->label; - std::vector<int> orderedLabels(nr_class); - std::copy(labels, labels + nr_class, orderedLabels.begin()); - std::sort(orderedLabels.begin(), orderedLabels.end()); - - ProbabilitiesVectorType probabilities(nr_class); - for (int i = 0; i < nr_class; ++i) - { - // svm_predict_probability is such that "dec_values[i]" corresponds to label "labels[i]" - std::vector<int>::iterator it = std::find(orderedLabels.begin(), orderedLabels.end(), labels[i]); - probabilities[it - orderedLabels.begin()] = dec_values[i]; - } - - // Free allocated memory - delete[] x; - delete[] dec_values; - - return probabilities; -} - - -template <class TValue, class TLabel> -void -SVMModel<TValue, TLabel>::SaveModel(const char* model_file_name) const -{ - if (svm_save_model(model_file_name, m_Model) != 0) - { - itkExceptionMacro(<< "Problem while saving SVM model " - << std::string(model_file_name)); - } -} - -template <class TValue, class TLabel> -void -SVMModel<TValue, TLabel>::LoadModel(const char* model_file_name) -{ - this->DeleteModel(); - m_Model = svm_load_model(model_file_name); - if (m_Model == ITK_NULLPTR) - { - itkExceptionMacro(<< "Problem while loading SVM model " - << std::string(model_file_name)); - } - m_Parameters = m_Model->param; - m_ModelUpToDate = true; -} - -template <class TValue, class TLabel> -void -SVMModel<TValue, TLabel>::PrintSelf(std::ostream& os, itk::Indent indent) const -{ - Superclass::PrintSelf(os, indent); -} - -template <class TValue, class TLabel> -void -SVMModel<TValue, TLabel>::SetSupportVectors(svm_node ** sv, int nbOfSupportVector) -{ - if (!m_Model) - { - itkExceptionMacro( "Internal SVM model is empty!"); - } - - // erase the old SV - // delete just the first element, it destoyes the whole pointers (cf SV filling with x_space) - delete[] (m_Model->SV[0]); - - for (int n = 0; n < m_Model->l; ++n) - { - m_Model->SV[n] = ITK_NULLPTR; - } - delete[] (m_Model->SV); - m_Model->SV = ITK_NULLPTR; - - m_Model->SV = new struct svm_node*[m_Model->l]; - - // copy new SV values - svm_node **SV = m_Model->SV; - - // Compute the total number of SV elements. - unsigned int elements = 0; - for (int p = 0; p < nbOfSupportVector; ++p) - { - //std::cout << p << " "; - const svm_node *tempNode = sv[p]; - //std::cout << p << " "; - while (tempNode->index != -1) - { - tempNode++; - ++elements; - } - ++elements; // for -1 values - } - - if (m_Model->l > 0) - { - SV[0] = new struct svm_node[elements]; - memcpy(SV[0], sv[0], sizeof(svm_node*) * elements); - } - svm_node *x_space = SV[0]; - - int j = 0; - for (int i = 0; i < m_Model->l; ++i) - { - // SV - SV[i] = &x_space[j]; - const svm_node *p = sv[i]; - svm_node * pCpy = SV[i]; - while (p->index != -1) - { - pCpy->index = p->index; - pCpy->value = p->value; - ++p; - ++pCpy; - ++j; - } - pCpy->index = -1; - ++j; - } - - if (m_Model->l > 0) - { - delete[] SV[0]; - } -} - -template <class TValue, class TLabel> -void -SVMModel<TValue, TLabel>::SetAlpha(double ** alpha, int itkNotUsed(nbOfSupportVector)) -{ - if (!m_Model) - { - itkExceptionMacro( "Internal SVM model is empty!"); - } - - // Erase the old sv_coef - for (int i = 0; i < m_Model->nr_class - 1; ++i) - { - delete[] m_Model->sv_coef[i]; - } - delete[] m_Model->sv_coef; - - // copy new sv_coef values - m_Model->sv_coef = new double*[m_Model->nr_class - 1]; - for (int i = 0; i < m_Model->nr_class - 1; ++i) - m_Model->sv_coef[i] = new double[m_Model->l]; - - for (int i = 0; i < m_Model->l; ++i) - { - // sv_coef - for (int k = 0; k < m_Model->nr_class - 1; ++k) - { - m_Model->sv_coef[k][i] = alpha[k][i]; - } - } -} - -} // end namespace otb - -#endif diff --git a/Modules/Learning/SVMLearning/include/otbSVMModelEstimator.h b/Modules/Learning/SVMLearning/include/otbSVMModelEstimator.h deleted file mode 100644 index 35b5b3d9015107400df274c640470be552f0de9b..0000000000000000000000000000000000000000 --- a/Modules/Learning/SVMLearning/include/otbSVMModelEstimator.h +++ /dev/null @@ -1,339 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef otbSVMModelEstimator_h -#define otbSVMModelEstimator_h - -#include "otbSVMModel.h" -#include "itkProcessObject.h" - -namespace otb -{ - -/** \class SVMModelEstimator - * \brief Class for SVM model estimation from images used for classification. - * - * - * The basic functionality of the SVMModelEstimator framework base class is to - * generate the models used in SVM classification. It requires input - * images and a training image to be provided by the user. - * This object supports data handling of multiband images. The object - * accepts the input image in vector format only, where each pixel is a - * vector and each element of the vector corresponds to an entry from - * 1 particular band of a multiband dataset. A single band image is treated - * as a vector image with a single element for every vector. The classified - * image is treated as a single band scalar image. - * - * The template parameter is the type of a membership function the - * ModelEstimator populates. - * - * A membership function represents a specific knowledge about - * a class. In other words, it should tell us how "likely" is that a - * measurement vector (pattern) belong to the class. - * - * As the method name indicates, you can have more than one membership - * function. One for each classes. The order you put the membership - * calculator becomes the class label for the class that is represented - * by the membership calculator. - * - * - * \ingroup ClassificationFilters - * - * \ingroup OTBSVMLearning - */ -template <class InputPixelType, class LabelPixelType> -class ITK_EXPORT SVMModelEstimator : public itk::ProcessObject -{ -public: - /** Standard class typedefs. */ - typedef SVMModelEstimator Self; - typedef itk::ProcessObject Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** Model typedef */ - typedef SVMModel<InputPixelType, LabelPixelType> ModelType; - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - /** Macro defining the type*/ - itkTypeMacro(SVMModelEstimator, SuperClass); - - /** Get the output model */ - ModelType * GetModel(); - - /** Get the output model */ - const ModelType * GetModel() const; - - /** Type definitions for the SVM Model. */ - typedef SVMModel<InputPixelType, LabelPixelType> SVMModelType; - typedef typename SVMModelType::Pointer SVMModelPointer; - - /** Get the cross validation accuracy measures */ - itkGetMacro(InitialCrossValidationAccuracy, double); - itkGetMacro(FinalCrossValidationAccuracy, double); - - /** Activate/Deactivate parameters optimization */ - itkSetMacro(ParametersOptimization, bool); - itkGetMacro(ParametersOptimization, bool); - itkBooleanMacro(ParametersOptimization); - - /** Set/Get the number of steps for the coarse optimization */ - itkSetMacro(CoarseOptimizationNumberOfSteps, unsigned int); - itkGetMacro(CoarseOptimizationNumberOfSteps, unsigned int); - - /** Set/Get the number of steps for the fine optimization */ - itkSetMacro(FineOptimizationNumberOfSteps, unsigned int); - itkGetMacro(FineOptimizationNumberOfSteps, unsigned int); - - /** Set/Get the number of cross validation folders */ - itkSetMacro(NumberOfCrossValidationFolders, unsigned int); - itkGetMacro(NumberOfCrossValidationFolders, unsigned int); - - /** Get the number of classes */ - unsigned int GetNumberOfClasses() - { - return this->GetModel()->GetNumberOfClasses(); - } - - /** Set the SVM type to ONE_CLASS, C_SVC, NU_SVC, ONE_CLASS, EPSILON_SVR, NU_SVR */ - void SetSVMType(int svmtype) - { - this->GetModel()->SetSVMType(svmtype); - this->Modified(); - } - - /** Get the SVM type (C_SVC, NU_SVC, ONE_CLASS, EPSILON_SVR, NU_SVR) */ - int GetSVMType(void) - { - return this->GetModel()->GetSVMType(); - } - - /** Set the kernel type to LINEAR, POLY, RBF, SIGMOID - * - linear: \f$ u'*v \f$ - * - polynomial: \f$ (\gamma*u'*v + coef0)^{degree} \f$ - * - radial basis function: \f$ exp(-\gamma*|u-v|^2) \f$ - * - sigmoid: \f$ tanh(\gamma*u'*v + coef0) \f$ - */ - void SetKernelType(int kerneltype) - { - this->GetModel()->SetKernelType(kerneltype); - this->Modified(); - } - - /** Get the kernel type */ - int GetKernelType(void) - { - return this->GetModel()->GetKernelType(); - } - - /** Set the degree of the polynomial kernel */ - void SetPolynomialKernelDegree(int degree) - { - this->GetModel()->SetPolynomialKernelDegree(degree); - this->Modified(); - } - - /** Get the degree of the polynomial kernel */ - int GetPolynomialKernelDegree(void) - { - return this->GetModel()->GetPolynomialKernelDegree(); - } - - /** Set the gamma parameter for poly/rbf/sigmoid kernels */ - void SetKernelGamma(double gamma) - { - this->GetModel()->SetKernelGamma(gamma); - this->Modified(); - } - /** Get the gamma parameter for poly/rbf/sigmoid kernels */ - double GetKernelGamma(void) - { - return this->GetModel()->GetKernelGamma(); - } - - /** Set the coef0 parameter for poly/sigmoid kernels */ - void SetKernelCoef0(double coef0) - { - this->GetModel()->SetKernelCoef0(coef0); - this->Modified(); - } - - /** Get the coef0 parameter for poly/sigmoid kernels */ - double GetKernelCoef0(void) - { - return this->GetModel()->GetKernelCoef0(); - } - - /** Set the Nu parameter for the training */ - void SetNu(double nu) - { - this->GetModel()->SetNu(nu); - this->Modified(); - } - - /** Set the Nu parameter for the training */ - double GetNu(void) - { - return this->GetModel()->GetNu(); - } - - /** Set the cache size in MB for the training */ - void SetCacheSize(int cSize) - { - this->GetModel()->SetCacheSize(cSize); - this->Modified(); - } - - /** Get the cache size in MB for the training */ - int GetCacheSize(void) - { - return (this->GetModel()->GetCacheSize()); - } - - /** Set the C parameter for the training for C_SVC, EPSILON_SVR and NU_SVR */ - void SetC(double c) - { - this->GetModel()->SetC(c); - this->Modified(); - } - - /** Get the C parameter for the training for C_SVC, EPSILON_SVR and NU_SVR */ - double GetC(void) - { - return this->GetModel()->GetC(); - } - - /** Set the tolerance for the stopping criterion for the training*/ - void SetEpsilon(double eps) - { - this->GetModel()->SetEpsilon(eps); - this->Modified(); - } - - /** Get the tolerance for the stopping criterion for the training*/ - double GetEpsilon(void) - { - return this->GetModel()->GetEpsilon(); - } - - /* Set the value of p for EPSILON_SVR */ - void SetP(double p) - { - //param.svm_type = EPSILON_SVR; - this->GetModel()->SetP(p); - this->Modified(); - } - - /* Get the value of p for EPSILON_SVR */ - double GetP(void) - { - return this->GetModel()->GetP(); - } - - /** Use the shrinking heuristics for the training */ - void DoShrinking(bool s) - { - this->GetModel()->DoShrinking(s); - this->Modified(); - } - - /** Get Use the shrinking heuristics for the training boolean */ - bool GetDoShrinking(void) - { - return (this->GetModel()->GetDoShrinking()); - } - - /** Do probability estimates */ - void DoProbabilityEstimates(bool prob) - { - this->GetModel()->DoProbabilityEstimates(prob); - this->Modified(); - } - - /** Get Do probability estimates boolean */ - bool GetDoProbabilityEstimates(void) - { - return (this->GetModel()->GetDoProbabilityEstimates()); - } - - /** Save the model */ - virtual void SaveModel(const char * fname) - { - this->GetModel()->SaveModel(fname); - } - virtual void SaveModel(const std::string& fname) - { - //implemented in term of const char * version - this->SaveModel(fname.c_str()); - } - -protected: - /** Constructor */ - SVMModelEstimator(); - /** Destructor */ - ~SVMModelEstimator() ITK_OVERRIDE; - void PrintSelf(std::ostream& os, itk::Indent indent) const ITK_OVERRIDE; - - /** Starts the modelling process */ - void GenerateData() ITK_OVERRIDE; - - /** This virtual function must be implemented in subclasses to - populate the model with samples */ - virtual void PrepareData(){} - - /** Optimize parameters */ - void OptimizeParameters(); - - /** The number of classes */ - unsigned int m_NumberOfClasses; - -private: - SVMModelEstimator(const Self &); //purposely not implemented - void operator =(const Self&); //purposely not implemented - - // Initial cross validation accuracy - double m_InitialCrossValidationAccuracy; - - // Final cross validationa accuracy - double m_FinalCrossValidationAccuracy; - - // Do parameters optimization, default : false - bool m_ParametersOptimization; - - // Number of steps for the coarse search - unsigned int m_CoarseOptimizationNumberOfSteps; - - // Number of steps for the fine search - unsigned int m_FineOptimizationNumberOfSteps; - - // Number of cross validation folders - unsigned int m_NumberOfCrossValidationFolders; - -}; // class SVMModelEstimator - -} // namespace otb - -#ifndef OTB_MANUAL_INSTANTIATION -#include "otbSVMModelEstimator.txx" -#endif - -#endif diff --git a/Modules/Learning/SVMLearning/include/otbSVMModelEstimator.txx b/Modules/Learning/SVMLearning/include/otbSVMModelEstimator.txx deleted file mode 100644 index f4d0d018c2f17e4675aa869036fdd56b9e425370..0000000000000000000000000000000000000000 --- a/Modules/Learning/SVMLearning/include/otbSVMModelEstimator.txx +++ /dev/null @@ -1,252 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef otbSVMModelEstimator_txx -#define otbSVMModelEstimator_txx - -#include "otbSVMModelEstimator.h" -#include "otbSVMCrossValidationCostFunction.h" -#include "otbExhaustiveExponentialOptimizer.h" -#include "itkRegularStepGradientDescentOptimizer.h" -#include "otbMacro.h" -#include "itkCommand.h" - -namespace otb -{ -template<class InputPixelType, class LabelPixelType> -SVMModelEstimator<InputPixelType, LabelPixelType> -::SVMModelEstimator(void) : - m_NumberOfClasses(0) -{ - // Cross validation accuracy measures - m_InitialCrossValidationAccuracy = 0.; - m_FinalCrossValidationAccuracy = 0.; - m_ParametersOptimization = false; - m_NumberOfCrossValidationFolders = 5; - m_CoarseOptimizationNumberOfSteps = 5; - m_FineOptimizationNumberOfSteps = 5; - - this->SetNumberOfRequiredInputs(0); - this->SetNumberOfRequiredOutputs(1); - this->SetNthOutput(0, ModelType::New()); -} - -template<class InputPixelType, class LabelPixelType> -typename SVMModelEstimator<InputPixelType, LabelPixelType>::ModelType * -SVMModelEstimator<InputPixelType, LabelPixelType> -::GetModel() -{ - if (this->GetNumberOfOutputs() < 1) - { - return ITK_NULLPTR; - } - return static_cast<ModelType *>(this->itk::ProcessObject::GetOutput(0)); -} - -template<class InputPixelType, class LabelPixelType> -const typename SVMModelEstimator<InputPixelType, LabelPixelType>::ModelType * -SVMModelEstimator<InputPixelType, LabelPixelType> -::GetModel() const -{ - if (this->GetNumberOfOutputs() < 1) - { - return 0; - } - return static_cast<const ModelType *>(this->itk::ProcessObject::GetOutput(0)); -} - -template<class InputPixelType, class LabelPixelType> -SVMModelEstimator<InputPixelType, LabelPixelType> -::~SVMModelEstimator(void) -{} - -/* - * PrintSelf - */ -template<class InputPixelType, class LabelPixelType> -void -SVMModelEstimator<InputPixelType, LabelPixelType> -::PrintSelf(std::ostream& os, itk::Indent indent) const -{ - Superclass::PrintSelf(os, indent); - -} // end PrintSelf - -/** - * Generate data (start the model building process) - */ -template<class InputPixelType, class LabelPixelType> -void -SVMModelEstimator<InputPixelType, LabelPixelType> -::GenerateData() -{ - // Get the pointer to the output model - ModelType * outputPtr = this->GetModel(); - - // Reset the model - outputPtr->Reset(); - - // Prepare data - this->PrepareData(); - - // Compute accuracy and eventually optimize parameters - this->OptimizeParameters(); - - // Train the model - outputPtr->Train(); - -} // end Generate data - -template<class InputPixelType, class LabelPixelType> -void -SVMModelEstimator<InputPixelType, LabelPixelType> -::OptimizeParameters() -{ - typedef SVMCrossValidationCostFunction<SVMModelType> CrossValidationFunctionType; - - typename CrossValidationFunctionType::Pointer crossValidationFunction = CrossValidationFunctionType::New(); - - crossValidationFunction->SetModel(this->GetModel()); - crossValidationFunction->SetNumberOfCrossValidationFolders(m_NumberOfCrossValidationFolders); - - typename CrossValidationFunctionType::ParametersType initialParameters, coarseBestParameters, fineBestParameters; - - switch (this->GetModel()->GetKernelType()) - { - case LINEAR: - // C - initialParameters.SetSize(1); - initialParameters[0] = this->GetModel()->GetC(); - break; - - case POLY: - // C, gamma and coef0 - initialParameters.SetSize(3); - initialParameters[0] = this->GetModel()->GetC(); - initialParameters[1] = this->GetModel()->GetKernelGamma(); - initialParameters[2] = this->GetModel()->GetKernelCoef0(); - break; - - case RBF: - // C and gamma - initialParameters.SetSize(2); - initialParameters[0] = this->GetModel()->GetC(); - initialParameters[1] = this->GetModel()->GetKernelGamma(); - break; - - case SIGMOID: - // C, gamma and coef0 - initialParameters.SetSize(3); - initialParameters[0] = this->GetModel()->GetC(); - initialParameters[1] = this->GetModel()->GetKernelGamma(); - initialParameters[2] = this->GetModel()->GetKernelCoef0(); - break; - - default: - // Only C - initialParameters.SetSize(1); - initialParameters[0] = this->GetModel()->GetC(); - break; - } - - m_InitialCrossValidationAccuracy = crossValidationFunction->GetValue(initialParameters); - m_FinalCrossValidationAccuracy = m_InitialCrossValidationAccuracy; - - otbMsgDebugMacro(<< "Initial accuracy : " << m_InitialCrossValidationAccuracy - << ", Parameters Optimization" << m_ParametersOptimization); - - if (m_ParametersOptimization) - { - otbMsgDebugMacro(<< "Model parameters optimization"); - - typename ExhaustiveExponentialOptimizer::Pointer coarseOptimizer = ExhaustiveExponentialOptimizer::New(); - typename ExhaustiveExponentialOptimizer::StepsType coarseNbSteps(initialParameters.Size()); - coarseNbSteps.Fill(m_CoarseOptimizationNumberOfSteps); - - coarseOptimizer->SetNumberOfSteps(coarseNbSteps); - coarseOptimizer->SetCostFunction(crossValidationFunction); - coarseOptimizer->SetInitialPosition(initialParameters); - coarseOptimizer->StartOptimization(); - - coarseBestParameters = coarseOptimizer->GetMaximumMetricValuePosition(); - - otbMsgDevMacro( << "Coarse minimum accuracy: " << coarseOptimizer->GetMinimumMetricValue() << " " << - coarseOptimizer->GetMinimumMetricValuePosition() ); - otbMsgDevMacro( << "Coarse maximum accuracy: " << coarseOptimizer->GetMaximumMetricValue() << " " << - coarseOptimizer->GetMaximumMetricValuePosition() ); - - typename ExhaustiveExponentialOptimizer::Pointer fineOptimizer = ExhaustiveExponentialOptimizer::New(); - typename ExhaustiveExponentialOptimizer::StepsType fineNbSteps(initialParameters.Size()); - fineNbSteps.Fill(m_FineOptimizationNumberOfSteps); - - double stepLength = 1. / static_cast<double>(m_FineOptimizationNumberOfSteps); - - fineOptimizer->SetNumberOfSteps(fineNbSteps); - fineOptimizer->SetStepLength(stepLength); - fineOptimizer->SetCostFunction(crossValidationFunction); - fineOptimizer->SetInitialPosition(coarseBestParameters); - fineOptimizer->StartOptimization(); - - otbMsgDevMacro(<< "Fine minimum accuracy: " << fineOptimizer->GetMinimumMetricValue() << " " << - fineOptimizer->GetMinimumMetricValuePosition() ); - otbMsgDevMacro(<< "Fine maximum accuracy: " << fineOptimizer->GetMaximumMetricValue() << " " << - fineOptimizer->GetMaximumMetricValuePosition() ); - - fineBestParameters = fineOptimizer->GetMaximumMetricValuePosition(); - - m_FinalCrossValidationAccuracy = fineOptimizer->GetMaximumMetricValue(); - - switch (this->GetModel()->GetKernelType()) - { - case LINEAR: - // C - this->GetModel()->SetC(fineBestParameters[0]); - break; - - case POLY: - // C, gamma and coef0 - this->GetModel()->SetC(fineBestParameters[0]); - this->GetModel()->SetKernelGamma(fineBestParameters[1]); - this->GetModel()->SetKernelCoef0(fineBestParameters[2]); - break; - - case RBF: - // C and gamma - this->GetModel()->SetC(fineBestParameters[0]); - this->GetModel()->SetKernelGamma(fineBestParameters[1]); - break; - - case SIGMOID: - // C, gamma and coef0 - this->GetModel()->SetC(fineBestParameters[0]); - this->GetModel()->SetKernelGamma(fineBestParameters[1]); - this->GetModel()->SetKernelCoef0(fineBestParameters[2]); - break; - - default: - // Only C - this->GetModel()->SetC(fineBestParameters[0]); - break; - } - } -} - -} //End namespace OTB -#endif diff --git a/Modules/Learning/SVMLearning/include/otbSVMPointSetModelEstimator.h b/Modules/Learning/SVMLearning/include/otbSVMPointSetModelEstimator.h deleted file mode 100644 index ec5fe007c0c7d91ac13a56b27921eed99fe7cd55..0000000000000000000000000000000000000000 --- a/Modules/Learning/SVMLearning/include/otbSVMPointSetModelEstimator.h +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef otbSVMPointSetModelEstimator_h -#define otbSVMPointSetModelEstimator_h - -#include "vcl_deprecated_header.h" - -#include "otbSVMModelEstimator.h" - -namespace otb -{ - -/** \class SVMPointSetModelEstimator - - * \brief Class for SVM model - * estimation from PointSets used for classification. - * - * - * The basic functionality of the SVMPointSetModelEstimator is to - * generate the models used in SVM classification. It - * requires one input poinset and a training pointset to be provided by the - * user. This object supports data handling of multiband data. The - * object accepts the input image as a VectorImage only, where each - * pixel is a vector and each element of the vector corresponds to an - * entry from 1 particular band of a multiband dataset. A single band - * data set is treated as a vector with a single element for every - * vector. The classified data is treated as a single band scalar - * data. - * - * \deprecated - * - * \sa MachineLearningModel - * \sa LibSVMMachineLearningModel - * \sa ImageClassificationFilter - * - * \ingroup ClassificationFilters - * - * \ingroup OTBSVMLearning - */ -template <class TInputPointSet, class TTrainingPointSet> -class ITK_EXPORT SVMPointSetModelEstimator : - public SVMModelEstimator<typename TInputPointSet::PixelType::value_type, typename TTrainingPointSet::PixelType> -{ -public: - /** Standard class typedefs. */ - typedef SVMPointSetModelEstimator Self; - typedef SVMModelEstimator<typename TInputPointSet::PixelType::value_type, - typename TTrainingPointSet::PixelType> Superclass; - typedef itk::SmartPointer<Self> - Pointer; - typedef itk::SmartPointer<const Self> - ConstPointer; - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - /** Run-time type information (and related methods). */ - itkTypeMacro(SVMPointSetModelEstimator, SVMModelEstimator); - - /** Type definition for the input image. */ - typedef typename TInputPointSet::Pointer InputPointSetPointer; - - /** Type definitions for the training image. */ - typedef typename TTrainingPointSet::Pointer TrainingPointSetPointer; - - /** Type definition for the vector associated with - * input image pixel type. */ - typedef typename TInputPointSet::PixelType InputPointSetPixelType; - typedef typename TInputPointSet::PointType InputPointType; - - /** Type definitions for the vector holding - * training image pixel type. */ - typedef typename TTrainingPointSet::PixelType TrainingPointSetPixelType; - - /** Type definitions for the iterators for the input and training images. */ - typedef typename - TInputPointSet::PointsContainerConstIterator InputPointSetIteratorType; - typedef typename - TTrainingPointSet::PointsContainerConstIterator TrainingPointSetIteratorType; - - /** Set the input image */ - void SetInputPointSet(const TInputPointSet * inputPointSet); - - /** Set the training image */ - void SetTrainingPointSet(const TTrainingPointSet * trainingPointSet); - - /** Get the input image */ - const TInputPointSet * GetInputPointSet(); - - /** Get the training image */ - const TTrainingPointSet * GetTrainingPointSet(); - -protected: - /** Constructor */ - SVMPointSetModelEstimator(); - /** Destructor */ - ~SVMPointSetModelEstimator() ITK_OVERRIDE; - /** PrintSelf */ - void PrintSelf(std::ostream& os, itk::Indent indent) const ITK_OVERRIDE; - /** Prepare data */ - void PrepareData() ITK_OVERRIDE; - -private: - SVMPointSetModelEstimator(const Self &); //purposely not implemented - void operator =(const Self&); //purposely not implemented - -}; // class SVMPointSetModelEstimator - -} // namespace otb - -#ifndef OTB_MANUAL_INSTANTIATION -#include "otbSVMPointSetModelEstimator.txx" -#endif - -#endif diff --git a/Modules/Learning/SVMLearning/include/otbSVMPointSetModelEstimator.txx b/Modules/Learning/SVMLearning/include/otbSVMPointSetModelEstimator.txx deleted file mode 100644 index ebb811c4a6dc183085a86aeb76d7f4fef51a609e..0000000000000000000000000000000000000000 --- a/Modules/Learning/SVMLearning/include/otbSVMPointSetModelEstimator.txx +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef otbSVMPointSetModelEstimator_txx -#define otbSVMPointSetModelEstimator_txx - -#include "otbSVMPointSetModelEstimator.h" -#include "itkCommand.h" -#include "otbMacro.h" - -namespace otb -{ -template<class TInputPointSet, - class TTrainingPointSet> -SVMPointSetModelEstimator<TInputPointSet, TTrainingPointSet> -::SVMPointSetModelEstimator(void) : SVMModelEstimator<typename TInputPointSet::PixelType::value_type, - typename TTrainingPointSet::PixelType>() -{ - this->SetNumberOfRequiredInputs(2); -} - -template<class TInputPointSet, - class TTrainingPointSet> -SVMPointSetModelEstimator<TInputPointSet, TTrainingPointSet> -::~SVMPointSetModelEstimator(void) -{} - -/* - * PrintSelf - */ -template<class TInputPointSet, - class TTrainingPointSet> -void -SVMPointSetModelEstimator<TInputPointSet, TTrainingPointSet> -::PrintSelf(std::ostream& os, itk::Indent indent) const -{ - Superclass::PrintSelf(os, indent); -} // end PrintSelf - -template<class TInputPointSet, class TTrainingPointSet> -void -SVMPointSetModelEstimator<TInputPointSet, TTrainingPointSet> -::SetInputPointSet(const TInputPointSet * inputPointSet) -{ - this->itk::ProcessObject::SetNthInput(0, const_cast<TInputPointSet *>(inputPointSet)); -} - -template<class TInputPointSet, class TTrainingPointSet> -void -SVMPointSetModelEstimator<TInputPointSet, TTrainingPointSet> -::SetTrainingPointSet(const TTrainingPointSet * trainingPointSet) -{ - this->itk::ProcessObject::SetNthInput(1, const_cast<TTrainingPointSet*>(trainingPointSet)); -} - -template<class TInputPointSet, class TTrainingPointSet> -const TInputPointSet * -SVMPointSetModelEstimator<TInputPointSet, TTrainingPointSet> -::GetInputPointSet() -{ - if (this->GetNumberOfInputs() < 1) - { - return ITK_NULLPTR; - } - return static_cast<TInputPointSet *>(this->itk::ProcessObject::GetInput(0)); -} - -template<class TInputPointSet, class TTrainingPointSet> -const TTrainingPointSet * -SVMPointSetModelEstimator<TInputPointSet, TTrainingPointSet> -::GetTrainingPointSet() -{ - if (this->GetNumberOfInputs() < 2) - { - return ITK_NULLPTR; - } - return static_cast<TTrainingPointSet *>(this->itk::ProcessObject::GetInput(1)); -} - -/** - * Generate data (start the model building process) - */ -template<class TInputPointSet, - class TTrainingPointSet> -void -SVMPointSetModelEstimator<TInputPointSet, TTrainingPointSet> -::PrepareData() -{ - - //Do some error checking - const TInputPointSet * inputPointSet = this->GetInputPointSet(); - const TTrainingPointSet * trainingPointSet = this->GetTrainingPointSet(); - typename Superclass::ModelType * model = this->GetModel(); - - int inputPointSetSize = inputPointSet->GetNumberOfPoints(); - int trainingPointSetSize = trainingPointSet->GetNumberOfPoints(); - - // Check if size of the two inputs are same - if (inputPointSetSize != trainingPointSetSize) - throw itk::ExceptionObject( - __FILE__, - __LINE__, - "Input pointset size is not the same as the training pointset size.", - ITK_LOCATION); - - // Declaration of the iterators on the input and training images - InputPointSetIteratorType inIt = inputPointSet->GetPoints()->Begin(); - TrainingPointSetIteratorType trIt = trainingPointSet->GetPoints()->Begin(); - - InputPointSetIteratorType inEnd = inputPointSet->GetPoints()->End(); - TrainingPointSetIteratorType trEnd = trainingPointSet->GetPoints()->End(); - - // Erase previous samples - model->ClearSamples(); - - otbMsgDevMacro(<< " Input nb points " << inputPointSetSize); - otbMsgDevMacro(<< " Training nb points " << trainingPointSetSize); - - unsigned int dataId = 0; - while (inIt != inEnd && trIt != trEnd) - { - typename TTrainingPointSet::PixelType label = itk::NumericTraits<typename TTrainingPointSet::PixelType>::Zero; - trainingPointSet->GetPointData(dataId, &label); - - otbMsgDevMacro(<< " Label " << label); - - typename TInputPointSet::PixelType value; - inputPointSet->GetPointData(dataId, &value); - - typename Superclass::ModelType::MeasurementType v; - - typename TInputPointSet::PixelType::iterator pIt = value.begin(); - typename TInputPointSet::PixelType::iterator pEnd = value.end(); - - while (pIt != pEnd) - { - v.push_back(*pIt); - ++pIt; - } - - model->AddSample(v, label); - - ++inIt; - ++trIt; - ++dataId; - } -} -} //End namespace OTB -#endif diff --git a/Modules/Learning/SVMLearning/include/otbSVMSampleListModelEstimator.h b/Modules/Learning/SVMLearning/include/otbSVMSampleListModelEstimator.h deleted file mode 100644 index bd6cc3016feb6cbdb85f2203c3ff24a650aa0219..0000000000000000000000000000000000000000 --- a/Modules/Learning/SVMLearning/include/otbSVMSampleListModelEstimator.h +++ /dev/null @@ -1,206 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef otbSVMSampleListModelEstimator_h -#define otbSVMSampleListModelEstimator_h - -#include "vcl_deprecated_header.h" - -#include "itkImageModelEstimatorBase.h" -#include "itkImageRegionIterator.h" -#include "otbSVMModelEstimator.h" - -namespace otb -{ -namespace Functor -{ -/** \class VectorToMeasurementVectorFunctor -* \brief Helper class to convert itk::Vector and itk::FixedArray samples to internal -* training vector type. -* -* \sa Vector -* \sa FixedArray - * - * \ingroup OTBSVMLearning -*/ -template <class TVector> -class VectorToMeasurementVectorFunctor -{ -public: - typedef TVector VectorType; - typedef std::vector<typename VectorType::ValueType> MeasurementVectorType; - - inline MeasurementVectorType operator ()(const VectorType& value) const - { - MeasurementVectorType output; - - for (unsigned int i = 0; i < value.Size(); ++i) - { - output.push_back(value[i]); - } - return output; - } -}; - -/** \class VariableLengthVectorToMeasurementVectorFunctor -* \brief Helper class to convert itk::VariableLengthVector samples to internal -* training vector type. -* \sa VariableLengthVector - * - * \ingroup OTBSVMLearning -*/ -template <class TVector> -class VariableLengthVectorToMeasurementVectorFunctor -{ -public: - typedef TVector VectorType; - typedef std::vector<typename VectorType::ValueType> MeasurementVectorType; - - inline MeasurementVectorType operator ()(const VectorType& value) const - { - MeasurementVectorType output; - - for (unsigned int i = 0; i < value.GetNumberOfElements(); ++i) - { - output.push_back(value.GetElement(i)); - } - - return output; - } -}; - -} - -/** - * \class SVMSampleListModelEstimator - * \brief Class for SVM model estimation from SampleLists used for classification. - * - * - * The basic functionality of the SVMSampleListModelEstimator is to - * generate the models used in SVM classification. It - * requires one input poinset and a training pointset to be provided by the - * user. This object supports data handling of multiband data. The - * object accepts the input image as a VectorImage only, where each - * pixel is a vector and each element of the vector corresponds to an - * entry from 1 particular band of a multiband dataset. A single band - * data set is treated as a vector with a single element for every - * vector. The classified data is treated as a single band scalar - * data. - * - * \deprecated - * - * \sa MachineLearningModel - * \sa LibSVMMachineLearningModel - * \sa ImageClassificationFilter - * - * \ingroup ClassificationFilters - * - * \ingroup OTBSVMLearning - */ -template <class TInputSampleList, - class TTrainingSampleList, class TMeasurementFunctor = - Functor::VectorToMeasurementVectorFunctor<typename TInputSampleList::MeasurementVectorType> > -class ITK_EXPORT SVMSampleListModelEstimator : - public SVMModelEstimator<typename TInputSampleList::MeasurementType, typename TTrainingSampleList::MeasurementType> -{ -public: - /** Standard class typedefs. */ - typedef SVMSampleListModelEstimator Self; - typedef SVMModelEstimator<typename TInputSampleList::MeasurementType, - typename TTrainingSampleList::MeasurementType> - Superclass; - - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - /** Run-time type information (and related methods). */ - itkTypeMacro(SVMSampleListModelEstimator, SVMModelEstimator); - - /** Type definition for the input image. */ - typedef TInputSampleList InputSampleListType; - typedef typename TInputSampleList::Pointer InputSampleListPointer; - - /** Type definitions for the training image. */ - typedef TTrainingSampleList TrainingSampleListType; - typedef typename TTrainingSampleList::Pointer TrainingSampleListPointer; - - /** Type definition for the vector associated with - * input image pixel type. */ - typedef typename TInputSampleList::ValueType InputSampleListValueType; - - /** Type definitions for the vector holding - * training image pixel type. */ - typedef typename TTrainingSampleList::ValueType TrainingSampleListValueType; - - /** Type definitions for the iterators for the input and training images. */ - typedef typename - TInputSampleList::ConstIterator InputSampleListIteratorType; - typedef typename - TTrainingSampleList::ConstIterator TrainingSampleListIteratorType; - - /** Measurement functor typedef */ - typedef TMeasurementFunctor MeasurementFunctorType; - - /** Set the input image. */ - //itkSetObjectMacro(InputSampleList, TInputSampleList); - void SetInputSampleList(const InputSampleListType* inputSampleList); - - /** Get the input image. */ - //itkGetObjectMacro(InputSampleList, TInputSampleList); - const InputSampleListType* GetInputSampleList(); - - /** Set the training image. */ - //itkSetMacro(TrainingSampleList, TrainingSampleListPointer); - void SetTrainingSampleList(const TrainingSampleListType* trainingSampleList); - - /** Get the training image. */ - //itkGetMacro(TrainingSampleList, TrainingSampleListPointer); - const TrainingSampleListType* GetTrainingSampleList(); - -protected: - /** Constructor */ - SVMSampleListModelEstimator(); - /** Destructor */ - ~SVMSampleListModelEstimator() ITK_OVERRIDE; - /** PrintSelf */ - void PrintSelf(std::ostream& os, itk::Indent indent) const ITK_OVERRIDE; - - /** PrepareData method */ - void PrepareData() ITK_OVERRIDE; - -private: - SVMSampleListModelEstimator(const Self &); //purposely not implemented - void operator =(const Self&); //purposely not implemented - - TrainingSampleListPointer m_TrainingSampleList; - InputSampleListPointer m_InputSampleList; - -}; // class SVMSampleListModelEstimator - -} // namespace otb - -#ifndef OTB_MANUAL_INSTANTIATION -#include "otbSVMSampleListModelEstimator.txx" -#endif - -#endif diff --git a/Modules/Learning/SVMLearning/include/otbSVMSampleListModelEstimator.txx b/Modules/Learning/SVMLearning/include/otbSVMSampleListModelEstimator.txx deleted file mode 100644 index 9ce5f42b47a74ae7ab8da5366906f5964d11ea2c..0000000000000000000000000000000000000000 --- a/Modules/Learning/SVMLearning/include/otbSVMSampleListModelEstimator.txx +++ /dev/null @@ -1,179 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -#ifndef otbSVMSampleListModelEstimator_txx -#define otbSVMSampleListModelEstimator_txx - -#include "otbSVMSampleListModelEstimator.h" -#include "itkCommand.h" -#include "otbMacro.h" - -namespace otb -{ -template<class TInputSampleList, - class TTrainingSampleList, class TMeasurementFunctor> -SVMSampleListModelEstimator<TInputSampleList, TTrainingSampleList, TMeasurementFunctor> -::SVMSampleListModelEstimator(void) : SVMModelEstimator<typename TInputSampleList::MeasurementType, - typename TTrainingSampleList::MeasurementType>() -{ - this->SetNumberOfRequiredInputs(2); -} - -template<class TInputSampleList, - class TTrainingSampleList, class TMeasurementFunctor> -SVMSampleListModelEstimator<TInputSampleList, TTrainingSampleList, TMeasurementFunctor> -::~SVMSampleListModelEstimator(void) -{} - -//Set the input sample list -template<class TInputSampleList, - class TTrainingSampleList, - class TMeasurementFunctor> -void -SVMSampleListModelEstimator<TInputSampleList, TTrainingSampleList, TMeasurementFunctor> -::SetInputSampleList( const InputSampleListType* inputSampleList ) -{ - // Process object is not const-correct so the const_cast is required here - this->itk::ProcessObject::SetNthInput(0, - const_cast< InputSampleListType* >(inputSampleList) ); -} - - -// Set the label sample list -template<class TInputSampleList, - class TTrainingSampleList, - class TMeasurementFunctor> -void -SVMSampleListModelEstimator<TInputSampleList, TTrainingSampleList, TMeasurementFunctor> -::SetTrainingSampleList(const TrainingSampleListType* trainingSampleList) -{ - // Process object is not const-correct so the const_cast is required here - this->itk::ProcessObject::SetNthInput(1, - const_cast<TrainingSampleListType*>(trainingSampleList) ); -} - -// Get the input sample list -template<class TInputSampleList, - class TTrainingSampleList, - class TMeasurementFunctor> -const typename SVMSampleListModelEstimator<TInputSampleList, - TTrainingSampleList, - TMeasurementFunctor>::InputSampleListType * -SVMSampleListModelEstimator<TInputSampleList, TTrainingSampleList, TMeasurementFunctor> -::GetInputSampleList( ) -{ - if (this->GetNumberOfInputs() < 2) - { - return ITK_NULLPTR; - } - - return static_cast<const InputSampleListType* > - (this->itk::ProcessObject::GetInput(0) ); -} - -// Get the input label sample list -template<class TInputSampleList, - class TTrainingSampleList, - class TMeasurementFunctor> -const typename SVMSampleListModelEstimator<TInputSampleList, - TTrainingSampleList, - TMeasurementFunctor>::TrainingSampleListType * -SVMSampleListModelEstimator<TInputSampleList, TTrainingSampleList, TMeasurementFunctor> -::GetTrainingSampleList( ) -{ - if (this->GetNumberOfInputs() < 2) - { - return ITK_NULLPTR; - } - - return static_cast<const TrainingSampleListType* > - (this->itk::ProcessObject::GetInput(1)); -} - - -/* - * PrintSelf - */ -template<class TInputSampleList, - class TTrainingSampleList, class TMeasurementFunctor> -void -SVMSampleListModelEstimator<TInputSampleList, TTrainingSampleList, TMeasurementFunctor> -::PrintSelf(std::ostream& os, itk::Indent indent) const -{ - Superclass::PrintSelf(os, indent); -} // end PrintSelf - -/** - * Generate data (start the model building process) - */ -template<class TInputSampleList, - class TTrainingSampleList, class TMeasurementFunctor> -void -SVMSampleListModelEstimator<TInputSampleList, TTrainingSampleList, TMeasurementFunctor> -::PrepareData() -{ - //Do some error checking - InputSampleListPointer inputSampleList = const_cast<InputSampleListType*>(this->GetInputSampleList()); - TrainingSampleListPointer trainingSampleList = const_cast<TrainingSampleListType*>(this->GetTrainingSampleList()); - typename Superclass::ModelType * model = this->GetModel(); - - int inputSampleListSize = inputSampleList->Size(); - int trainingSampleListSize = trainingSampleList->Size(); - - // Check if size of the two inputs are same - if (inputSampleListSize != trainingSampleListSize) - { - /*throw itk::ExceptionObject( - __FILE__, - __LINE__, - "Input pointset size is not the same as the training pointset size.", - ITK_LOCATION); */ - itkExceptionMacro(<< "Input pointset size is not the same as the training pointset size (" - << inputSampleListSize << " vs "<< trainingSampleListSize << ")."); - } - - // Declaration of the iterators on the input and training images - InputSampleListIteratorType inIt = inputSampleList->Begin(); - TrainingSampleListIteratorType trIt = trainingSampleList->Begin(); - - InputSampleListIteratorType inEnd = inputSampleList->End(); - TrainingSampleListIteratorType trEnd = trainingSampleList->End(); - - // Clear previous samples - model->ClearSamples(); - - otbMsgDebugMacro(<< " Input nb points " << inputSampleListSize); - otbMsgDebugMacro(<< " Training nb points " << trainingSampleListSize); - - MeasurementFunctorType mfunctor; - while (inIt != inEnd && trIt != trEnd) - { - typename TTrainingSampleList::MeasurementType label = - trIt.GetMeasurementVector()[0]; - typename TInputSampleList::MeasurementVectorType value = - inIt.GetMeasurementVector(); - model->AddSample(mfunctor(value), label); - ++inIt; - ++trIt; - } -} -} //End namespace OTB -#endif diff --git a/Modules/Learning/SVMLearning/otb-module.cmake b/Modules/Learning/SVMLearning/otb-module.cmake deleted file mode 100644 index 84eefe1b8ca2f15a1af44b705517259374dd7c1b..0000000000000000000000000000000000000000 --- a/Modules/Learning/SVMLearning/otb-module.cmake +++ /dev/null @@ -1,43 +0,0 @@ -# -# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) -# -# This file is part of Orfeo Toolbox -# -# https://www.orfeo-toolbox.org/ -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -set(DOCUMENTATION "Deprecated classes for SVM learning. See module 'Supervised' for a replacement") - -otb_module(OTBSVMLearning - DEPENDS - OTBVectorDataBase - OTBITK - OTBImageBase - OTBLibSVM - OTBLabelMap - OTBStreaming - OTBCommon - - TEST_DEPENDS - OTBStatistics - OTBImageIO - OTBMoments - OTBVectorDataIO - OTBIOXML - OTBTestKernel - - DESCRIPTION - "${DOCUMENTATION}" -) diff --git a/Modules/Learning/SVMLearning/src/CMakeLists.txt b/Modules/Learning/SVMLearning/src/CMakeLists.txt deleted file mode 100644 index f6964736e8d21de119ee3b67d1775f0d7816adc5..0000000000000000000000000000000000000000 --- a/Modules/Learning/SVMLearning/src/CMakeLists.txt +++ /dev/null @@ -1,35 +0,0 @@ -# -# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) -# -# This file is part of Orfeo Toolbox -# -# https://www.orfeo-toolbox.org/ -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -set(OTBSVMLearning_SRC - otbExhaustiveExponentialOptimizer.cxx - ) - -add_library(OTBSVMLearning ${OTBSVMLearning_SRC}) -target_link_libraries(OTBSVMLearning - ${OTBVectorDataBase_LIBRARIES} - ${OTBImageBase_LIBRARIES} - ${OTBLibSVM_LIBRARIES} - ${OTBStreaming_LIBRARIES} - ${OTBCommon_LIBRARIES} - - ) - -otb_module_target(OTBSVMLearning) diff --git a/Modules/Learning/SVMLearning/test/CMakeLists.txt b/Modules/Learning/SVMLearning/test/CMakeLists.txt deleted file mode 100644 index d047ca0a4815c6593de316413b6cf4197a81d742..0000000000000000000000000000000000000000 --- a/Modules/Learning/SVMLearning/test/CMakeLists.txt +++ /dev/null @@ -1,231 +0,0 @@ -# -# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) -# -# This file is part of Orfeo Toolbox -# -# https://www.orfeo-toolbox.org/ -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -otb_module_test() - -set(OTBSVMLearningTests -otbSVMLearningTestDriver.cxx -otbSVMImageClassificationWithRuleFilter.cxx -otbLabelMapSVMClassifier.cxx -otbSVMPointSetModelEstimatorTrain.cxx -otbExhaustiveExponentialOptimizerNew.cxx -otbSVMImageModelEstimatorModelAccessor.cxx -otbSVMImageClassificationFilter.cxx -otbSVMModelNew.cxx -otbSVMImageModelEstimatorNew.cxx -otbSVMImageModelEstimatorTrainOneClass.cxx -otbSVMCrossValidationCostFunctionNew.cxx -otbSVMModelLoadSave.cxx -otbSVMClassifierPointSet.cxx -otbSVMImageClassificationWithRuleFilterNew.cxx -otbSVMImageModelEstimatorTrain.cxx -otbObjectDetectionClassifier.cxx -otbSVMClassifierNew.cxx -otbSVMSampleListModelEstimatorTest.cxx -otbSVMModelAccessor.cxx -otbSVMModelLoad.cxx -otbSVMImageClassificationFilterNew.cxx -otbSVMPointSetModelEstimatorNew.cxx -otbSVMMarginSampler.cxx -otbExhaustiveExponentialOptimizerTest.cxx -) - -add_executable(otbSVMLearningTestDriver ${OTBSVMLearningTests}) -target_link_libraries(otbSVMLearningTestDriver ${OTBSVMLearning-Test_LIBRARIES}) -otb_module_target_label(otbSVMLearningTestDriver) - -# Tests Declaration - -otb_add_test(NAME leTvSVMImageClassificationWithRuleFilter COMMAND otbSVMLearningTestDriver - --compare-image ${NOTOL} - ${BASELINE}/leSVMImageClassificationWithRuleFilterOutput.tif - ${TEMP}/leSVMImageClassificationWithRuleFilterOutput.tif - otbSVMImageClassificationWithRuleFilter - ${INPUTDATA}/ROI_QB_MUL_4.tif - ${INPUTDATA}/svm_model_image - ${TEMP}/leSVMImageClassificationWithRuleFilterOutput.tif) - -#otb_add_test(NAME obTvLabelMapSVMClassifier COMMAND otbSVMLearningTestDriver - #otbLabelMapSVMClassifier - #${INPUTDATA}/maur.tif - #${INPUTDATA}/maur_labelled.tif - #${TEMP}/obTvLabelMapSVMClassifierLabeledOutput.tif) - -otb_add_test(NAME obTuLabelMapSVMClassifierNew COMMAND otbSVMLearningTestDriver - otbLabelMapSVMClassifierNew) - -otb_add_test(NAME leTvSVMPointSetModelEstimatorTrain COMMAND otbSVMLearningTestDriver - --compare-ascii ${EPSILON_3} ${BASELINE_FILES}/leTvsvm_model_pointset - ${TEMP}/leTvsvm_model_pointset - otbSVMPointSetModelEstimatorTrain - ${TEMP}/leTvsvm_model_pointset) - -otb_add_test(NAME leTuExhaustiveExponentialOptimizerNew COMMAND otbSVMLearningTestDriver - otbExhaustiveExponentialOptimizerNew) - -otb_add_test(NAME leTvSVMImageModelEstimatorModelAccessor COMMAND otbSVMLearningTestDriver - --compare-ascii ${EPSILON_3} ${BASELINE_FILES}/leSVMModelEstimatorModelAccessor.txt - ${TEMP}/leSVMModelEstimatorModelAccessor.txt - otbSVMImageModelEstimatorModelAccessor - ${INPUTDATA}/ROI_QB_MUL_4.tif - ${INPUTDATA}/ROI_QB_MUL_4_train.c1.hdr - ${TEMP}/leSVMModelEstimatorModelAccessor.txt) - -otb_add_test(NAME leTvSVMImageClassificationFilter COMMAND otbSVMLearningTestDriver - --compare-image ${NOTOL} - ${BASELINE}/leSVMImageClassificationFilterOutput.tif - ${TEMP}/leSVMImageClassificationFilterOutput.tif - otbSVMImageClassificationFilter - ${INPUTDATA}/ROI_QB_MUL_4.tif - ${INPUTDATA}/svm_model_image - ${TEMP}/leSVMImageClassificationFilterOutput.tif) - - - -otb_add_test(NAME leTuSVMModelNew COMMAND otbSVMLearningTestDriver - otbSVMModelNew) - -otb_add_test(NAME leTuSVMImageModelEstimatorNew COMMAND otbSVMLearningTestDriver - otbSVMImageModelEstimatorNew) - -otb_add_test(NAME leTvSVMImageModelEstimatorTrainOneClass COMMAND otbSVMLearningTestDriver - --compare-ascii ${EPSILON_3} ${BASELINE_FILES}/leTvsvm_model_image_one_class - ${TEMP}/leTvsvm_model_image_one_class - otbSVMImageModelEstimatorTrainOneClass - ${INPUTDATA}/ROI_QB_MUL_4.tif - ${INPUTDATA}/ROI_QB_MUL_4_train_one_class.tif - ${TEMP}/leTvsvm_model_image_one_class) - -otb_add_test(NAME leTuSVMCrossValidationCostFunctionNew COMMAND otbSVMLearningTestDriver - otbSVMCrossValidationCostFunctionNew) - -otb_add_test(NAME leTvSVMModelLoadSave COMMAND otbSVMLearningTestDriver - --compare-ascii ${NOTOL} ${INPUTDATA}/svm_model - ${TEMP}/svmmodel_test - otbSVMModelLoadSave - ${INPUTDATA}/svm_model - ${TEMP}/svmmodel_test) - -otb_add_test(NAME leTvSVMClassifierPointSet COMMAND otbSVMLearningTestDriver - otbSVMClassifierPointSet - ${INPUTDATA}/svm_model_pointset) - -otb_add_test(NAME leTuSVMImageClassificationWithRuleFilterNew COMMAND otbSVMLearningTestDriver - otbSVMImageClassificationWithRuleFilterNew) - -otb_add_test(NAME leTvSVMImageModelEstimatorTrain COMMAND otbSVMLearningTestDriver - --compare-ascii ${EPSILON_3} ${BASELINE_FILES}/leTvsvm_model_image - ${TEMP}/leTvsvm_model_image - otbSVMImageModelEstimatorTrain - ${INPUTDATA}/ROI_QB_MUL_4.tif - ${INPUTDATA}/ROI_QB_MUL_4_train.c1.hdr - ${TEMP}/leTvsvm_model_image - 0 ) - -# RK: 09/2016. LibSVM has serious issues in the code. Fixing this third party code is the right fix -# which requires some time and communication with upstream developer. But in the mean-time this failing test -# cannot be attributed to way OTB or OTB dashboard. For this reason, I am skipping 'baseline' comparison of output -# results. From this day onwards test results are not validated and can have bad results. -# If and When libsvm code is fixed, we put back test validation. Until then, we are extremely sorry for this action. -# Twisting the test to check only some parameters while skipping always problematic ones does not seems a right choice. -# After all, test has problem which is clear, a fix is needed for sure and that fix must be applied upstream - -# --compare-ascii ${EPSILON_3} ${BASELINE_FILES}/leTvsvm_model_image_opt -# ${TEMP}/leTvsvm_model_image_opt - -otb_add_test(NAME leTvSVMImageModelEstimatorTrainWithOptimization COMMAND otbSVMLearningTestDriver - otbSVMImageModelEstimatorTrain - ${INPUTDATA}/ROI_QB_MUL_4.tif - ${INPUTDATA}/ROI_QB_MUL_4_train.c1.hdr - ${TEMP}/leTvsvm_model_image_opt - 1) - -otb_add_test(NAME odTuObjectDetectionClassifierNew COMMAND otbSVMLearningTestDriver - otbObjectDetectionClassifierNew - ) - -otb_add_test(NAME odTvObjectDetectionClassifierStreaming COMMAND otbSVMLearningTestDriver - --compare-ascii ${NOTOL} - ${BASELINE_FILES}/TvObjectDetectionClassifierOutput.txt - ${TEMP}/TvObjectDetectionClassifierOutputStreaming.txt - otbObjectDetectionClassifier - ${INPUTDATA}/ObjectReco/Boats/maur_B010202_01_extract_amplitude.tif - ${INPUTDATA}/ObjectReco/Boats/FeatureStats_RadiometricMoments_amplitude.xml - ${BASELINE_FILES}/TvDescriptorsSVMModelCreation.svm - ${TEMP}/TvObjectDetectionClassifierOutputStreaming.txt - 50 # streaming - 5 # neighborhood radius - ) - -otb_add_test(NAME odTvObjectDetectionClassifier COMMAND otbSVMLearningTestDriver - --compare-ascii ${NOTOL} - ${BASELINE_FILES}/TvObjectDetectionClassifierOutput.txt - ${TEMP}/TvObjectDetectionClassifierOutput.txt - otbObjectDetectionClassifier - ${INPUTDATA}/ObjectReco/Boats/maur_B010202_01_extract_amplitude.tif - ${INPUTDATA}/ObjectReco/Boats/FeatureStats_RadiometricMoments_amplitude.xml - ${BASELINE_FILES}/TvDescriptorsSVMModelCreation.svm - ${TEMP}/TvObjectDetectionClassifierOutput.txt - 0 # streaming - 5 # neighborhood radius - ) - -otb_add_test(NAME leTuSVMClassifierNew COMMAND otbSVMLearningTestDriver - otbSVMClassifierNew) - -otb_add_test(NAME leTvSVMSampleListModelEstimatorTest COMMAND otbSVMLearningTestDriver - --compare-ascii ${EPSILON_4} - ${BASELINE_FILES}/leTvSVMSampleListModelEstimatorModel.txt - ${TEMP}/leTvSVMSampleListModelEstimatorModel.txt - otbSVMSampleListModelEstimatorTest - ${EXAMPLEDATA}/qb_RoadExtract.tif - ${EXAMPLEDATA}/qb_RoadExtract_easyClassification.shp - ${TEMP}/leTvSVMSampleListModelEstimatorModel.txt - ) - -otb_add_test(NAME leTuSVMSampleListModelEstimatorNew COMMAND otbSVMLearningTestDriver - otbSVMSampleListModelEstimatorNew) - -otb_add_test(NAME leTvSVMModelAccessor COMMAND otbSVMLearningTestDriver - --compare-ascii ${EPSILON_5} ${BASELINE_FILES}/leSVMModelAccessor.txt - ${TEMP}/leSVMModelAccessor.txt - otbSVMModelAccessor - ${INPUTDATA}/svm_model - ${TEMP}/leSVMModelAccessor.txt) - -otb_add_test(NAME leTuSVMModelLoad COMMAND otbSVMLearningTestDriver - otbSVMModelLoad - ${INPUTDATA}/svm_model) - -otb_add_test(NAME leTuSVMImageClassificationFilterNew COMMAND otbSVMLearningTestDriver - otbSVMImageClassificationFilterNew) - -otb_add_test(NAME leTuSVMPointSetModelEstimatorNew COMMAND otbSVMLearningTestDriver - otbSVMPointSetModelEstimatorNew) - -otb_add_test(NAME leTuSVMMarginSamplerNew COMMAND otbSVMLearningTestDriver - otbSVMMarginSamplerNew) - -otb_add_test(NAME leTvExhaustiveExponentialOptimizerTest COMMAND otbSVMLearningTestDriver - --compare-ascii ${NOTOL} - ${BASELINE_FILES}/leTvExhaustiveExponentialOptimizerOutput.txt - ${TEMP}/leTvExhaustiveExponentialOptimizerTestOutput.txt - otbExhaustiveExponentialOptimizerTest - ${TEMP}/leTvExhaustiveExponentialOptimizerTestOutput.txt) diff --git a/Modules/Learning/SVMLearning/test/otbSVMClassifierNew.cxx b/Modules/Learning/SVMLearning/test/otbSVMClassifierNew.cxx deleted file mode 100644 index 0d51a3e1cf3847104d81f197114c4c210da678e2..0000000000000000000000000000000000000000 --- a/Modules/Learning/SVMLearning/test/otbSVMClassifierNew.cxx +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - - - -#include "itkPointSetToListSampleAdaptor.h" -#include "itkSubsample.h" -#include "otbSVMClassifier.h" - -int otbSVMClassifierNew(int itkNotUsed(argc), char * itkNotUsed(argv) []) -{ - typedef double InputPixelType; - typedef int LabelPixelType; - typedef itk::PointSet<InputPixelType, 2> PointSetType; - - typedef itk::Statistics::PointSetToListSampleAdaptor<PointSetType> - DataSampleType; - - typedef otb::SVMClassifier<DataSampleType, LabelPixelType> ClassifierType; - - ClassifierType::Pointer classifier = ClassifierType::New(); - - std::cout << classifier << std::endl; - - return EXIT_SUCCESS; -} diff --git a/Modules/Learning/SVMLearning/test/otbSVMClassifierPointSet.cxx b/Modules/Learning/SVMLearning/test/otbSVMClassifierPointSet.cxx deleted file mode 100644 index 8dcb30d277b1e627869182e8604bd32bcedafa91..0000000000000000000000000000000000000000 --- a/Modules/Learning/SVMLearning/test/otbSVMClassifierPointSet.cxx +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - - - -#include <fstream> - -#include "itkPoint.h" - -#include "itkPointSetToListSampleAdaptor.h" -#include "itkSubsample.h" -#include "otbSVMClassifier.h" - -int otbSVMClassifierPointSet(int argc, char* argv[]) -{ - if (argc != 2) - { - std::cout << "Usage : " << argv[0] << " modelFile" - << std::endl; - return EXIT_FAILURE; - } - - const char * modelFilename = argv[1]; - - std::cout << "Building the pointset" << std::endl; - - typedef double InputPixelType; - typedef int LabelPixelType; - typedef std::vector<InputPixelType> InputVectorType; - const unsigned int Dimension = 2; - - typedef itk::PointSet<InputVectorType, Dimension> - MeasurePointSetType; - - MeasurePointSetType::Pointer mPSet = MeasurePointSetType::New(); - - typedef MeasurePointSetType::PointType MeasurePointType; - - typedef MeasurePointSetType::PointsContainer MeasurePointsContainer; - - MeasurePointsContainer::Pointer mCont = MeasurePointsContainer::New(); - - unsigned int pointId; - - for (pointId = 0; pointId < 20; pointId++) - { - - MeasurePointType mP; - - mP[0] = pointId; - mP[1] = pointId; - - InputVectorType measure; - //measure.push_back(vcl_pow(pointId, 2.0)); - measure.push_back(double(2.0 * pointId)); - measure.push_back(double(-10)); - - mCont->InsertElement(pointId, mP); - mPSet->SetPointData(pointId, measure); - - } - - mPSet->SetPoints(mCont); - - std::cout << "PointSet built" << std::endl; - - typedef itk::Statistics::PointSetToListSampleAdaptor<MeasurePointSetType> - SampleType; - SampleType::Pointer sample = SampleType::New(); - sample->SetPointSet(mPSet); - - std::cout << "Sample set to Adaptor" << std::endl; - - /** preparing classifier and decision rule object */ - typedef otb::SVMModel<SampleType::MeasurementVectorType::ValueType, LabelPixelType> ModelType; - - ModelType::Pointer model = ModelType::New(); - - model->LoadModel(modelFilename); - - std::cout << "Model loaded" << std::endl; - - int numberOfClasses = model->GetNumberOfClasses(); - - typedef otb::SVMClassifier<SampleType, LabelPixelType> ClassifierType; - - ClassifierType::Pointer classifier = ClassifierType::New(); - - classifier->SetNumberOfClasses(numberOfClasses); - classifier->SetModel(model); - classifier->SetInput(sample.GetPointer()); - classifier->Update(); - - /* Build the class map */ - - std::cout << "classifier get output" << std::endl; - ClassifierType::OutputType* membershipSample = - classifier->GetOutput(); - std::cout << "Sample iterators" << std::endl; - ClassifierType::OutputType::ConstIterator m_iter = - membershipSample->Begin(); - ClassifierType::OutputType::ConstIterator m_last = - membershipSample->End(); - - double error = 0.0; - pointId = 0; - while (m_iter != m_last) - { - ClassifierType::ClassLabelType label = m_iter.GetClassLabel(); - - InputVectorType measure; - - mPSet->GetPointData(pointId, &measure); - - if (label != ((measure[0] + measure[1]) > 0)) error++; - - std::cout << label << "/" << - ((measure[0] + measure[1]) > 0) << std::endl; - - ++pointId; - ++m_iter; - } - - std::cout << "Error = " << error / pointId << std::endl; - - return EXIT_SUCCESS; -} diff --git a/Modules/Learning/SVMLearning/test/otbSVMImageClassificationFilter.cxx b/Modules/Learning/SVMLearning/test/otbSVMImageClassificationFilter.cxx deleted file mode 100644 index aabfdcebb06cc8bcea83cb676584a86023abb55b..0000000000000000000000000000000000000000 --- a/Modules/Learning/SVMLearning/test/otbSVMImageClassificationFilter.cxx +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "otbSVMImageClassificationFilter.h" -#include "otbVectorImage.h" -#include "otbImage.h" -#include "otbImageFileReader.h" -#include "otbImageFileWriter.h" - -int otbSVMImageClassificationFilter(int itkNotUsed(argc), char * argv[]) -{ - const char * infname = argv[1]; - const char * modelfname = argv[2]; - const char * outfname = argv[3]; - - const unsigned int Dimension = 2; - typedef double PixelType; - typedef unsigned short LabeledPixelType; - - typedef otb::VectorImage<PixelType, Dimension> ImageType; - typedef otb::Image<LabeledPixelType, Dimension> LabeledImageType; - typedef otb::SVMImageClassificationFilter<ImageType, LabeledImageType> ClassificationFilterType; - typedef ClassificationFilterType::ModelType ModelType; - typedef otb::ImageFileReader<ImageType> ReaderType; - typedef otb::ImageFileWriter<LabeledImageType> WriterType; - - // Instantiating object - ClassificationFilterType::Pointer filter = ClassificationFilterType::New(); - - ReaderType::Pointer reader = ReaderType::New(); - reader->SetFileName(infname); - - ModelType::Pointer model = ModelType::New(); - model->LoadModel(modelfname); - - filter->SetModel(model); - filter->SetInput(reader->GetOutput()); - - WriterType::Pointer writer = WriterType::New(); - writer->SetInput(filter->GetOutput()); - writer->SetFileName(outfname); - writer->Update(); - - return EXIT_SUCCESS; -} diff --git a/Modules/Learning/SVMLearning/test/otbSVMImageClassificationFilterNew.cxx b/Modules/Learning/SVMLearning/test/otbSVMImageClassificationFilterNew.cxx deleted file mode 100644 index 4f17c6b9dd57d79524192aa9d92fa82221d70c63..0000000000000000000000000000000000000000 --- a/Modules/Learning/SVMLearning/test/otbSVMImageClassificationFilterNew.cxx +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "otbSVMImageClassificationFilter.h" -#include "otbVectorImage.h" -#include "otbImage.h" - -int otbSVMImageClassificationFilterNew(int itkNotUsed(argc), char * itkNotUsed(argv) []) -{ - const unsigned int Dimension = 2; - typedef double PixelType; - typedef unsigned short LabeledPixelType; - - typedef otb::VectorImage<PixelType, Dimension> ImageType; - typedef otb::Image<LabeledPixelType, Dimension> LabeledImageType; - - typedef otb::SVMImageClassificationFilter<ImageType, LabeledImageType> ClassificationFilterType; - - // Instantiating object - ClassificationFilterType::Pointer filter = ClassificationFilterType::New(); - - std::cout << filter << std::endl; - - return EXIT_SUCCESS; -} diff --git a/Modules/Learning/SVMLearning/test/otbSVMImageClassificationWithRuleFilter.cxx b/Modules/Learning/SVMLearning/test/otbSVMImageClassificationWithRuleFilter.cxx deleted file mode 100644 index ea6785b5f87740536423c3a6a057af1c75056cf1..0000000000000000000000000000000000000000 --- a/Modules/Learning/SVMLearning/test/otbSVMImageClassificationWithRuleFilter.cxx +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "otbSVMImageClassificationWithRuleFilter.h" -#include "otbImage.h" -#include "otbImageFileReader.h" -#include "otbImageFileWriter.h" - -int otbSVMImageClassificationWithRuleFilter(int itkNotUsed(argc), char * argv[]) -{ - const char * infname = argv[1]; - const char * modelfname = argv[2]; - const char * outfname = argv[3]; - - const unsigned int Dimension = 2; - typedef double PixelType; - typedef unsigned short LabeledPixelType; - - typedef otb::VectorImage<PixelType, Dimension> ImageType; - typedef otb::Image<LabeledPixelType, Dimension> LabeledImageType; - typedef otb::SVMImageClassificationWithRuleFilter<ImageType, LabeledImageType> ClassificationFilterType; - typedef ClassificationFilterType::ModelType ModelType; - typedef otb::ImageFileReader<ImageType> ReaderType; - typedef otb::ImageFileWriter<LabeledImageType> WriterType; - - // Instantiating object - ClassificationFilterType::Pointer filter = ClassificationFilterType::New(); - - ReaderType::Pointer reader = ReaderType::New(); - reader->SetFileName(infname); - - ModelType::Pointer model = ModelType::New(); - model->LoadModel(modelfname); - - filter->SetModel(model); - filter->SetInput(reader->GetOutput()); - - WriterType::Pointer writer = WriterType::New(); - writer->SetInput(filter->GetOutput()); - writer->SetFileName(outfname); - writer->Update(); - - return EXIT_SUCCESS; -} diff --git a/Modules/Learning/SVMLearning/test/otbSVMImageClassificationWithRuleFilterNew.cxx b/Modules/Learning/SVMLearning/test/otbSVMImageClassificationWithRuleFilterNew.cxx deleted file mode 100644 index 6fa5d229e69ebcba966ee7dcdb9b7ef323a2a3ba..0000000000000000000000000000000000000000 --- a/Modules/Learning/SVMLearning/test/otbSVMImageClassificationWithRuleFilterNew.cxx +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "otbSVMImageClassificationWithRuleFilter.h" -#include "otbImage.h" - -int otbSVMImageClassificationWithRuleFilterNew(int itkNotUsed(argc), char * itkNotUsed(argv) []) -{ - const unsigned int Dimension = 2; - typedef double PixelType; - typedef unsigned short LabeledPixelType; - - typedef otb::VectorImage<PixelType, Dimension> ImageType; - typedef otb::Image<LabeledPixelType, Dimension> LabeledImageType; - - typedef otb::SVMImageClassificationWithRuleFilter<ImageType, LabeledImageType> ClassificationWithRuleFilterType; - - // Instantiating object - ClassificationWithRuleFilterType::Pointer filter = ClassificationWithRuleFilterType::New(); - - std::cout << filter << std::endl; - - return EXIT_SUCCESS; -} diff --git a/Modules/Learning/SVMLearning/test/otbSVMImageModelEstimatorModelAccessor.cxx b/Modules/Learning/SVMLearning/test/otbSVMImageModelEstimatorModelAccessor.cxx deleted file mode 100644 index 777a04fb9b5c0fd147f1a196075c35b0867e29cf..0000000000000000000000000000000000000000 --- a/Modules/Learning/SVMLearning/test/otbSVMImageModelEstimatorModelAccessor.cxx +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - - - -#include <iomanip> -#include <iostream> -#include <fstream> - -#include "itkMacro.h" -#include "otbImage.h" -#include "otbVectorImage.h" - -#include "otbSVMModel.h" -#include "otbSVMImageModelEstimator.h" - -#include "otbImageFileReader.h" - -int otbSVMImageModelEstimatorModelAccessor(int itkNotUsed(argc), char* argv[]) -{ - const char* inputImageFileName = argv[1]; - const char* trainingImageFileName = argv[2]; - const char* outputModelFileName = argv[3]; - - typedef double InputPixelType; - const unsigned int Dimension = 2; - - typedef otb::VectorImage<InputPixelType, Dimension> InputImageType; - - typedef otb::Image<int, Dimension> TrainingImageType; - - typedef otb::SVMImageModelEstimator<InputImageType, - TrainingImageType> EstimatorType; - - typedef otb::ImageFileReader<InputImageType> InputReaderType; - typedef otb::ImageFileReader<TrainingImageType> TrainingReaderType; - - InputReaderType::Pointer inputReader = InputReaderType::New(); - TrainingReaderType::Pointer trainingReader = TrainingReaderType::New(); - - inputReader->SetFileName(inputImageFileName); - trainingReader->SetFileName(trainingImageFileName); - - inputReader->Update(); - trainingReader->Update(); - - EstimatorType::Pointer svmEstimator = EstimatorType::New(); - - svmEstimator->SetInputImage(inputReader->GetOutput()); - svmEstimator->SetTrainingImage(trainingReader->GetOutput()); - svmEstimator->ParametersOptimizationOff(); - - svmEstimator->Update(); - - typedef EstimatorType::SVMModelPointer SVMModelPointer; - SVMModelPointer ptrModel = svmEstimator->GetModel(); - - std::ofstream f; - unsigned int nbClass = ptrModel->GetNumberOfClasses(); - unsigned int nbSupportVector = ptrModel->GetNumberOfSupportVectors(); - - f.open(outputModelFileName); - f << "Test methods of SVMModel class:" << std::endl; - f << " - GetNumberOfClasses() " << nbClass << std::endl; - f << " - GetNumberOfHyperplane() " << ptrModel->GetNumberOfHyperplane() << std::endl; - f << " - GetNumberOfSupportVectors() " << nbSupportVector << std::endl; - - f << " - GetSupportVectors() [nb support vector][]" << std::endl; - svm_node ** SVs = ptrModel->GetSupportVectors(); - if (SVs == ITK_NULLPTR) - { - itkGenericExceptionMacro(<< "SVs NULL"); - } - for (unsigned int i = 0; i < nbSupportVector; ++i) - { - if (SVs[i] == ITK_NULLPTR) itkGenericExceptionMacro(<< "SVs " << i << " NULL"); - f << std::endl; - f << " SV[" << i << "]:"; - const svm_node *p = SVs[i]; - /* for(unsigned int j=0; j<nbSupportVector; ++j) - { - f << " SV["<<i<<"]["<<j<<"]:"; */ - if (svmEstimator->GetKernelType() == PRECOMPUTED) - { - f << " " << p->value; - - } - else - { - while (p->index != -1) - { - f << " [" << p->index << ";" << p->value << "] "; - p++; - } - } - f << std::endl; - // } - } - - f << " - GetRho() [nr_class*(nr_class-1)/2]" << std::endl; - unsigned int taille = nbClass * (nbClass - 1) / 2; - double * rhos = ptrModel->GetRho(); - if (rhos == ITK_NULLPTR) - { - itkGenericExceptionMacro(<< "rhos NULL"); - } - f << std::setprecision(10) << " "; - for (unsigned int i = 0; i < taille; ++i) - { - f << " " << rhos[i]; - } - - f << std::endl; - f << " - GetAlpha() [nb class-1][nb support vector]" << std::endl; - double ** alphas = ptrModel->GetAlpha(); - if (alphas == ITK_NULLPTR) - { - itkGenericExceptionMacro(<< "alphas NULL"); - } - for (unsigned int i = 0; i < nbClass - 1; ++i) - { - if (alphas[i] == ITK_NULLPTR) itkGenericExceptionMacro(<< "alphas " << i << " NULL"); - f << " "; - for (unsigned int j = 0; j < nbSupportVector; ++j) - { - f << " " << alphas[i][j]; - } - } - f << std::endl; - // f << " - Evaluate() (double) -> "<<ptrModel->Evaluate()<<std::endl; - -// typedef SVMModelType::ValuesType ValuesType; -// ValuesType _evaluateHyperplaneDistance; -// _evaluateHyperplaneDistance = ptrModel->EvaluateHyperplaneDistance(); - -// f << " - EvaluateHyperplaneDistance() VariableLengthVector() nb value(s): "<<_evaluateHyperplaneDistance.Size()<<std::endl; -// for (unsigned int i=0; i<_evaluateHyperplaneDistance.Size(); ++i) -// { -// f << " "<<_evaluateHyperplaneDistance[i]<<std::endl; -// } - f << "end" << std::endl; - f.close(); - - return EXIT_SUCCESS; -} diff --git a/Modules/Learning/SVMLearning/test/otbSVMImageModelEstimatorNew.cxx b/Modules/Learning/SVMLearning/test/otbSVMImageModelEstimatorNew.cxx deleted file mode 100644 index 3c2934c68b3da3de7a1da463858313008630dd2c..0000000000000000000000000000000000000000 --- a/Modules/Learning/SVMLearning/test/otbSVMImageModelEstimatorNew.cxx +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - - - -#include "itkMacro.h" -#include "otbImage.h" -#include "otbVectorImage.h" -#include <iostream> - -#include "otbSVMImageModelEstimator.h" - -int otbSVMImageModelEstimatorNew(int itkNotUsed(argc), char * itkNotUsed(argv) []) -{ - typedef double InputPixelType; - const unsigned int Dimension = 2; - - typedef otb::VectorImage<InputPixelType, Dimension> InputImageType; - - typedef otb::Image<InputPixelType, Dimension> TrainingImageType; - - typedef otb::SVMImageModelEstimator<InputImageType, - TrainingImageType> EstimatorType; - - EstimatorType::Pointer svmModel = EstimatorType::New(); - - std::cout << svmModel << std::endl; - - return EXIT_SUCCESS; -} diff --git a/Modules/Learning/SVMLearning/test/otbSVMImageModelEstimatorTrain.cxx b/Modules/Learning/SVMLearning/test/otbSVMImageModelEstimatorTrain.cxx deleted file mode 100644 index adbde202a055fd44502d30fcd532e62bfc09b35c..0000000000000000000000000000000000000000 --- a/Modules/Learning/SVMLearning/test/otbSVMImageModelEstimatorTrain.cxx +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - - - -#include "itkMacro.h" -#include "otbImage.h" -#include "otbVectorImage.h" -#include <iostream> - -#include "otbSVMImageModelEstimator.h" - -#include "otbImageFileReader.h" - -int otbSVMImageModelEstimatorTrain(int itkNotUsed(argc), char* argv[]) -{ - // Force the pseudo-random number generator to always output - // the same sequence of random numbers - // Done because, in case of optimization, rand() is called by libsvm - srand(0); - - const char* inputImageFileName = argv[1]; - const char* trainingImageFileName = argv[2]; - const char* outputModelFileName = argv[3]; - const bool optimization = atoi(argv[4]); - - typedef double InputPixelType; - const unsigned int Dimension = 2; - typedef otb::VectorImage<InputPixelType, Dimension> InputImageType; - typedef otb::Image<int, Dimension> TrainingImageType; - typedef otb::SVMImageModelEstimator<InputImageType, - TrainingImageType> EstimatorType; - typedef otb::ImageFileReader<InputImageType> InputReaderType; - typedef otb::ImageFileReader<TrainingImageType> TrainingReaderType; - - InputReaderType::Pointer inputReader = InputReaderType::New(); - TrainingReaderType::Pointer trainingReader = TrainingReaderType::New(); - EstimatorType::Pointer svmEstimator = EstimatorType::New(); - - inputReader->SetFileName(inputImageFileName); - trainingReader->SetFileName(trainingImageFileName); - inputReader->Update(); - trainingReader->Update(); - - svmEstimator->SetInputImage(inputReader->GetOutput()); - svmEstimator->SetTrainingImage(trainingReader->GetOutput()); - svmEstimator->SetParametersOptimization(optimization); - - svmEstimator->Update(); - - otbGenericMsgDebugMacro(<< "Saving model"); - svmEstimator->GetModel()->SaveModel(outputModelFileName); - - return EXIT_SUCCESS; -} diff --git a/Modules/Learning/SVMLearning/test/otbSVMImageModelEstimatorTrainOneClass.cxx b/Modules/Learning/SVMLearning/test/otbSVMImageModelEstimatorTrainOneClass.cxx deleted file mode 100644 index be11582f1f2422de6173f2dffceb8a42d160765d..0000000000000000000000000000000000000000 --- a/Modules/Learning/SVMLearning/test/otbSVMImageModelEstimatorTrainOneClass.cxx +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - - - -#include "itkMacro.h" -#include "otbImage.h" -#include "otbVectorImage.h" -#include <iostream> - -#include "otbSVMImageModelEstimator.h" - -#include "otbImageFileReader.h" - -int otbSVMImageModelEstimatorTrainOneClass(int itkNotUsed(argc), char* argv[]) -{ - const char* inputImageFileName = argv[1]; - const char* trainingImageFileName = argv[2]; - const char* outputModelFileName = argv[3]; - - typedef double InputPixelType; - const unsigned int Dimension = 2; - typedef otb::VectorImage<InputPixelType, Dimension> InputImageType; - typedef otb::Image<int, Dimension> TrainingImageType; - typedef otb::SVMImageModelEstimator<InputImageType, - TrainingImageType> EstimatorType; - typedef otb::ImageFileReader<InputImageType> InputReaderType; - typedef otb::ImageFileReader<TrainingImageType> TrainingReaderType; - - InputReaderType::Pointer inputReader = InputReaderType::New(); - TrainingReaderType::Pointer trainingReader = TrainingReaderType::New(); - EstimatorType::Pointer svmEstimator = EstimatorType::New(); - - inputReader->SetFileName(inputImageFileName); - trainingReader->SetFileName(trainingImageFileName); - inputReader->Update(); - trainingReader->Update(); - - svmEstimator->SetInputImage(inputReader->GetOutput()); - svmEstimator->SetTrainingImage(trainingReader->GetOutput()); - svmEstimator->SetSVMType(ONE_CLASS); - - svmEstimator->Update(); - - otbGenericMsgDebugMacro(<< "Saving model"); - svmEstimator->GetModel()->SaveModel(outputModelFileName); - - return EXIT_SUCCESS; -} diff --git a/Modules/Learning/SVMLearning/test/otbSVMLearningTestDriver.cxx b/Modules/Learning/SVMLearning/test/otbSVMLearningTestDriver.cxx deleted file mode 100644 index cc7c12c3e625aa191dd578580182b514b1ed5854..0000000000000000000000000000000000000000 --- a/Modules/Learning/SVMLearning/test/otbSVMLearningTestDriver.cxx +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "otbTestMain.h" - -void RegisterTests() -{ - REGISTER_TEST(otbSVMImageClassificationWithRuleFilter); - REGISTER_TEST(otbLabelMapSVMClassifierNew); - REGISTER_TEST(otbLabelMapSVMClassifier); - REGISTER_TEST(otbSVMPointSetModelEstimatorTrain); - REGISTER_TEST(otbExhaustiveExponentialOptimizerNew); - REGISTER_TEST(otbSVMImageModelEstimatorModelAccessor); - REGISTER_TEST(otbSVMImageClassificationFilter); - REGISTER_TEST(otbSVMModelNew); - REGISTER_TEST(otbSVMImageModelEstimatorNew); - REGISTER_TEST(otbSVMImageModelEstimatorTrainOneClass); - REGISTER_TEST(otbSVMCrossValidationCostFunctionNew); - REGISTER_TEST(otbSVMModelLoadSave); - REGISTER_TEST(otbSVMClassifierPointSet); - REGISTER_TEST(otbSVMImageClassificationWithRuleFilterNew); - REGISTER_TEST(otbSVMImageModelEstimatorTrain); - REGISTER_TEST(otbObjectDetectionClassifierNew); - REGISTER_TEST(otbObjectDetectionClassifier); - REGISTER_TEST(otbSVMClassifierNew); - REGISTER_TEST(otbSVMSampleListModelEstimatorNew); - REGISTER_TEST(otbSVMSampleListModelEstimatorTest); - REGISTER_TEST(otbSVMModelAccessor); - REGISTER_TEST(otbSVMModelLoad); - REGISTER_TEST(otbSVMImageClassificationFilterNew); - REGISTER_TEST(otbSVMPointSetModelEstimatorNew); - REGISTER_TEST(otbSVMMarginSamplerNew); - REGISTER_TEST(otbExhaustiveExponentialOptimizerTest); -} diff --git a/Modules/Learning/SVMLearning/test/otbSVMModelAccessor.cxx b/Modules/Learning/SVMLearning/test/otbSVMModelAccessor.cxx deleted file mode 100644 index d563bb1efaeb27848a2a0a8316c898b8695e9e53..0000000000000000000000000000000000000000 --- a/Modules/Learning/SVMLearning/test/otbSVMModelAccessor.cxx +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - - - -#include "itkMacro.h" -#include "otbImage.h" -#include <iostream> -#include <fstream> - -#include "otbSVMModel.h" - -int otbSVMModelAccessor(int itkNotUsed(argc), char* argv[]) -{ - typedef unsigned char InputPixelType; - typedef unsigned char LabelPixelType; - - typedef otb::SVMModel<InputPixelType, LabelPixelType> ModelType; - - ModelType::Pointer ptrModel = ModelType::New(); - - ptrModel->LoadModel(argv[1]); - - std::ofstream f; - unsigned int nbClass = ptrModel->GetNumberOfClasses(); - unsigned int nbSupportVector = ptrModel->GetNumberOfSupportVectors(); - - f.open(argv[2]); - f << "Test methods of SVMModel class:" << std::endl; - f << " - GetNumberOfClasses() " << nbClass << std::endl; - f << " - GetNumberOfHyperplane() " << ptrModel->GetNumberOfHyperplane() << std::endl; - f << " - GetNumberOfSupportVectors() " << nbSupportVector << std::endl; - - f << " - GetSupportVectors() [nb support vector][]" << std::endl; - svm_node ** SVs = ptrModel->GetSupportVectors(); - if (SVs == ITK_NULLPTR) - { - itkGenericExceptionMacro(<< "SVs NULL"); - } - for (unsigned int i = 0; i < nbSupportVector; ++i) - { - if (SVs[i] == ITK_NULLPTR) itkGenericExceptionMacro(<< "SVs " << i << " NULL"); - f << std::endl; - f << " SV[" << i << "]:"; - const svm_node *p = SVs[i]; - while (p->index != -1) - { - f << " [" << p->index << ";" << p->value << "] "; - p++; - } - f << std::endl; - } - - f << " - GetRho() [nr_class*(nr_class-1)/2]" << std::endl; - unsigned int taille = nbClass * (nbClass - 1) / 2; - double * rhos = ptrModel->GetRho(); - if (rhos == ITK_NULLPTR) - { - itkGenericExceptionMacro(<< "rhos NULL"); - } - f << " "; - for (unsigned int i = 0; i < taille; ++i) - { - f << " " << rhos[i]; - } - - f << std::endl; - f << " - GetAlpha() [nb class-1][nb support vector]" << std::endl; - double ** alphas = ptrModel->GetAlpha(); - if (alphas == ITK_NULLPTR) - { - itkGenericExceptionMacro(<< "alphas NULL"); - } - for (unsigned int i = 0; i < nbClass - 1; ++i) - { - if (alphas[i] == ITK_NULLPTR) itkGenericExceptionMacro(<< "alphas " << i << " NULL"); - f << " "; - for (unsigned int j = 0; j < nbSupportVector; ++j) - { - f << " " << alphas[i][j]; - } - } - f << std::endl; -// f << " - Evaluate() (double) -> "<<ptrModel->Evaluate()<<std::endl; - -// typedef ModelType::ValuesType ValuesType; -// ValuesType _evaluateHyperplaneDistance; -// _evaluateHyperplaneDistance = ptrModel->EvaluateHyperplaneDistance(); - -// f << " - EvaluateHyperplaneDistance() VariableLengthVector() nb value(s): "<<_evaluateHyperplaneDistance.Size()<<std::endl; -// for (unsigned int i=0; i<_evaluateHyperplaneDistance.Size(); ++i) -// { -// f << " "<<_evaluateHyperplaneDistance[i]<<std::endl; -// } - f << "end" << std::endl; - f.close(); - - return EXIT_SUCCESS; -} diff --git a/Modules/Learning/SVMLearning/test/otbSVMModelCopyTest.cxx b/Modules/Learning/SVMLearning/test/otbSVMModelCopyTest.cxx deleted file mode 100644 index 9d6552c6c93076645bdf7e2c412460d77cb7410f..0000000000000000000000000000000000000000 --- a/Modules/Learning/SVMLearning/test/otbSVMModelCopyTest.cxx +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -#include "itkMacro.h" -#include "otbImage.h" -#include <iostream> - -#include "otbSVMModel.h" - -int otbSVMModelCopyTest(int itkNotUsed(argc), char* argv[]) -{ - typedef unsigned char InputPixelType; - typedef unsigned char LabelPixelType; - - typedef otb::SVMModel<InputPixelType, LabelPixelType> ModelType; - - ModelType::Pointer svmModel = ModelType::New(); - - svmModel->LoadModel(argv[1]); - - ModelType::Pointer svmModelCopy = svmModel->GetCopy(); - svmModelCopy->SaveModel(argv[2]); - - return EXIT_SUCCESS; -} diff --git a/Modules/Learning/SVMLearning/test/otbSVMModelLoad.cxx b/Modules/Learning/SVMLearning/test/otbSVMModelLoad.cxx deleted file mode 100644 index 698c6a7266b07e937232abf43ef838dd7467f467..0000000000000000000000000000000000000000 --- a/Modules/Learning/SVMLearning/test/otbSVMModelLoad.cxx +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - - - -#include "itkMacro.h" -#include "otbImage.h" -#include <iostream> - -#include "otbSVMModel.h" - -int otbSVMModelLoad(int itkNotUsed(argc), char* argv[]) -{ - typedef unsigned char InputPixelType; - typedef unsigned char LabelPixelType; - typedef otb::SVMModel<InputPixelType, LabelPixelType> ModelType; - - ModelType::Pointer svmModel = ModelType::New(); - - svmModel->LoadModel(argv[1]); - - return EXIT_SUCCESS; -} diff --git a/Modules/Learning/SVMLearning/test/otbSVMModelLoadSave.cxx b/Modules/Learning/SVMLearning/test/otbSVMModelLoadSave.cxx deleted file mode 100644 index cc8ef32438770527ab0054b04dd9e5772e69501e..0000000000000000000000000000000000000000 --- a/Modules/Learning/SVMLearning/test/otbSVMModelLoadSave.cxx +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - - - -#include "itkMacro.h" -#include "otbImage.h" -#include <iostream> - -#include "otbSVMModel.h" - -int otbSVMModelLoadSave(int itkNotUsed(argc), char* argv[]) -{ - typedef unsigned char InputPixelType; - typedef unsigned char LabelPixelType; - - typedef otb::SVMModel<InputPixelType, LabelPixelType> ModelType; - - ModelType::Pointer svmModel = ModelType::New(); - - svmModel->LoadModel(argv[1]); - svmModel->SaveModel(argv[2]); - - return EXIT_SUCCESS; -} diff --git a/Modules/Learning/SVMLearning/test/otbSVMModelNew.cxx b/Modules/Learning/SVMLearning/test/otbSVMModelNew.cxx deleted file mode 100644 index 4362e5044c39732341acd866af7b1fdc696c3c41..0000000000000000000000000000000000000000 --- a/Modules/Learning/SVMLearning/test/otbSVMModelNew.cxx +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - - - -#include "itkMacro.h" -#include "otbImage.h" -#include <iostream> - -#include "otbSVMModel.h" - -int otbSVMModelNew(int itkNotUsed(argc), char * itkNotUsed(argv) []) -{ - typedef unsigned char InputPixelType; - typedef unsigned char LabelPixelType; - - typedef otb::SVMModel<InputPixelType, LabelPixelType> ModelType; - - ModelType::Pointer svmModel = ModelType::New(); - - std::cout << svmModel << std::endl; - - return EXIT_SUCCESS; -} diff --git a/Modules/Learning/SVMLearning/test/otbSVMPointSetModelEstimatorNew.cxx b/Modules/Learning/SVMLearning/test/otbSVMPointSetModelEstimatorNew.cxx deleted file mode 100644 index 763753c9e502caf5aabdf00c7d15f9db077f1f57..0000000000000000000000000000000000000000 --- a/Modules/Learning/SVMLearning/test/otbSVMPointSetModelEstimatorNew.cxx +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - - - -#include "itkMacro.h" -#include "itkPointSet.h" -#include <iostream> - -#include "otbSVMPointSetModelEstimator.h" - -int otbSVMPointSetModelEstimatorNew(int itkNotUsed(argc), char * itkNotUsed(argv) []) -{ - typedef std::vector<double> InputPixelType; - typedef double LabelPixelType; - const unsigned int Dimension = 2; - - typedef itk::PointSet<InputPixelType, Dimension> MeasurePointSetType; - typedef itk::PointSet<LabelPixelType, Dimension> LabelPointSetType; - typedef otb::SVMPointSetModelEstimator<MeasurePointSetType, - LabelPointSetType> EstimatorType; - - EstimatorType::Pointer estimator = EstimatorType::New(); - - std::cout << estimator << std::endl; - - return EXIT_SUCCESS; -} diff --git a/Modules/Learning/SVMLearning/test/otbSVMPointSetModelEstimatorTrain.cxx b/Modules/Learning/SVMLearning/test/otbSVMPointSetModelEstimatorTrain.cxx deleted file mode 100644 index d4946371efda6834bc60132a95330aa66da3ad3f..0000000000000000000000000000000000000000 --- a/Modules/Learning/SVMLearning/test/otbSVMPointSetModelEstimatorTrain.cxx +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - - - -#include "itkMacro.h" -#include "itkPointSet.h" -#include <iostream> - -#include "otbSVMPointSetModelEstimator.h" - -int otbSVMPointSetModelEstimatorTrain(int itkNotUsed(argc), char* argv[]) -{ - const char* outputModelFileName = argv[1]; - - typedef std::vector<double> InputPixelType; - typedef double LabelPixelType; - const unsigned int Dimension = 2; - - typedef itk::PointSet<InputPixelType, Dimension> MeasurePointSetType; - typedef itk::PointSet<LabelPixelType, Dimension> LabelPointSetType; - typedef MeasurePointSetType::PointType MeasurePointType; - typedef LabelPointSetType::PointType LabelPointType; - typedef MeasurePointSetType::PointsContainer MeasurePointsContainer; - typedef LabelPointSetType::PointsContainer LabelPointsContainer; - - MeasurePointSetType::Pointer mPSet = MeasurePointSetType::New(); - LabelPointSetType::Pointer lPSet = LabelPointSetType::New(); - MeasurePointsContainer::Pointer mCont = MeasurePointsContainer::New(); - LabelPointsContainer::Pointer lCont = LabelPointsContainer::New(); - - for (unsigned int pointId = 0; pointId < 20; pointId++) - { - MeasurePointType mP; - LabelPointType lP; - - mP[0] = pointId; - mP[1] = pointId; - - lP[0] = pointId; - lP[1] = pointId; - - InputPixelType measure; - measure.push_back(double(2.0 * pointId)); - measure.push_back(double(-10)); - - LabelPixelType label = static_cast<LabelPixelType>((measure[0] + measure[1]) > 0); //2x-10>0 - - mCont->InsertElement(pointId, mP); - mPSet->SetPointData(pointId, measure); - - lCont->InsertElement(pointId, lP); - lPSet->SetPointData(pointId, label); - } - - mPSet->SetPoints(mCont); - lPSet->SetPoints(lCont); - - typedef otb::SVMPointSetModelEstimator<MeasurePointSetType, LabelPointSetType> EstimatorType; - EstimatorType::Pointer estimator = EstimatorType::New(); - - estimator->SetInputPointSet(mPSet); - estimator->SetTrainingPointSet(lPSet); - estimator->ParametersOptimizationOff(); - - estimator->Update(); - - estimator->GetModel()->SaveModel(outputModelFileName); - - return EXIT_SUCCESS; -} diff --git a/Modules/Learning/SVMLearning/test/otbSVMSampleListModelEstimatorTest.cxx b/Modules/Learning/SVMLearning/test/otbSVMSampleListModelEstimatorTest.cxx deleted file mode 100644 index 55c76bf55e07a82a07d2b5cd74dd73495204ecbd..0000000000000000000000000000000000000000 --- a/Modules/Learning/SVMLearning/test/otbSVMSampleListModelEstimatorTest.cxx +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - - - -#include "itkMacro.h" -#include <iostream> - -#include "otbSVMSampleListModelEstimator.h" - -#include "otbVectorImage.h" -#include "otbImageFileReader.h" - -#include "otbVectorData.h" -#include "otbVectorDataFileReader.h" - -#include "otbListSampleGenerator.h" - -int otbSVMSampleListModelEstimatorNew(int itkNotUsed(argc), char * itkNotUsed(argv) []) -{ - typedef double InputPixelType; - typedef double LabelPixelType; - - typedef itk::VariableLengthVector<InputPixelType> SampleType; - typedef itk::Statistics::ListSample<SampleType> ListSampleType; - typedef itk::FixedArray<LabelPixelType, 1> TrainingSampleType; - typedef itk::Statistics::ListSample<TrainingSampleType> TrainingListSampleType; - - typedef otb::SVMSampleListModelEstimator<ListSampleType, - TrainingListSampleType> EstimatorType; - - EstimatorType::Pointer estimator = EstimatorType::New(); - - std::cout << estimator << std::endl; - - return EXIT_SUCCESS; -} - -int otbSVMSampleListModelEstimatorTest(int argc, char* argv[]) -{ - if (argc != 4) - { - std::cerr << "Usage: " << argv[0] << " inputImage inputVectorData outputModelFileName" - << std::endl; - return EXIT_FAILURE; - } - - std::string imageFilename = argv[1]; - std::string vectorDataFilename = argv[2]; - std::string outputModelFileName= argv[3]; - int maxTrainingSize = 500; - int maxValidationSize = 500; - double validationTrainingProportion = 0.5; - - std::string classKey = "Class"; - - typedef double PixelType; - typedef otb::VectorImage<PixelType, 2> ImageType; - typedef otb::ImageFileReader<ImageType> ReaderType; - - ReaderType::Pointer reader = ReaderType::New(); - reader->SetFileName(imageFilename); - reader->UpdateOutputInformation(); - - typedef otb::VectorData<float, 2> VectorDataType; - typedef otb::VectorDataFileReader<VectorDataType> VectorDataReaderType; - - VectorDataReaderType::Pointer vectorReader = VectorDataReaderType::New(); - vectorReader->SetFileName(vectorDataFilename); - - typedef otb::ListSampleGenerator<ImageType, VectorDataType> ListSampleGeneratorType; - ListSampleGeneratorType::Pointer generator = ListSampleGeneratorType::New(); - generator->SetMaxTrainingSize(maxTrainingSize); - generator->SetMaxValidationSize(maxValidationSize); - generator->SetValidationTrainingProportion(validationTrainingProportion); - - generator->SetInput(reader->GetOutput()); - generator->SetInputVectorData(vectorReader->GetOutput()); - - typedef ListSampleGeneratorType::ListSampleType ListSampleType; - typedef ListSampleGeneratorType::ListLabelType TrainingListSampleType; - typedef otb::SVMSampleListModelEstimator<ListSampleType, TrainingListSampleType> EstimatorType; - - EstimatorType::Pointer estimator = EstimatorType::New(); - estimator->SetInputSampleList(generator->GetTrainingListSample()); - estimator->SetTrainingSampleList(generator->GetTrainingListLabel()); - - estimator->Update(); - estimator->GetModel()->SaveModel(outputModelFileName); - - // Print the ListSample generator - std::cout << generator << std::endl; - - - return EXIT_SUCCESS; -} diff --git a/Modules/Learning/Supervised/include/otbConfusionMatrixCalculator.h b/Modules/Learning/Supervised/include/otbConfusionMatrixCalculator.h index ed49b98bd7fa331cd62e9d35261cbdae808c4b53..465b0ae9a30a2024cb3384a2b9181fa8c51ad0ad 100644 --- a/Modules/Learning/Supervised/include/otbConfusionMatrixCalculator.h +++ b/Modules/Learning/Supervised/include/otbConfusionMatrixCalculator.h @@ -91,12 +91,6 @@ public: /** Type for the measurement */ typedef itk::VariableLengthVector<double> MeasurementType; - - /** - * \deprecated in OTB 3.16, please use void Compute(void) instead. - */ - itkLegacyMacro( virtual void Update() ); - /** Computes m_ConfusionMatrix and then the measurements over it. */ void Compute(void); diff --git a/Modules/Learning/Supervised/include/otbConfusionMatrixCalculator.txx b/Modules/Learning/Supervised/include/otbConfusionMatrixCalculator.txx index e4ef8e309c87eb0f9f99cd478cd1915613a381a5..f88c779b8662893006d0ef69a3826859cf12ac6c 100644 --- a/Modules/Learning/Supervised/include/otbConfusionMatrixCalculator.txx +++ b/Modules/Learning/Supervised/include/otbConfusionMatrixCalculator.txx @@ -48,21 +48,6 @@ ConfusionMatrixCalculator<TRefListLabel, TProdListLabel> m_ProducedLabels = ProdListLabelType::New(); } - -#if !defined(ITK_LEGACY_REMOVE) -template <class TRefListLabel, class TProdListLabel> -void -ConfusionMatrixCalculator<TRefListLabel, TProdListLabel> -::Update() -{ - itkWarningMacro("otb::ConfusionMatrixCalculator::Update() is DEPRECATED. " - "Use otb::ConfusionMatrixCalculator::Compute() instead."); - - this->Compute(); -} -#endif - - template <class TRefListLabel, class TProdListLabel> void ConfusionMatrixCalculator<TRefListLabel, TProdListLabel> diff --git a/Modules/Learning/SVMLearning/include/otbExhaustiveExponentialOptimizer.h b/Modules/Learning/Supervised/include/otbExhaustiveExponentialOptimizer.h similarity index 95% rename from Modules/Learning/SVMLearning/include/otbExhaustiveExponentialOptimizer.h rename to Modules/Learning/Supervised/include/otbExhaustiveExponentialOptimizer.h index 3e855204087745ffbef84ccdddeb6c283abcc4e8..cae5fb092d593407aa0855a1e62cb6a7b249d397 100644 --- a/Modules/Learning/SVMLearning/include/otbExhaustiveExponentialOptimizer.h +++ b/Modules/Learning/Supervised/include/otbExhaustiveExponentialOptimizer.h @@ -42,9 +42,9 @@ namespace otb * * \ingroup Numerics Optimizers * - * \ingroup OTBSVMLearning + * \ingroup OTBSupervised */ -class ITK_EXPORT ExhaustiveExponentialOptimizer : +class ITK_ABI_EXPORT ExhaustiveExponentialOptimizer : public itk::SingleValuedNonLinearOptimizer { public: @@ -59,7 +59,7 @@ public: itkNewMacro(Self); /** Run-time type information (and related methods). */ - itkTypeMacro(ExhaustiveExponentialOptimizer, SingleValuedNonLinearOptimizer); + itkTypeMacro(ExhaustiveExponentialOptimizer,itk::SingleValuedNonLinearOptimizer); void StartOptimization(void) ITK_OVERRIDE; diff --git a/Modules/Learning/SVMLearning/include/otbLabelMapSVMClassifier.h b/Modules/Learning/Supervised/include/otbLabelMapClassifier.h similarity index 74% rename from Modules/Learning/SVMLearning/include/otbLabelMapSVMClassifier.h rename to Modules/Learning/Supervised/include/otbLabelMapClassifier.h index 32198547cc5aac69def620423fcc65e6fc0798e1..75dc291f3df947dbe9a9ab6d45d4fca8ccd73470 100644 --- a/Modules/Learning/SVMLearning/include/otbLabelMapSVMClassifier.h +++ b/Modules/Learning/Supervised/include/otbLabelMapClassifier.h @@ -18,32 +18,32 @@ * limitations under the License. */ -#ifndef otbLabelMapSVMClassifier_h -#define otbLabelMapSVMClassifier_h +#ifndef otbLabelMapClassifier_h +#define otbLabelMapClassifier_h #include "itkInPlaceLabelMapFilter.h" -#include "otbSVMModel.h" +#include "otbMachineLearningModel.h" #include "itkListSample.h" #include "otbAttributesMapLabelObject.h" namespace otb { -/** \class LabelMapSVMClassifier +/** \class LabelMapClassifier * \brief Classify each LabelObject of the input LabelMap in place * * \sa otb::AttributesMapLabelObject * \sa otb::SVMModel * \sa itk::InPlaceLabelMapFilter * - * \ingroup OTBSVMLearning + * \ingroup OTBSupervised */ template<class TInputLabelMap> -class ITK_EXPORT LabelMapSVMClassifier : +class ITK_EXPORT LabelMapClassifier : public itk::InPlaceLabelMapFilter<TInputLabelMap> { public: /** Standard class typedefs. */ - typedef LabelMapSVMClassifier Self; + typedef LabelMapClassifier Self; typedef itk::InPlaceLabelMapFilter<TInputLabelMap> Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; @@ -56,27 +56,26 @@ public: typedef typename LabelObjectType::AttributesValueType AttributesValueType; typedef typename LabelObjectType::ClassLabelType ClassLabelType; - typedef std::vector<AttributesValueType> MeasurementVectorType; - - typedef Functor::AttributesMapMeasurementFunctor - <LabelObjectType, MeasurementVectorType> MeasurementFunctorType; /** ImageDimension constants */ itkStaticConstMacro(InputImageDimension, unsigned int, TInputLabelMap::ImageDimension); - /** Type definitions for the SVM Model. */ - typedef SVMModel<AttributesValueType, ClassLabelType> SVMModelType; - typedef typename SVMModelType::Pointer SVMModelPointer; + /** Type definitions for the learning model. */ + typedef MachineLearningModel<AttributesValueType, ClassLabelType> ModelType; + typedef typename ModelType::Pointer ModelPointer; + typedef typename ModelType::InputSampleType MeasurementVectorType; + typedef Functor::AttributesMapMeasurementFunctor + <LabelObjectType, MeasurementVectorType> MeasurementFunctorType; /** Standard New method. */ itkNewMacro(Self); /** Runtime information support. */ - itkTypeMacro(LabelMapSVMClassifier, + itkTypeMacro(LabelMapClassifier, itk::InPlaceLabelMapFilter); - itkSetObjectMacro(Model, SVMModelType); + itkSetObjectMacro(Model, ModelType); void SetMeasurementFunctor(const MeasurementFunctorType& functor) { @@ -89,8 +88,8 @@ public: } protected: - LabelMapSVMClassifier(); - ~LabelMapSVMClassifier() ITK_OVERRIDE {}; + LabelMapClassifier(); + ~LabelMapClassifier() ITK_OVERRIDE {}; void ThreadedProcessLabelObject( LabelObjectType * labelObject ) ITK_OVERRIDE; @@ -98,11 +97,11 @@ protected: private: - LabelMapSVMClassifier(const Self&); //purposely not implemented + LabelMapClassifier(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented - /** The SVM model used for classification */ - SVMModelPointer m_Model; + /** The learning model used for classification */ + ModelPointer m_Model; /** The functor used to build the measurement vector */ MeasurementFunctorType m_MeasurementFunctor; @@ -112,7 +111,7 @@ private: } // end namespace otb #ifndef OTB_MANUAL_INSTANTIATION -#include "otbLabelMapSVMClassifier.txx" +#include "otbLabelMapClassifier.txx" #endif #endif diff --git a/Modules/Learning/SVMLearning/include/otbLabelMapSVMClassifier.txx b/Modules/Learning/Supervised/include/otbLabelMapClassifier.txx similarity index 74% rename from Modules/Learning/SVMLearning/include/otbLabelMapSVMClassifier.txx rename to Modules/Learning/Supervised/include/otbLabelMapClassifier.txx index 0c1ad9561540497486c909130c8f6117aee87bd6..b7a6141b5a76f52085307c54a3ca4bff7ba33d9b 100644 --- a/Modules/Learning/SVMLearning/include/otbLabelMapSVMClassifier.txx +++ b/Modules/Learning/Supervised/include/otbLabelMapClassifier.txx @@ -18,27 +18,27 @@ * limitations under the License. */ -#ifndef otbLabelMapSVMClassifier_txx -#define otbLabelMapSVMClassifier_txx +#ifndef otbLabelMapClassifier_txx +#define otbLabelMapClassifier_txx -#include "otbLabelMapSVMClassifier.h" +#include "otbLabelMapClassifier.h" namespace otb { template <class TInputImage> -LabelMapSVMClassifier<TInputImage> -::LabelMapSVMClassifier() +LabelMapClassifier<TInputImage> +::LabelMapClassifier() { - // Force to single-threaded (SVMModel is not thread-safe) + // Force to single-threaded in case the learning model is not thread safe // This way, we benefit of the LabelMapFilter design and only need // to implement ThreadedProcessLabelObject - this->SetNumberOfThreads(1); + this->SetNumberOfThreads(1); // TODO : check if still needed } template<class TInputImage> void -LabelMapSVMClassifier<TInputImage> +LabelMapClassifier<TInputImage> ::ReleaseInputs( ) { // by pass itk::InPlaceLabelMapFilter::ReleaseInputs() implementation, @@ -48,10 +48,10 @@ LabelMapSVMClassifier<TInputImage> template<class TInputImage> void -LabelMapSVMClassifier<TInputImage> +LabelMapClassifier<TInputImage> ::ThreadedProcessLabelObject( LabelObjectType * labelObject ) { - ClassLabelType classLabel = m_Model->EvaluateLabel(m_MeasurementFunctor(labelObject)); + ClassLabelType classLabel = (m_Model->Predict(m_MeasurementFunctor(labelObject)))[0]; labelObject->SetClassLabel(classLabel); } diff --git a/Modules/Learning/Supervised/include/otbLibSVMMachineLearningModel.h b/Modules/Learning/Supervised/include/otbLibSVMMachineLearningModel.h index f61335ca894d5cc42d270c9bffc40f76a4e17679..a8baa08e58118980fff9deb9dd184e05d9ef2d0c 100644 --- a/Modules/Learning/Supervised/include/otbLibSVMMachineLearningModel.h +++ b/Modules/Learning/Supervised/include/otbLibSVMMachineLearningModel.h @@ -25,10 +25,7 @@ #include "itkFixedArray.h" #include "otbMachineLearningModel.h" -// SVM estimator -#include "otbSVMSampleListModelEstimator.h" -// Validation -#include "otbSVMClassifier.h" +#include "svm.h" namespace otb { @@ -51,12 +48,16 @@ public: typedef typename Superclass::TargetListSampleType TargetListSampleType; typedef typename Superclass::ConfidenceValueType ConfidenceValueType; - // LibSVM related typedefs - typedef otb::Functor::VariableLengthVectorToMeasurementVectorFunctor<InputSampleType> MeasurementVectorFunctorType; - typedef otb::SVMSampleListModelEstimator<InputListSampleType, TargetListSampleType, MeasurementVectorFunctorType> - SVMEstimatorType; - - typedef otb::SVMClassifier<InputSampleType, TargetValueType> ClassifierType; + /** enum to choose the way confidence is computed + * CM_INDEX : compute the difference between highest and second highest probability + * CM_PROBA : returns probabilities for all classes + * The given pointer needs to store 'nbClass' values + * This mode requires that ConfidenceValueType is double + * CM_HYPER : returns hyperplanes distances* + * The given pointer needs to store 'nbClass * (nbClass-1) / 2' values + * This mode requires that ConfidenceValueType is double + */ + typedef enum {CM_INDEX,CM_PROBA,CM_HYPER} ConfidenceMode; /** Run-time type information (and related methods). */ itkNewMacro(Self); @@ -80,41 +81,188 @@ public: bool CanWriteFile(const std::string &) ITK_OVERRIDE; //@} - //Setters/Getters to SVM model - otbGetObjectMemberMacro(SVMestimator, SVMType, int); - otbSetObjectMemberMacro(SVMestimator, SVMType, int); +#define otbSetSVMParameterMacro(name, alias, type) \ + void Set##name (const type _arg) \ + { \ + itkDebugMacro("setting " #name " to " << _arg); \ + if ( this->m_Parameters.alias != _arg ) \ + { \ + this->m_Parameters.alias = _arg; \ + this->Modified(); \ + } \ + } + + /** Set the SVM type to C_SVC, NU_SVC, ONE_CLASS, EPSILON_SVR, NU_SVR */ + otbSetSVMParameterMacro(SVMType, svm_type, int) - otbGetObjectMemberMacro(SVMestimator, KernelType, int); - otbSetObjectMemberMacro(SVMestimator, KernelType, int); + /** Get the SVM type (C_SVC, NU_SVC, ONE_CLASS, EPSILON_SVR, NU_SVR) */ + int GetSVMType(void) const + { + return m_Parameters.svm_type; + } - otbGetObjectMemberMacro(SVMestimator, C, double); - otbSetObjectMemberMacro(SVMestimator, C, double); + /** Set the kernel type to LINEAR, POLY, RBF, SIGMOID + linear: u'*v + polynomial: (gamma*u'*v + coef0)^degree + radial basis function: exp(-gamma*|u-v|^2) + sigmoid: tanh(gamma*u'*v + coef0)*/ + otbSetSVMParameterMacro(KernelType, kernel_type, int) - // TODO : we should harmonize this parameter name : ParameterOptimization -> ParametersOptimization - bool GetParameterOptimization() + /** Get the kernel type */ + int GetKernelType(void) const { - return this->m_SVMestimator->GetParametersOptimization(); + return m_Parameters.kernel_type; } - void SetParameterOptimization(bool value) + + /** Set the degree of the polynomial kernel */ + otbSetSVMParameterMacro(PolynomialKernelDegree,degree,int) + + /** Get the degree of the polynomial kernel */ + int GetPolynomialKernelDegree(void) const { - this->m_SVMestimator->SetParametersOptimization(value); - this->Modified(); + return m_Parameters.degree; + } + + /** Set the gamma parameter for poly/rbf/sigmoid kernels */ + otbSetSVMParameterMacro(KernelGamma,gamma,double) + + /** Get the gamma parameter for poly/rbf/sigmoid kernels */ + double GetKernelGamma(void) const + { + return m_Parameters.gamma; + } + + /** Set the coef0 parameter for poly/sigmoid kernels */ + otbSetSVMParameterMacro(KernelCoef0,coef0,double) + + /** Get the coef0 parameter for poly/sigmoid kernels */ + double GetKernelCoef0(void) const + { + return m_Parameters.coef0; + } + + /** Set the C parameter for the training for C_SVC, EPSILON_SVR and NU_SVR */ + otbSetSVMParameterMacro(C,C,double) + + /** Get the C parameter for the training for C_SVC, EPSILON_SVR and NU_SVR */ + double GetC(void) const + { + return m_Parameters.C; + } + + itkSetMacro(ParameterOptimization, bool); + itkGetMacro(ParameterOptimization, bool); + + /** Do probability estimates */ + void SetDoProbabilityEstimates(bool prob) + { + m_Parameters.probability = static_cast<int>(prob); } - otbGetObjectMemberMacro(SVMestimator, DoProbabilityEstimates, bool); - void SetDoProbabilityEstimates(bool value) + /** Get Do probability estimates boolean */ + bool GetDoProbabilityEstimates(void) const { - this->m_SVMestimator->DoProbabilityEstimates(value); + return static_cast<bool>(m_Parameters.probability); } - otbGetObjectMemberMacro(SVMestimator, Epsilon, double); - otbSetObjectMemberMacro(SVMestimator, Epsilon, double); + /** Test if the model has probabilities */ + bool HasProbabilities(void) const; + + /** Set the tolerance for the stopping criterion for the training*/ + otbSetSVMParameterMacro(Epsilon,eps,double) + + /** Get the tolerance for the stopping criterion for the training*/ + double GetEpsilon(void) const + { + return m_Parameters.eps; + } - otbGetObjectMemberMacro(SVMestimator, P, double); - otbSetObjectMemberMacro(SVMestimator, P, double); + /** Set the value of p for EPSILON_SVR */ + otbSetSVMParameterMacro(P,p,double) - otbGetObjectMemberMacro(SVMestimator, Nu, double); - otbSetObjectMemberMacro(SVMestimator, Nu, double); + /** Get the value of p for EPSILON_SVR */ + double GetP(void) const + { + return m_Parameters.p; + } + + /** Set the Nu parameter for the training */ + otbSetSVMParameterMacro(Nu,nu,double) + + /** Set the Nu parameter for the training */ + double GetNu(void) const + { + return m_Parameters.nu; + } + +#undef otbSetSVMParameterMacro + + /** Use the shrinking heuristics for the training */ + void DoShrinking(bool s) + { + m_Parameters.shrinking = static_cast<int>(s); + this->Modified(); + } + + /** Get Use the shrinking heuristics for the training boolea */ + bool GetDoShrinking(void) const + { + return static_cast<bool>(m_Parameters.shrinking); + } + + /** Set the cache size in MB for the training */ + void SetCacheSize(int cSize) + { + m_Parameters.cache_size = static_cast<double>(cSize); + this->Modified(); + } + + /** Get the cache size in MB for the training */ + int GetCacheSize(void) const + { + return static_cast<int>(m_Parameters.cache_size); + } + + itkSetMacro(CVFolders, unsigned int); + itkGetMacro(CVFolders, unsigned int); + + itkGetMacro(InitialCrossValidationAccuracy, double); + + itkGetMacro(FinalCrossValidationAccuracy, double); + + itkSetMacro(CoarseOptimizationNumberOfSteps, unsigned int); + itkGetMacro(CoarseOptimizationNumberOfSteps, unsigned int); + + itkSetMacro(FineOptimizationNumberOfSteps, unsigned int); + itkGetMacro(FineOptimizationNumberOfSteps, unsigned int); + + void SetConfidenceMode(unsigned int mode) + { + if (m_ConfidenceMode != static_cast<ConfidenceMode>(mode) ) + { + m_ConfidenceMode = static_cast<ConfidenceMode>(mode); + this->m_ConfidenceIndex = this->HasProbabilities(); + this->Modified(); + } + } + itkGetMacro(ConfidenceMode, unsigned int); + + unsigned int GetNumberOfKernelParameters(); + + double CrossValidation(void); + + /** Return number of support vectors */ + unsigned int GetNumberOfSupportVectors(void) const + { + if (m_Model) return m_Model->l; + return 0; + } + + unsigned int GetNumberOfClasses(void) const + { + if (m_Model) return m_Model->nr_class; + return 0; + } protected: /** Constructor */ @@ -133,7 +281,49 @@ private: LibSVMMachineLearningModel(const Self &); //purposely not implemented void operator =(const Self&); //purposely not implemented - typename SVMEstimatorType::Pointer m_SVMestimator; + void BuildProblem(void); + + void ConsistencyCheck(void); + + void DeleteProblem(void); + + void DeleteModel(void); + + void OptimizeParameters(void); + + /** Container to hold the SVM model itself */ + struct svm_model* m_Model; + + /** Structure that stores training vectors */ + struct svm_problem m_Problem; + + /** Container of the SVM parameters */ + struct svm_parameter m_Parameters; + + /** Do parameters optimization, default : false */ + bool m_ParameterOptimization; + + /** Number of Cross Validation folders*/ + unsigned int m_CVFolders; + + /** Initial cross validation accuracy */ + double m_InitialCrossValidationAccuracy; + + /** Final cross validationa accuracy */ + double m_FinalCrossValidationAccuracy; + + /** Number of steps for the coarse search */ + unsigned int m_CoarseOptimizationNumberOfSteps; + + /** Number of steps for the fine search */ + unsigned int m_FineOptimizationNumberOfSteps; + + /** Output mode for confidence index (see enum ) */ + ConfidenceMode m_ConfidenceMode; + + /** Temporary array to store cross-validation results */ + std::vector<double> m_TmpTarget; + }; } // end namespace otb diff --git a/Modules/Learning/Supervised/include/otbLibSVMMachineLearningModel.txx b/Modules/Learning/Supervised/include/otbLibSVMMachineLearningModel.txx index b2e14bcad6ad74218eb9a85849fd2231a95028de..2b14f6dca92ebe4c97d4305b16afe744e5635944 100644 --- a/Modules/Learning/Supervised/include/otbLibSVMMachineLearningModel.txx +++ b/Modules/Learning/Supervised/include/otbLibSVMMachineLearningModel.txx @@ -23,6 +23,10 @@ #include <fstream> #include "otbLibSVMMachineLearningModel.h" +#include "otbSVMCrossValidationCostFunction.h" +#include "otbExhaustiveExponentialOptimizer.h" +#include "otbMacro.h" +#include "otbUtils.h" namespace otb { @@ -31,22 +35,48 @@ template <class TInputValue, class TOutputValue> LibSVMMachineLearningModel<TInputValue,TOutputValue> ::LibSVMMachineLearningModel() { - 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->SetSVMType(C_SVC); + this->SetKernelType(LINEAR); + this->SetPolynomialKernelDegree(3); + this->SetKernelGamma(1.); // 1/k + this->SetKernelCoef0(1.); + this->SetNu(0.5); + this->SetC(1.0); + this->SetEpsilon(1e-3); + this->SetP(0.1); + this->SetDoProbabilityEstimates(false); + this->DoShrinking(true); + this->SetCacheSize(40); // MB + this->m_ParameterOptimization = false; this->m_IsRegressionSupported = true; -} + this->SetCVFolders(5); + this->m_InitialCrossValidationAccuracy = 0.; + this->m_FinalCrossValidationAccuracy = 0.; + this->m_CoarseOptimizationNumberOfSteps = 5; + this->m_FineOptimizationNumberOfSteps = 5; + this->m_ConfidenceMode = + LibSVMMachineLearningModel<TInputValue,TOutputValue>::CM_INDEX; + + this->m_Parameters.nr_weight = 0; + this->m_Parameters.weight_label = ITK_NULLPTR; + this->m_Parameters.weight = ITK_NULLPTR; + + this->m_Model = ITK_NULLPTR; + this->m_Problem.l = 0; + this->m_Problem.y = ITK_NULLPTR; + this->m_Problem.x = ITK_NULLPTR; +#ifndef OTB_SHOW_ALL_MSG_DEBUG + svm_set_print_string_function(&otb::Utils::PrintNothing); +#endif +} template <class TInputValue, class TOutputValue> LibSVMMachineLearningModel<TInputValue,TOutputValue> ::~LibSVMMachineLearningModel() { - //delete m_SVMModel; + this->DeleteModel(); + this->DeleteProblem(); } /** Train the machine learning model */ @@ -55,19 +85,22 @@ void LibSVMMachineLearningModel<TInputValue,TOutputValue> ::Train() { - // Set up SVM's parameters - // CvSVMParams params; - // params.svm_type = m_SVMType; - // params.kernel_type = m_KernelType; - // params.term_crit = cvTermCriteria(m_TermCriteriaType, m_MaxIter, m_Epsilon); + this->DeleteProblem(); + this->DeleteModel(); - // // Train the SVM - m_SVMestimator->SetInputSampleList(this->GetInputListSample()); - m_SVMestimator->SetTrainingSampleList(this->GetTargetListSample()); + // Build problem + this->BuildProblem(); - m_SVMestimator->Update(); + // Check consistency + this->ConsistencyCheck(); - this->m_ConfidenceIndex = this->GetDoProbabilityEstimates(); + // Compute accuracy and eventually optimize parameters + this->OptimizeParameters(); + + // train the model + m_Model = svm_train(&m_Problem, &m_Parameters); + + this->m_ConfidenceIndex = this->HasProbabilities(); } template <class TInputValue, class TOutputValue> @@ -77,10 +110,25 @@ LibSVMMachineLearningModel<TInputValue,TOutputValue> ::DoPredict(const InputSampleType & input, ConfidenceValueType *quality) const { TargetSampleType target; + target.Fill(0); + + // Get type and number of classes + int svm_type = svm_get_svm_type(m_Model); + + // Allocate nodes (/TODO if performances problems are related to too + // many allocations, a cache approach can be set) + struct svm_node * x = new struct svm_node[input.Size() + 1]; - MeasurementVectorFunctorType mfunctor; + // Fill the node + for (unsigned int i = 0 ; i < input.Size() ; i++) + { + x[i].index = i + 1; + x[i].value = input[i]; + } - target = m_SVMestimator->GetModel()->EvaluateLabel(mfunctor(input)); + // terminate node + x[input.Size()].index = -1; + x[input.Size()].value = 0; if (quality != ITK_NULLPTR) { @@ -88,24 +136,70 @@ LibSVMMachineLearningModel<TInputValue,TOutputValue> { itkExceptionMacro("Confidence index not available for this classifier !"); } - typename SVMEstimatorType::ModelType::ProbabilitiesVectorType probaVector = - m_SVMestimator->GetModel()->EvaluateProbabilities(mfunctor(input)); - double maxProb = 0.0; - double secProb = 0.0; - for (unsigned int i=0 ; i<probaVector.Size() ; ++i) + if (this->m_ConfidenceMode == CM_INDEX) { - if (maxProb < probaVector[i]) + if (svm_type == C_SVC || svm_type == NU_SVC) { - secProb = maxProb; - maxProb = probaVector[i]; + // Eventually allocate space for probabilities + unsigned int nr_class = svm_get_nr_class(m_Model); + double *prob_estimates = new double[nr_class]; + // predict + target[0] = static_cast<TargetValueType>(svm_predict_probability(m_Model, x, prob_estimates)); + double maxProb = 0.0; + double secProb = 0.0; + for (unsigned int i=0 ; i< nr_class ; ++i) + { + if (maxProb < prob_estimates[i]) + { + secProb = maxProb; + maxProb = prob_estimates[i]; + } + else if (secProb < prob_estimates[i]) + { + secProb = prob_estimates[i]; + } + } + (*quality) = static_cast<ConfidenceValueType>(maxProb - secProb); + + delete[] prob_estimates; } - else if (secProb < probaVector[i]) + else { - secProb = probaVector[i]; + target[0] = static_cast<TargetValueType>(svm_predict(m_Model, x)); + // Prob. model for test data: target value = predicted value + z + // z: Laplace distribution e^(-|z|/sigma)/(2sigma) + // sigma is output as confidence index + (*quality) = svm_get_svr_probability(m_Model); } } - (*quality) = static_cast<ConfidenceValueType>(maxProb - secProb); + else if (this->m_ConfidenceMode == CM_PROBA) + { + target[0] = static_cast<TargetValueType>(svm_predict_probability(m_Model, x, quality)); + } + else if (this->m_ConfidenceMode == CM_HYPER) + { + target[0] = static_cast<TargetValueType>(svm_predict_values(m_Model, x, quality)); + } } + else + { + // default case : if the model has probabilities, we call svm_predict_probabilities() + // which gives different results than svm_predict() + if (svm_check_probability_model(m_Model)) + { + unsigned int nr_class = svm_get_nr_class(m_Model); + double *prob_estimates = new double[nr_class]; + target[0] = static_cast<TargetValueType>(svm_predict_probability(m_Model, x, prob_estimates)); + delete[] prob_estimates; + } + else + { + target[0] = static_cast<TargetValueType>(svm_predict(m_Model, x)); + } + } + + // Free allocated memory + delete[] x; return target; } @@ -115,7 +209,10 @@ void LibSVMMachineLearningModel<TInputValue,TOutputValue> ::Save(const std::string & filename, const std::string & itkNotUsed(name)) { - m_SVMestimator->GetModel()->SaveModel(filename.c_str()); + if (svm_save_model(filename.c_str(), m_Model) != 0) + { + itkExceptionMacro(<< "Problem while saving SVM model " << filename); + } } template <class TInputValue, class TOutputValue> @@ -123,9 +220,15 @@ void LibSVMMachineLearningModel<TInputValue,TOutputValue> ::Load(const std::string & filename, const std::string & itkNotUsed(name)) { - m_SVMestimator->GetModel()->LoadModel(filename.c_str()); + this->DeleteModel(); + m_Model = svm_load_model(filename.c_str()); + if (m_Model == ITK_NULLPTR) + { + itkExceptionMacro(<< "Problem while loading SVM model " << filename); + } + m_Parameters = m_Model->param; - this->m_ConfidenceIndex = m_SVMestimator->GetModel()->HasProbabilities(); + this->m_ConfidenceIndex = this->HasProbabilities(); } template <class TInputValue, class TOutputValue> @@ -174,6 +277,276 @@ LibSVMMachineLearningModel<TInputValue,TOutputValue> Superclass::PrintSelf(os,indent); } +template <class TInputValue, class TOutputValue> +bool +LibSVMMachineLearningModel<TInputValue,TOutputValue> +::HasProbabilities(void) const +{ + bool modelHasProba = static_cast<bool>(svm_check_probability_model(m_Model)); + int type = svm_get_svm_type(m_Model); + int cmMode = this->m_ConfidenceMode; + bool ret = false; + if (type == EPSILON_SVR || type == NU_SVR) + { + ret = (modelHasProba && cmMode == CM_INDEX); + } + else if (type == C_SVC || type == NU_SVC) + { + ret = (modelHasProba && (cmMode == CM_INDEX || cmMode == CM_PROBA)) || + (cmMode == CM_HYPER); + } + return ret; +} + +template <class TInputValue, class TOutputValue> +void +LibSVMMachineLearningModel<TInputValue,TOutputValue> +::BuildProblem() +{ + // Get number of samples + typename InputListSampleType::Pointer samples = this->GetInputListSample(); + typename TargetListSampleType::Pointer target = this->GetTargetListSample(); + int probl = samples->Size(); + + if (probl < 1) + { + itkExceptionMacro(<< "No samples, can not build SVM problem."); + } + otbMsgDebugMacro(<< "Building problem ..."); + + // Get the size of the samples + long int elements = samples->GetMeasurementVectorSize(); + + // Allocate the problem + m_Problem.l = probl; + m_Problem.y = new double[probl]; + m_Problem.x = new struct svm_node*[probl]; + for (int i = 0; i < probl; ++i) + { + m_Problem.x[i] = new struct svm_node[elements+1]; + } + + // Iterate on the samples + typename InputListSampleType::ConstIterator sIt = samples->Begin(); + typename TargetListSampleType::ConstIterator tIt = target->Begin(); + int sampleIndex = 0; + + while (sIt != samples->End() && tIt != target->End()) + { + // Set the label + m_Problem.y[sampleIndex] = tIt.GetMeasurementVector()[0]; + const InputSampleType &sample = sIt.GetMeasurementVector(); + for (int k = 0 ; k < elements ; ++k) + { + m_Problem.x[sampleIndex][k].index = k + 1; + m_Problem.x[sampleIndex][k].value = sample[k]; + } + // terminate node + m_Problem.x[sampleIndex][elements].index = -1; + m_Problem.x[sampleIndex][elements].value = 0; + + ++sampleIndex; + ++sIt; + ++tIt; + } + + // Compute the kernel gamma from number of elements if necessary + if (this->GetKernelGamma() == 0) + { + this->SetKernelGamma(1.0 / static_cast<double>(elements)); + } + + // allocate buffer for cross validation + m_TmpTarget.resize(m_Problem.l); +} + +template <class TInputValue, class TOutputValue> +void +LibSVMMachineLearningModel<TInputValue,TOutputValue> +::ConsistencyCheck() +{ + if (this->GetSVMType() == ONE_CLASS && this->GetDoProbabilityEstimates()) + { + otbMsgDebugMacro(<< "Disabling SVM probability estimates for ONE_CLASS SVM type."); + this->SetDoProbabilityEstimates(false); + } + + const char* error_msg = svm_check_parameter(&m_Problem, &m_Parameters); + + if (error_msg) + { + std::string err(error_msg); + itkExceptionMacro("SVM parameter check failed : " << err); + } +} + +template <class TInputValue, class TOutputValue> +void +LibSVMMachineLearningModel<TInputValue,TOutputValue> +::DeleteProblem() +{ + if (m_Problem.y) + { + delete[] m_Problem.y; + m_Problem.y = ITK_NULLPTR; + } + if (m_Problem.x) + { + for (int i = 0; i < m_Problem.l; ++i) + { + if (m_Problem.x[i]) + { + delete[] m_Problem.x[i]; + } + } + delete[] m_Problem.x; + m_Problem.x = ITK_NULLPTR; + } + m_Problem.l = 0; +} + +template <class TInputValue, class TOutputValue> +void +LibSVMMachineLearningModel<TInputValue,TOutputValue> +::DeleteModel(void) +{ + if(m_Model) + { + svm_free_and_destroy_model(&m_Model); + } + m_Model = ITK_NULLPTR; +} + +template <class TInputValue, class TOutputValue> +unsigned int +LibSVMMachineLearningModel<TInputValue,TOutputValue> +::GetNumberOfKernelParameters() +{ + unsigned int nb = 1; + switch(this->GetKernelType()) + { + case LINEAR: + // C + nb = 1; + break; + case POLY: + // C, gamma and coef0 + nb = 3; + break; + case RBF: + // C and gamma + nb = 2; + break; + case SIGMOID: + // C, gamma and coef0 + nb = 3; + break; + default: + // C + nb = 1; + break; + } + return nb; +} + +template <class TInputValue, class TOutputValue> +double +LibSVMMachineLearningModel<TInputValue,TOutputValue> +::CrossValidation(void) +{ + double accuracy = 0.0; + // Get the length of the problem + unsigned int length = m_Problem.l; + if (length == 0 || m_TmpTarget.size() < length ) + return accuracy; + + // Do cross validation + svm_cross_validation(&m_Problem, &m_Parameters, m_CVFolders, &m_TmpTarget[0]); + + // Evaluate accuracy + double total_correct = 0.; + for (unsigned int i = 0; i < length; ++i) + { + if (m_TmpTarget[i] == m_Problem.y[i]) + { + ++total_correct; + } + } + accuracy = total_correct / length; + + // return accuracy value + return accuracy; +} + +template <class TInputValue, class TOutputValue> +void +LibSVMMachineLearningModel<TInputValue,TOutputValue> +::OptimizeParameters() +{ + typedef SVMCrossValidationCostFunction<LibSVMMachineLearningModel<TInputValue,TOutputValue> > CrossValidationFunctionType; + typename CrossValidationFunctionType::Pointer crossValidationFunction = CrossValidationFunctionType::New(); + crossValidationFunction->SetModel(this); + + typename CrossValidationFunctionType::ParametersType initialParameters, coarseBestParameters, fineBestParameters; + + unsigned int nbParams = this->GetNumberOfKernelParameters(); + initialParameters.SetSize(nbParams); + initialParameters[0] = this->GetC(); + if (nbParams > 1) initialParameters[1] = this->GetKernelGamma(); + if (nbParams > 2) initialParameters[2] = this->GetKernelCoef0(); + + m_InitialCrossValidationAccuracy = crossValidationFunction->GetValue(initialParameters); + m_FinalCrossValidationAccuracy = m_InitialCrossValidationAccuracy; + + otbMsgDebugMacro(<< "Initial accuracy : " << m_InitialCrossValidationAccuracy + << ", Parameters Optimization" << m_ParameterOptimization); + + if (m_ParameterOptimization) + { + otbMsgDebugMacro(<< "Model parameters optimization"); + typename ExhaustiveExponentialOptimizer::Pointer coarseOptimizer = ExhaustiveExponentialOptimizer::New(); + typename ExhaustiveExponentialOptimizer::StepsType coarseNbSteps(initialParameters.Size()); + coarseNbSteps.Fill(m_CoarseOptimizationNumberOfSteps); + + coarseOptimizer->SetNumberOfSteps(coarseNbSteps); + coarseOptimizer->SetCostFunction(crossValidationFunction); + coarseOptimizer->SetInitialPosition(initialParameters); + coarseOptimizer->StartOptimization(); + + coarseBestParameters = coarseOptimizer->GetMaximumMetricValuePosition(); + + otbMsgDevMacro( << "Coarse minimum accuracy: " << coarseOptimizer->GetMinimumMetricValue() << " " << + coarseOptimizer->GetMinimumMetricValuePosition() ); + otbMsgDevMacro( << "Coarse maximum accuracy: " << coarseOptimizer->GetMaximumMetricValue() << " " << + coarseOptimizer->GetMaximumMetricValuePosition() ); + + typename ExhaustiveExponentialOptimizer::Pointer fineOptimizer = ExhaustiveExponentialOptimizer::New(); + typename ExhaustiveExponentialOptimizer::StepsType fineNbSteps(initialParameters.Size()); + fineNbSteps.Fill(m_FineOptimizationNumberOfSteps); + + double stepLength = 1. / static_cast<double>(m_FineOptimizationNumberOfSteps); + + fineOptimizer->SetNumberOfSteps(fineNbSteps); + fineOptimizer->SetStepLength(stepLength); + fineOptimizer->SetCostFunction(crossValidationFunction); + fineOptimizer->SetInitialPosition(coarseBestParameters); + fineOptimizer->StartOptimization(); + + otbMsgDevMacro(<< "Fine minimum accuracy: " << fineOptimizer->GetMinimumMetricValue() << " " << + fineOptimizer->GetMinimumMetricValuePosition() ); + otbMsgDevMacro(<< "Fine maximum accuracy: " << fineOptimizer->GetMaximumMetricValue() << " " << + fineOptimizer->GetMaximumMetricValuePosition() ); + + fineBestParameters = fineOptimizer->GetMaximumMetricValuePosition(); + + m_FinalCrossValidationAccuracy = fineOptimizer->GetMaximumMetricValue(); + + this->SetC(fineBestParameters[0]); + if (nbParams > 1) this->SetKernelGamma(fineBestParameters[1]); + if (nbParams > 2) this->SetKernelCoef0(fineBestParameters[2]); + } +} + } //end namespace otb #endif diff --git a/Modules/Learning/SVMLearning/include/otbSVMCrossValidationCostFunction.h b/Modules/Learning/Supervised/include/otbSVMCrossValidationCostFunction.h similarity index 89% rename from Modules/Learning/SVMLearning/include/otbSVMCrossValidationCostFunction.h rename to Modules/Learning/Supervised/include/otbSVMCrossValidationCostFunction.h index 8c6f12cbe3046bc1cee74b0acea996f4318b0bdd..ceb76a148636d70d4dd3d0b3b836de2c6cb36d87 100644 --- a/Modules/Learning/SVMLearning/include/otbSVMCrossValidationCostFunction.h +++ b/Modules/Learning/Supervised/include/otbSVMCrossValidationCostFunction.h @@ -21,7 +21,6 @@ #ifndef otbSVMCrossValidationCostFunction_h #define otbSVMCrossValidationCostFunction_h -#include "otbSVMModel.h" #include "itkSingleValuedCostFunction.h" namespace otb @@ -48,7 +47,7 @@ namespace otb * * \ingroup ClassificationFilters * - * \ingroup OTBSVMLearning + * \ingroup OTBSupervised */ template <class TModel> class ITK_EXPORT SVMCrossValidationCostFunction @@ -78,10 +77,6 @@ public: itkSetObjectMacro(Model, SVMModelType); itkGetObjectMacro(Model, SVMModelType); - /** Set/Get the number of cross validation folders */ - itkSetMacro(NumberOfCrossValidationFolders, unsigned int); - itkGetMacro(NumberOfCrossValidationFolders, unsigned int); - /** Set/Get the derivative step */ itkSetMacro(DerivativeStep, ParametersValueType); itkGetMacro(DerivativeStep, ParametersValueType); @@ -103,7 +98,7 @@ protected: /** Update svm parameters struct according to the input parameters */ - virtual void UpdateParameters(struct svm_parameter& svm_parameters, const ParametersType& parameters) const; + void UpdateParameters(const ParametersType& parameters) const; private: SVMCrossValidationCostFunction(const Self &); //purposely not implemented @@ -112,9 +107,6 @@ private: /**Pointer to the SVM model to optimize */ SVMModelPointer m_Model; - /** Number of cross validation folders */ - unsigned int m_NumberOfCrossValidationFolders; - /** Step used to compute the derivatives */ ParametersValueType m_DerivativeStep; diff --git a/Modules/Learning/SVMLearning/include/otbSVMCrossValidationCostFunction.txx b/Modules/Learning/Supervised/include/otbSVMCrossValidationCostFunction.txx similarity index 66% rename from Modules/Learning/SVMLearning/include/otbSVMCrossValidationCostFunction.txx rename to Modules/Learning/Supervised/include/otbSVMCrossValidationCostFunction.txx index c96dc9cecd64cd9fa618c2da045c42cc8bba68c9..25da162a45435a95a46cd2ffe1bc6972c812bb16 100644 --- a/Modules/Learning/SVMLearning/include/otbSVMCrossValidationCostFunction.txx +++ b/Modules/Learning/Supervised/include/otbSVMCrossValidationCostFunction.txx @@ -22,12 +22,13 @@ #define otbSVMCrossValidationCostFunction_txx #include "otbSVMCrossValidationCostFunction.h" +#include "otbMacro.h" namespace otb { template<class TModel> SVMCrossValidationCostFunction<TModel> -::SVMCrossValidationCostFunction() : m_Model(), m_NumberOfCrossValidationFolders(10), m_DerivativeStep(0.001) +::SVMCrossValidationCostFunction() : m_Model(), m_DerivativeStep(0.001) {} template<class TModel> SVMCrossValidationCostFunction<TModel> @@ -52,9 +53,9 @@ SVMCrossValidationCostFunction<TModel> } // Updates vm_parameters according to current parameters - this->UpdateParameters(m_Model->GetParameters(), parameters); + this->UpdateParameters(parameters); - return m_Model->CrossValidation(m_NumberOfCrossValidationFolders); + return m_Model->CrossValidation(); } template<class TModel> @@ -95,67 +96,18 @@ SVMCrossValidationCostFunction<TModel> { itkExceptionMacro(<< "Model is null, can not evaluate number of parameters."); } - - switch (m_Model->GetKernelType()) - { - case LINEAR: - // C - return 1; - - case POLY: - // C, gamma and coef0 - return 3; - - case RBF: - // C and gamma - return 2; - - case SIGMOID: - // C, gamma and coef0 - return 3; - - default: - // C - return 1; - } + return m_Model->GetNumberOfKernelParameters(); } template<class TModel> void SVMCrossValidationCostFunction<TModel> -::UpdateParameters(struct svm_parameter& svm_parameters, const ParametersType& parameters) const +::UpdateParameters(const ParametersType& parameters) const { - switch (m_Model->GetKernelType()) - { - case LINEAR: - // C - svm_parameters.C = parameters[0]; - break; - - case POLY: - // C, gamma and coef0 - svm_parameters.C = parameters[0]; - svm_parameters.gamma = parameters[1]; - svm_parameters.coef0 = parameters[2]; - break; - - case RBF: - // C and gamma - svm_parameters.C = parameters[0]; - svm_parameters.gamma = parameters[1]; - break; - - case SIGMOID: - // C, gamma and coef0 - svm_parameters.C = parameters[0]; - svm_parameters.gamma = parameters[1]; - svm_parameters.coef0 = parameters[2]; - break; - - default: - svm_parameters.C = parameters[0]; - break; - } + unsigned int nbParams = m_Model->GetNumberOfKernelParameters(); + m_Model->SetC(parameters[0]); + if (nbParams > 1) m_Model->SetKernelGamma(parameters[1]); + if (nbParams > 2) m_Model->SetKernelCoef0(parameters[2]); } } // namespace otb diff --git a/Modules/Learning/SVMLearning/include/otbSVMMarginSampler.h b/Modules/Learning/Supervised/include/otbSVMMarginSampler.h similarity index 94% rename from Modules/Learning/SVMLearning/include/otbSVMMarginSampler.h rename to Modules/Learning/Supervised/include/otbSVMMarginSampler.h index 31765e033ae14e42676685aac24c74425fef32e4..c6a3ae1daedefaeb20b5701150675f2c04a98ae4 100644 --- a/Modules/Learning/SVMLearning/include/otbSVMMarginSampler.h +++ b/Modules/Learning/Supervised/include/otbSVMMarginSampler.h @@ -31,7 +31,7 @@ namespace otb * \brief Implement one iteration of active learning by margin * \ingroup ActiveLearningFilters * - * \ingroup OTBSVMLearning + * \ingroup OTBSupervised */ template< class TSample, class TModel > @@ -69,7 +69,6 @@ public: /** Type definitions for the SVM Model. */ typedef TModel SVMModelType; typedef typename SVMModelType::Pointer SVMModelPointer; - typedef typename SVMModelType::DistancesVectorType DistancesVectorType; itkSetMacro(NumberOfCandidates, unsigned int); itkGetMacro(NumberOfCandidates, unsigned int); @@ -95,8 +94,6 @@ protected: virtual void DoMarginSampling(); private: - /** Output pointer (MembershipSample) */ - //typename OutputType::Pointer m_Output; SVMModelPointer m_Model; diff --git a/Modules/Learning/SVMLearning/include/otbSVMMarginSampler.txx b/Modules/Learning/Supervised/include/otbSVMMarginSampler.txx similarity index 89% rename from Modules/Learning/SVMLearning/include/otbSVMMarginSampler.txx rename to Modules/Learning/Supervised/include/otbSVMMarginSampler.txx index 08aaf32104e61986c660932fd49cf86d42886c51..b5ca257fadec2c14c4d69aa5078005a3ddf71b81 100644 --- a/Modules/Learning/SVMLearning/include/otbSVMMarginSampler.txx +++ b/Modules/Learning/Supervised/include/otbSVMMarginSampler.txx @@ -78,28 +78,32 @@ SVMMarginSampler< TSample, TModel > typename OutputType::ConstIterator endO = output->End(); typename TSample::MeasurementVectorType measurements; + m_Model->SetConfidenceMode(TModel::CM_HYPER); int numberOfComponentsPerSample = iter.GetMeasurementVector().Size(); + int nbClass = static_cast<int>(m_Model->GetNumberOfClasses()); + std::vector<double> hdistances(nbClass * (nbClass - 1) / 2); + otbMsgDevMacro( << "Starting iterations " ); while (iter != end && iterO != endO) { int i = 0; - typename SVMModelType::MeasurementType modelMeasurement; + typename SVMModelType::InputSampleType modelMeasurement(numberOfComponentsPerSample); measurements = iter.GetMeasurementVector(); // otbMsgDevMacro( << "Loop on components " << svm_type ); for (i=0; i<numberOfComponentsPerSample; ++i) { - modelMeasurement.push_back(measurements[i]); + modelMeasurement[i] = measurements[i]; } // Get distances to the hyperplanes - DistancesVectorType hdistances = m_Model->EvaluateHyperplanesDistances(modelMeasurement); + m_Model->Predict(modelMeasurement, &(hdistances[0])); double minDistance = vcl_abs(hdistances[0]); // Compute th min distances - for(unsigned int j = 1; j<hdistances.Size(); ++j) + for(unsigned int j = 1; j<hdistances.size(); ++j) { if(vcl_abs(hdistances[j])<minDistance) { @@ -129,8 +133,6 @@ SVMMarginSampler< TSample, TModel > m_MarginSamples.push_back(idDistVector[i].first); } - // m_Output->AddInstance(static_cast<unsigned int>(classLabel), iterO.GetInstanceIdentifier()); - } } // end of namespace otb diff --git a/Modules/Learning/Supervised/otb-module.cmake b/Modules/Learning/Supervised/otb-module.cmake index 2c7c4ae51189889628694c0269c7a469a6d3205f..879254c83cd3111ecf2bca0c4801c5bb93b8d6c4 100644 --- a/Modules/Learning/Supervised/otb-module.cmake +++ b/Modules/Learning/Supervised/otb-module.cmake @@ -29,12 +29,13 @@ ENABLE_SHARED OTBCommon OTBITK OTBImageBase + OTBLabelMap OTBLearningBase OTBUnsupervised OPTIONAL_DEPENDS OTBOpenCV - OTBSVMLearning + OTBLibSVM OTBShark TEST_DEPENDS diff --git a/Modules/Learning/Supervised/src/CMakeLists.txt b/Modules/Learning/Supervised/src/CMakeLists.txt index 0f9a686cef46df288e6b21184746f8fd261af972..7a3c77b3a7e2992216d16f444178abb697424dc0 100644 --- a/Modules/Learning/Supervised/src/CMakeLists.txt +++ b/Modules/Learning/Supervised/src/CMakeLists.txt @@ -20,6 +20,7 @@ set(OTBSupervised_SRC otbMachineLearningModelFactoryBase.cxx + otbExhaustiveExponentialOptimizer.cxx ) if(OTB_USE_OPENCV) @@ -29,7 +30,7 @@ endif() add_library(OTBSupervised ${OTBSupervised_SRC}) target_link_libraries(OTBSupervised ${OTBCommon_LIBRARIES} - ${OTBSVMLearning_LIBRARIES} + ${OTBLibSVM_LIBRARIES} ${OTBOpenCV_LIBRARIES} ${OTBShark_LIBRARIES} ) diff --git a/Modules/Learning/SVMLearning/src/otbExhaustiveExponentialOptimizer.cxx b/Modules/Learning/Supervised/src/otbExhaustiveExponentialOptimizer.cxx similarity index 100% rename from Modules/Learning/SVMLearning/src/otbExhaustiveExponentialOptimizer.cxx rename to Modules/Learning/Supervised/src/otbExhaustiveExponentialOptimizer.cxx diff --git a/Modules/Learning/Supervised/test/0000209-SVMValidationLinearlySeparableProbEstimation.cxx b/Modules/Learning/Supervised/test/0000209-SVMValidationLinearlySeparableProbEstimation.cxx index f349f7e1f850384f88d573a8907ecba8ced75853..5394d793ed7b82d62cb7c3d7d231a5053c724c53 100644 --- a/Modules/Learning/Supervised/test/0000209-SVMValidationLinearlySeparableProbEstimation.cxx +++ b/Modules/Learning/Supervised/test/0000209-SVMValidationLinearlySeparableProbEstimation.cxx @@ -165,7 +165,7 @@ int main(int argc, char* argv[]) estimator->SetTrainingSampleList(trainingLabels); estimator->SetKernelType(kernel); - estimator->DoProbabilityEstimates(probEstimate); + estimator->SetDoProbabilityEstimates(probEstimate); // estimator->SetParametersOptimization(true); estimator->Update(); diff --git a/Modules/Learning/Supervised/test/CMakeLists.txt b/Modules/Learning/Supervised/test/CMakeLists.txt index edeb96d0cde66eae5456db2cb539c0bde665c9fb..858f9f84ea9592a96da94b17d6c9cf4074fc6994 100644 --- a/Modules/Learning/Supervised/test/CMakeLists.txt +++ b/Modules/Learning/Supervised/test/CMakeLists.txt @@ -27,6 +27,11 @@ otbMachineLearningModelCanRead.cxx otbTrainMachineLearningModel.cxx otbImageClassificationFilter.cxx otbMachineLearningRegressionTests.cxx +otbExhaustiveExponentialOptimizerNew.cxx +otbExhaustiveExponentialOptimizerTest.cxx +otbLabelMapClassifier.cxx +otbSVMCrossValidationCostFunctionNew.cxx +otbSVMMarginSampler.cxx ) if(OTB_USE_SHARK) @@ -70,6 +75,16 @@ otb_add_test(NAME leTvConfusionMatrixConcatenateTest COMMAND otbSupervisedTestDr ${INPUTDATA}/Classification/QB_1_ortho_C5.csv ${INPUTDATA}/Classification/QB_1_ortho_C6.csv) +otb_add_test(NAME leTuExhaustiveExponentialOptimizerNew COMMAND otbSupervisedTestDriver + otbExhaustiveExponentialOptimizerNew) + +otb_add_test(NAME leTvExhaustiveExponentialOptimizerTest COMMAND otbSupervisedTestDriver + --compare-ascii ${NOTOL} + ${BASELINE_FILES}/leTvExhaustiveExponentialOptimizerOutput.txt + ${TEMP}/leTvExhaustiveExponentialOptimizerTestOutput.txt + otbExhaustiveExponentialOptimizerTest + ${TEMP}/leTvExhaustiveExponentialOptimizerTestOutput.txt) + if(OTB_USE_LIBSVM) include(tests-libsvm.cmake) endif() diff --git a/Modules/Learning/SVMLearning/test/otbExhaustiveExponentialOptimizerNew.cxx b/Modules/Learning/Supervised/test/otbExhaustiveExponentialOptimizerNew.cxx similarity index 100% rename from Modules/Learning/SVMLearning/test/otbExhaustiveExponentialOptimizerNew.cxx rename to Modules/Learning/Supervised/test/otbExhaustiveExponentialOptimizerNew.cxx diff --git a/Modules/Learning/SVMLearning/test/otbExhaustiveExponentialOptimizerTest.cxx b/Modules/Learning/Supervised/test/otbExhaustiveExponentialOptimizerTest.cxx similarity index 100% rename from Modules/Learning/SVMLearning/test/otbExhaustiveExponentialOptimizerTest.cxx rename to Modules/Learning/Supervised/test/otbExhaustiveExponentialOptimizerTest.cxx diff --git a/Modules/Learning/SVMLearning/test/otbLabelMapSVMClassifier.cxx b/Modules/Learning/Supervised/test/otbLabelMapClassifier.cxx similarity index 88% rename from Modules/Learning/SVMLearning/test/otbLabelMapSVMClassifier.cxx rename to Modules/Learning/Supervised/test/otbLabelMapClassifier.cxx index 634a41f5511b33fcdd42c9044ec2deb0a9a568c7..094e3e3a23256ad05a6708ccd234469eae5dbeba 100644 --- a/Modules/Learning/SVMLearning/test/otbLabelMapSVMClassifier.cxx +++ b/Modules/Learning/Supervised/test/otbLabelMapClassifier.cxx @@ -31,8 +31,8 @@ #include "otbShapeAttributesLabelMapFilter.h" #include "otbBandsStatisticsAttributesLabelMapFilter.h" #include "otbLabelMapWithClassLabelToLabeledSampleListFilter.h" -#include "otbSVMSampleListModelEstimator.h" -#include "otbLabelMapSVMClassifier.h" +#include "otbLibSVMMachineLearningModel.h" +#include "otbLabelMapClassifier.h" #include "otbLabelMapWithClassLabelToClassLabelImageFilter.h" const unsigned int Dimension = 2; @@ -60,12 +60,9 @@ typedef itk::Statistics::ListSample<VectorType> ListSampleType; typedef itk::Statistics::ListSample<TrainingVectorType> TrainingListSampleType; typedef otb::LabelMapWithClassLabelToLabeledSampleListFilter<LabelMapType, ListSampleType, TrainingListSampleType> ListSampleFilterType; +typedef otb::LibSVMMachineLearningModel<double,LabelType> SVMType; -typedef otb::Functor::VariableLengthVectorToMeasurementVectorFunctor<VectorType> MeasurementVectorFunctorType; -typedef otb::SVMSampleListModelEstimator<ListSampleType, TrainingListSampleType, - MeasurementVectorFunctorType> SVMEstimatorType; - -typedef otb::LabelMapSVMClassifier<LabelMapType> ClassifierType; +typedef otb::LabelMapClassifier<LabelMapType> ClassifierType; typedef otb::LabelMapWithClassLabelToClassLabelImageFilter <LabelMapType, LabeledImageType> ClassifImageGeneratorType; @@ -78,13 +75,13 @@ LabelObjectType::Pointer makeTrainingSample(LabelMapType* labelMap, LabelType la return newLabelObject; } -int otbLabelMapSVMClassifierNew(int itkNotUsed(argc), char * itkNotUsed(argv)[]) +int otbLabelMapClassifierNew(int itkNotUsed(argc), char * itkNotUsed(argv)[]) { ClassifierType::Pointer classifier = ClassifierType::New(); return EXIT_SUCCESS; } -int otbLabelMapSVMClassifier(int itkNotUsed(argc), char * argv[]) +int otbLabelMapClassifier(int itkNotUsed(argc), char * argv[]) { const char * infname = argv[1]; const char * lfname = argv[2]; @@ -98,7 +95,7 @@ int otbLabelMapSVMClassifier(int itkNotUsed(argc), char * argv[]) BandsStatisticsFilterType::Pointer radiometricFilter = BandsStatisticsFilterType::New(); LabelMapType::Pointer trainingLabelMap = LabelMapType::New(); ListSampleFilterType::Pointer labelMap2SampleList = ListSampleFilterType::New(); - SVMEstimatorType::Pointer svmEstim = SVMEstimatorType::New(); + SVMType::Pointer model = SVMType::New(); ClassifierType::Pointer classifier = ClassifierType::New(); ClassifImageGeneratorType::Pointer imGenerator = ClassifImageGeneratorType::New(); LabeledWriterType::Pointer writer = LabeledWriterType::New(); @@ -153,14 +150,13 @@ int otbLabelMapSVMClassifier(int itkNotUsed(argc), char * argv[]) labelMap2SampleList->Update(); // Estimate SVM model - svmEstim->SetInputSampleList(labelMap2SampleList->GetOutputSampleList()); - svmEstim->SetTrainingSampleList(labelMap2SampleList->GetOutputTrainingSampleList()); - svmEstim->Modified(); - svmEstim->Update(); + model->SetInputListSample(const_cast<SVMType::InputListSampleType*>(labelMap2SampleList->GetOutputSampleList())); + model->SetTargetListSample(const_cast<SVMType::TargetListSampleType*>(labelMap2SampleList->GetOutputTrainingSampleList())); + model->Train(); // Classify using the whole LabelMap with estimated model classifier->SetInput(labelMap); - classifier->SetModel(svmEstim->GetModel()); + classifier->SetModel(model); for (attrIt = attributes.begin(); attrIt != attributes.end(); ++attrIt) { diff --git a/Modules/Learning/SVMLearning/test/otbSVMCrossValidationCostFunctionNew.cxx b/Modules/Learning/Supervised/test/otbSVMCrossValidationCostFunctionNew.cxx similarity index 90% rename from Modules/Learning/SVMLearning/test/otbSVMCrossValidationCostFunctionNew.cxx rename to Modules/Learning/Supervised/test/otbSVMCrossValidationCostFunctionNew.cxx index a8865b5300655ac69f9279ee4abeb44e48aa57c3..06ec8c1b6a3bc53bb4c7c5f7095042c0ecd273ed 100644 --- a/Modules/Learning/SVMLearning/test/otbSVMCrossValidationCostFunctionNew.cxx +++ b/Modules/Learning/Supervised/test/otbSVMCrossValidationCostFunctionNew.cxx @@ -25,6 +25,7 @@ #include "otbImage.h" #include <iostream> +#include "otbLibSVMMachineLearningModel.h" #include "otbSVMCrossValidationCostFunction.h" int otbSVMCrossValidationCostFunctionNew(int itkNotUsed(argc), char * itkNotUsed(argv) []) @@ -32,7 +33,7 @@ int otbSVMCrossValidationCostFunctionNew(int itkNotUsed(argc), char * itkNotUsed typedef unsigned char InputPixelType; typedef unsigned char LabelPixelType; - typedef otb::SVMModel<InputPixelType, LabelPixelType> ModelType; + typedef otb::LibSVMMachineLearningModel<InputPixelType,LabelPixelType> ModelType; typedef otb::SVMCrossValidationCostFunction<ModelType> FunctionType; FunctionType::Pointer function = FunctionType::New(); diff --git a/Modules/Learning/SVMLearning/test/otbSVMMarginSampler.cxx b/Modules/Learning/Supervised/test/otbSVMMarginSampler.cxx similarity index 89% rename from Modules/Learning/SVMLearning/test/otbSVMMarginSampler.cxx rename to Modules/Learning/Supervised/test/otbSVMMarginSampler.cxx index a0822eeb8d3a8e68562c2ad4b663033d10f20d42..f70bb88332dcd2adbf04ddb7140c63094fb2e916 100644 --- a/Modules/Learning/SVMLearning/test/otbSVMMarginSampler.cxx +++ b/Modules/Learning/Supervised/test/otbSVMMarginSampler.cxx @@ -25,14 +25,13 @@ #include "itkListSample.h" #include "otbSVMMarginSampler.h" -#include "otbSVMModel.h" +#include "otbLibSVMMachineLearningModel.h" int otbSVMMarginSamplerNew(int itkNotUsed(argc), char * itkNotUsed(argv) []) { typedef itk::VariableLengthVector<double> SampleType; typedef itk::Statistics::ListSample<SampleType> SampleListType; - typedef otb::SVMModel<SampleListType::MeasurementType, - unsigned int> SVMModelType; + typedef otb::LibSVMMachineLearningModel<double,unsigned int> SVMModelType; typedef otb::SVMMarginSampler<SampleListType,SVMModelType> MarginSamplerType; MarginSamplerType::Pointer marginSampler = MarginSamplerType::New(); diff --git a/Modules/Learning/Supervised/test/otbSupervisedTestDriver.cxx b/Modules/Learning/Supervised/test/otbSupervisedTestDriver.cxx index d96021c156c46b0e7d72ccac06f0d9006c0eb8b5..73b5d464039957b8fb9eefb9be82db3a66d58e9a 100644 --- a/Modules/Learning/Supervised/test/otbSupervisedTestDriver.cxx +++ b/Modules/Learning/Supervised/test/otbSupervisedTestDriver.cxx @@ -34,34 +34,32 @@ void RegisterTests() REGISTER_TEST(otbConfusionMatrixMeasurementsNew); REGISTER_TEST(otbConfusionMatrixMeasurementsTest); REGISTER_TEST(otbConfusionMatrixConcatenateTest); + REGISTER_TEST(otbExhaustiveExponentialOptimizerNew); + REGISTER_TEST(otbExhaustiveExponentialOptimizerTest); #ifdef OTB_USE_LIBSVM REGISTER_TEST(otbLibSVMMachineLearningModelCanRead); + REGISTER_TEST(otbLibSVMMachineLearningModelNew); + REGISTER_TEST(otbLibSVMMachineLearningModel); + REGISTER_TEST(otbLibSVMRegressionTests); + REGISTER_TEST(otbLabelMapClassifierNew); + REGISTER_TEST(otbLabelMapClassifier); + REGISTER_TEST(otbSVMCrossValidationCostFunctionNew); + REGISTER_TEST(otbSVMMarginSamplerNew); #endif #ifdef OTB_USE_OPENCV + // can read tests REGISTER_TEST(otbSVMMachineLearningModelCanRead); REGISTER_TEST(otbRandomForestsMachineLearningModelCanRead); REGISTER_TEST(otbBoostMachineLearningModelCanRead); REGISTER_TEST(otbNeuralNetworkMachineLearningModelCanRead); REGISTER_TEST(otbNormalBayesMachineLearningModelCanRead); REGISTER_TEST(otbDecisionTreeMachineLearningModelCanRead); - #ifndef OTB_OPENCV_3 - REGISTER_TEST(otbGradientBoostedTreeMachineLearningModelCanRead); - #endif REGISTER_TEST(otbKNNMachineLearningModelCanRead); - #endif - - #ifdef OTB_USE_LIBSVM - REGISTER_TEST(otbLibSVMMachineLearningModelNew); - REGISTER_TEST(otbLibSVMMachineLearningModel); - REGISTER_TEST(otbLibSVMRegressionTests); - #endif - - #ifdef OTB_USE_OPENCV + // training tests REGISTER_TEST(otbSVMMachineLearningModelNew); REGISTER_TEST(otbSVMMachineLearningModel); - REGISTER_TEST(otbSVMMachineLearningRegressionModel); REGISTER_TEST(otbKNearestNeighborsMachineLearningModelNew); REGISTER_TEST(otbKNearestNeighborsMachineLearningModel); REGISTER_TEST(otbRandomForestsMachineLearningModelNew); @@ -74,17 +72,20 @@ void RegisterTests() REGISTER_TEST(otbNormalBayesMachineLearningModel); REGISTER_TEST(otbDecisionTreeMachineLearningModelNew); REGISTER_TEST(otbDecisionTreeMachineLearningModel); - #ifndef OTB_OPENCV_3 - REGISTER_TEST(otbGradientBoostedTreeMachineLearningModelNew); - REGISTER_TEST(otbGradientBoostedTreeMachineLearningModel); - REGISTER_TEST(otbGradientBoostedTreeRegressionTests); - #endif + // regression tests REGISTER_TEST(otbNeuralNetworkRegressionTests); REGISTER_TEST(otbSVMRegressionTests); + REGISTER_TEST(otbSVMMachineLearningRegressionModel); REGISTER_TEST(otbDecisionTreeRegressionTests); REGISTER_TEST(otbKNearestNeighborsRegressionTests); REGISTER_TEST(otbRandomForestsRegressionTests); -#endif + #ifndef OTB_OPENCV_3 + REGISTER_TEST(otbGradientBoostedTreeMachineLearningModelCanRead); + REGISTER_TEST(otbGradientBoostedTreeMachineLearningModelNew); + REGISTER_TEST(otbGradientBoostedTreeMachineLearningModel); + REGISTER_TEST(otbGradientBoostedTreeRegressionTests); + #endif +#endif #ifdef OTB_USE_SHARK REGISTER_TEST(otbSharkRFMachineLearningModelNew); diff --git a/Modules/Learning/Supervised/test/otbTrainMachineLearningModel.cxx b/Modules/Learning/Supervised/test/otbTrainMachineLearningModel.cxx index 590fae174907817e0ed525cda4d56c1d3e78e2d0..0633cd0f53a7acbf991cf2d727b1e766c9a753a3 100644 --- a/Modules/Learning/Supervised/test/otbTrainMachineLearningModel.cxx +++ b/Modules/Learning/Supervised/test/otbTrainMachineLearningModel.cxx @@ -204,7 +204,6 @@ int otbLibSVMMachineLearningModel(int argc, char * argv[]) typedef otb::LibSVMMachineLearningModel<InputValueType, TargetValueType> SVMType; InputListSampleType::Pointer samples = InputListSampleType::New(); TargetListSampleType::Pointer labels = TargetListSampleType::New(); - TargetListSampleType::Pointer predicted = TargetListSampleType::New(); if (!ReadDataFile(argv[1], samples, labels)) { @@ -217,8 +216,7 @@ int otbLibSVMMachineLearningModel(int argc, char * argv[]) classifier->SetTargetListSample(labels); classifier->Train(); - classifier->SetTargetListSample(predicted); - classifier->PredictAll(); + TargetListSampleType::Pointer predicted = classifier->PredictBatch(samples, NULL); ConfusionMatrixCalculatorType::Pointer cmCalculator = ConfusionMatrixCalculatorType::New(); @@ -235,13 +233,10 @@ int otbLibSVMMachineLearningModel(int argc, char * argv[]) classifier->Save(argv[2]); //Load Model to new LibSVM - TargetListSampleType::Pointer predictedLoad = TargetListSampleType::New(); SVMType::Pointer classifierLoad = SVMType::New(); classifierLoad->Load(argv[2]); - classifierLoad->SetInputListSample(samples); - classifierLoad->SetTargetListSample(predictedLoad); - classifierLoad->PredictAll(); + TargetListSampleType::Pointer predictedLoad = classifierLoad->PredictBatch(samples, NULL); ConfusionMatrixCalculatorType::Pointer cmCalculatorLoad = ConfusionMatrixCalculatorType::New(); @@ -298,7 +293,6 @@ int otbSVMMachineLearningModel(int argc, char * argv[]) InputListSampleType::Pointer samples = InputListSampleType::New(); TargetListSampleType::Pointer labels = TargetListSampleType::New(); - TargetListSampleType::Pointer predicted = TargetListSampleType::New(); if(!ReadDataFile(argv[1],samples,labels)) { @@ -311,8 +305,7 @@ int otbSVMMachineLearningModel(int argc, char * argv[]) classifier->SetTargetListSample(labels); classifier->Train(); - classifier->SetTargetListSample(predicted); - classifier->PredictAll(); + TargetListSampleType::Pointer predicted = classifier->PredictBatch(samples, NULL); classifier->Save(argv[2]); @@ -329,13 +322,10 @@ int otbSVMMachineLearningModel(int argc, char * argv[]) std::cout<<"Overall Accuracy: "<<cmCalculator->GetOverallAccuracy()<<std::endl; //Load Model to new SVM - TargetListSampleType::Pointer predictedLoad = TargetListSampleType::New(); SVMType::Pointer classifierLoad = SVMType::New(); classifierLoad->Load(argv[2]); - classifierLoad->SetInputListSample(samples); - classifierLoad->SetTargetListSample(predictedLoad); - classifierLoad->PredictAll(); + TargetListSampleType::Pointer predictedLoad = classifierLoad->PredictBatch(samples); ConfusionMatrixCalculatorType::Pointer cmCalculatorLoad = ConfusionMatrixCalculatorType::New(); @@ -373,7 +363,6 @@ int otbSVMMachineLearningRegressionModel(int argc, char * argv[]) InputListSampleRegressionType::Pointer samples = InputListSampleRegressionType::New(); TargetListSampleRegressionType::Pointer labels = TargetListSampleRegressionType::New(); - TargetListSampleRegressionType::Pointer predicted = TargetListSampleRegressionType::New(); if(!ReadDataRegressionFile(argv[1],samples,labels)) { @@ -415,9 +404,7 @@ int otbSVMMachineLearningRegressionModel(int argc, char * argv[]) samplesT->SetMeasurementVectorSize(itk::NumericTraits<InputSampleRegressionType>::GetLength(sample)); samplesT->PushBack(sample); - classifier->SetInputListSample(samplesT); - classifier->SetTargetListSample(predicted); - classifier->PredictAll(); + TargetListSampleRegressionType::Pointer predicted = classifier->PredictBatch(samplesT, NULL); const float age = 15; @@ -451,7 +438,6 @@ int otbKNearestNeighborsMachineLearningModel(int argc, char * argv[]) typedef otb::KNearestNeighborsMachineLearningModel<InputValueType,TargetValueType> KNearestNeighborsType; InputListSampleType::Pointer samples = InputListSampleType::New(); TargetListSampleType::Pointer labels = TargetListSampleType::New(); - TargetListSampleType::Pointer predicted = TargetListSampleType::New(); if(!ReadDataFile(argv[1],samples,labels)) { @@ -466,8 +452,7 @@ int otbKNearestNeighborsMachineLearningModel(int argc, char * argv[]) //write the model classifier->Save(argv[2]); - classifier->SetTargetListSample(predicted); - classifier->PredictAll(); + TargetListSampleType::Pointer predicted = classifier->PredictBatch(samples, NULL); ConfusionMatrixCalculatorType::Pointer cmCalculator = ConfusionMatrixCalculatorType::New(); @@ -483,13 +468,10 @@ int otbKNearestNeighborsMachineLearningModel(int argc, char * argv[]) //Load Model to new KNN - TargetListSampleType::Pointer predictedLoad = TargetListSampleType::New(); KNearestNeighborsType::Pointer classifierLoad = KNearestNeighborsType::New(); classifierLoad->Load(argv[2]); - classifierLoad->SetInputListSample(samples); - classifierLoad->SetTargetListSample(predictedLoad); - classifierLoad->PredictAll(); + TargetListSampleType::Pointer predictedLoad = classifierLoad->PredictBatch(samples, NULL); ConfusionMatrixCalculatorType::Pointer cmCalculatorLoad = ConfusionMatrixCalculatorType::New(); @@ -533,7 +515,6 @@ int otbRandomForestsMachineLearningModel(int argc, char * argv[]) typedef otb::RandomForestsMachineLearningModel<InputValueType,TargetValueType> RandomForestType; InputListSampleType::Pointer samples = InputListSampleType::New(); TargetListSampleType::Pointer labels = TargetListSampleType::New(); - TargetListSampleType::Pointer predicted = TargetListSampleType::New(); if(!ReadDataFile(argv[1],samples,labels)) { @@ -558,8 +539,7 @@ int otbRandomForestsMachineLearningModel(int argc, char * argv[]) classifier->Train(); classifier->Save(argv[2]); - classifier->SetTargetListSample(predicted); - classifier->PredictAll(); + TargetListSampleType::Pointer predicted = classifier->PredictBatch(samples, NULL); ConfusionMatrixCalculatorType::Pointer cmCalculator = ConfusionMatrixCalculatorType::New(); @@ -574,13 +554,10 @@ int otbRandomForestsMachineLearningModel(int argc, char * argv[]) std::cout<<"Overall Accuracy: "<<cmCalculator->GetOverallAccuracy()<<std::endl; //Load Model to new RF - TargetListSampleType::Pointer predictedLoad = TargetListSampleType::New(); RandomForestType::Pointer classifierLoad = RandomForestType::New(); classifierLoad->Load(argv[2]); - classifierLoad->SetInputListSample(samples); - classifierLoad->SetTargetListSample(predictedLoad); - classifierLoad->PredictAll(); + TargetListSampleType::Pointer predictedLoad = classifierLoad->PredictBatch(samples, NULL); ConfusionMatrixCalculatorType::Pointer cmCalculatorLoad = ConfusionMatrixCalculatorType::New(); @@ -625,7 +602,6 @@ int otbBoostMachineLearningModel(int argc, char * argv[]) InputListSampleType::Pointer samples = InputListSampleType::New(); TargetListSampleType::Pointer labels = TargetListSampleType::New(); - TargetListSampleType::Pointer predicted = TargetListSampleType::New(); if(!ReadDataFile(argv[1],samples,labels)) { @@ -647,8 +623,7 @@ int otbBoostMachineLearningModel(int argc, char * argv[]) classifier->SetTargetListSample(labels); classifier->Train(); - classifier->SetTargetListSample(predicted); - classifier->PredictAll(); + TargetListSampleType::Pointer predicted = classifier->PredictBatch(samples, NULL); classifier->Save(argv[2]); @@ -665,13 +640,10 @@ int otbBoostMachineLearningModel(int argc, char * argv[]) std::cout<<"Overall Accuracy: "<<cmCalculator->GetOverallAccuracy()<<std::endl; //Load Model to new Boost model - TargetListSampleType::Pointer predictedLoad = TargetListSampleType::New(); BoostType::Pointer classifierLoad = BoostType::New(); classifierLoad->Load(argv[2]); - classifierLoad->SetInputListSample(samples); - classifierLoad->SetTargetListSample(predictedLoad); - classifierLoad->PredictAll(); + TargetListSampleType::Pointer predictedLoad = classifierLoad->PredictBatch(samples, NULL); ConfusionMatrixCalculatorType::Pointer cmCalculatorLoad = ConfusionMatrixCalculatorType::New(); @@ -716,7 +688,6 @@ int otbANNMachineLearningModel(int argc, char * argv[]) typedef otb::NeuralNetworkMachineLearningModel<InputValueType, TargetValueType> ANNType; InputListSampleType::Pointer samples = InputListSampleType::New(); TargetListSampleType::Pointer labels = TargetListSampleType::New(); - TargetListSampleType::Pointer predicted = TargetListSampleType::New(); if (!ReadDataFile(argv[1], samples, labels)) { @@ -742,8 +713,7 @@ int otbANNMachineLearningModel(int argc, char * argv[]) classifier->SetEpsilon(0.01); */ classifier->Train(); - classifier->SetTargetListSample(predicted); - classifier->PredictAll(); + TargetListSampleType::Pointer predicted = classifier->PredictBatch(samples, NULL); ConfusionMatrixCalculatorType::Pointer cmCalculator = ConfusionMatrixCalculatorType::New(); @@ -760,13 +730,10 @@ int otbANNMachineLearningModel(int argc, char * argv[]) classifier->Save(argv[2]); //Load Model to new ANN - TargetListSampleType::Pointer predictedLoad = TargetListSampleType::New(); ANNType::Pointer classifierLoad = ANNType::New(); classifierLoad->Load(argv[2]); - classifierLoad->SetInputListSample(samples); - classifierLoad->SetTargetListSample(predictedLoad); - classifierLoad->PredictAll(); + TargetListSampleType::Pointer predictedLoad = classifierLoad->PredictBatch(samples, NULL); ConfusionMatrixCalculatorType::Pointer cmCalculatorLoad = ConfusionMatrixCalculatorType::New(); @@ -811,7 +778,6 @@ int otbNormalBayesMachineLearningModel(int argc, char * argv[]) InputListSampleType::Pointer samples = InputListSampleType::New(); TargetListSampleType::Pointer labels = TargetListSampleType::New(); - TargetListSampleType::Pointer predicted = TargetListSampleType::New(); if(!ReadDataFile(argv[1],samples,labels)) { @@ -824,8 +790,7 @@ int otbNormalBayesMachineLearningModel(int argc, char * argv[]) classifier->SetTargetListSample(labels); classifier->Train(); - classifier->SetTargetListSample(predicted); - classifier->PredictAll(); + TargetListSampleType::Pointer predicted = classifier->PredictBatch(samples, NULL); classifier->Save(argv[2]); @@ -842,13 +807,10 @@ int otbNormalBayesMachineLearningModel(int argc, char * argv[]) std::cout<<"Overall Accuracy: "<<cmCalculator->GetOverallAccuracy()<<std::endl; //Load Model to new Normal Bayes - TargetListSampleType::Pointer predictedLoad = TargetListSampleType::New(); NormalBayesType::Pointer classifierLoad = NormalBayesType::New(); classifierLoad->Load(argv[2]); - classifierLoad->SetInputListSample(samples); - classifierLoad->SetTargetListSample(predictedLoad); - classifierLoad->PredictAll(); + TargetListSampleType::Pointer predictedLoad = classifierLoad->PredictBatch(samples, NULL); ConfusionMatrixCalculatorType::Pointer cmCalculatorLoad = ConfusionMatrixCalculatorType::New(); @@ -893,7 +855,6 @@ int otbDecisionTreeMachineLearningModel(int argc, char * argv[]) InputListSampleType::Pointer samples = InputListSampleType::New(); TargetListSampleType::Pointer labels = TargetListSampleType::New(); - TargetListSampleType::Pointer predicted = TargetListSampleType::New(); if(!ReadDataFile(argv[1],samples,labels)) { @@ -906,8 +867,7 @@ int otbDecisionTreeMachineLearningModel(int argc, char * argv[]) classifier->SetTargetListSample(labels); classifier->Train(); - classifier->SetTargetListSample(predicted); - classifier->PredictAll(); + TargetListSampleType::Pointer predicted = classifier->PredictBatch(samples, NULL); classifier->Save(argv[2]); @@ -924,13 +884,10 @@ int otbDecisionTreeMachineLearningModel(int argc, char * argv[]) std::cout<<"Overall Accuracy: "<<cmCalculator->GetOverallAccuracy()<<std::endl; //Load Model to new Decision Tree - TargetListSampleType::Pointer predictedLoad = TargetListSampleType::New(); DecisionTreeType::Pointer classifierLoad = DecisionTreeType::New(); classifierLoad->Load(argv[2]); - classifierLoad->SetInputListSample(samples); - classifierLoad->SetTargetListSample(predictedLoad); - classifierLoad->PredictAll(); + TargetListSampleType::Pointer predictedLoad = classifierLoad->PredictBatch(samples, NULL); ConfusionMatrixCalculatorType::Pointer cmCalculatorLoad = ConfusionMatrixCalculatorType::New(); @@ -976,7 +933,6 @@ int otbGradientBoostedTreeMachineLearningModel(int argc, char * argv[]) InputListSampleType::Pointer samples = InputListSampleType::New(); TargetListSampleType::Pointer labels = TargetListSampleType::New(); - TargetListSampleType::Pointer predicted = TargetListSampleType::New(); if(!ReadDataFile(argv[1],samples,labels)) { @@ -989,8 +945,7 @@ int otbGradientBoostedTreeMachineLearningModel(int argc, char * argv[]) classifier->SetTargetListSample(labels); classifier->Train(); - classifier->SetTargetListSample(predicted); - classifier->PredictAll(); + TargetListSampleType::Pointer predicted = classifier->PredictBatch(samples, NULL); classifier->Save(argv[2]); @@ -1007,13 +962,10 @@ int otbGradientBoostedTreeMachineLearningModel(int argc, char * argv[]) std::cout<<"Overall Accuracy: "<<cmCalculator->GetOverallAccuracy()<<std::endl; //Load Model to new GBT - TargetListSampleType::Pointer predictedLoad = TargetListSampleType::New(); GBTreeType::Pointer classifierLoad = GBTreeType::New(); classifierLoad->Load(argv[2]); - classifierLoad->SetInputListSample(samples); - classifierLoad->SetTargetListSample(predictedLoad); - classifierLoad->PredictAll(); + TargetListSampleType::Pointer predictedLoad = classifierLoad->PredictBatch(samples, NULL); ConfusionMatrixCalculatorType::Pointer cmCalculatorLoad = ConfusionMatrixCalculatorType::New(); @@ -1196,7 +1148,6 @@ int otbSharkRFMachineLearningModel(int argc, char * argv[]) typedef otb::SharkRandomForestsMachineLearningModel<InputValueType,TargetValueType> RandomForestType; InputListSampleType::Pointer samples = InputListSampleType::New(); TargetListSampleType::Pointer labels = TargetListSampleType::New(); - TargetListSampleType::Pointer predicted = TargetListSampleType::New(); if(!SharkReadDataFile(argv[1],samples,labels)) { @@ -1216,11 +1167,10 @@ int otbSharkRFMachineLearningModel(int argc, char * argv[]) std::cout << "Train\n"; classifier->Train(); std::cout << "Save\n"; - classifier->Save(argv[2]); - + classifier->Save(argv[2]); + std::cout << "Predict\n"; - classifier->SetTargetListSample(predicted); - classifier->PredictAll(); + TargetListSampleType::Pointer predicted = classifier->PredictBatch(samples, NULL); ConfusionMatrixCalculatorType::Pointer cmCalculator = ConfusionMatrixCalculatorType::New(); @@ -1233,7 +1183,7 @@ int otbSharkRFMachineLearningModel(int argc, char * argv[]) const float kappaIdx = cmCalculator->GetKappaIndex(); std::cout<<"Kappa: "<<kappaIdx<<std::endl; std::cout<<"Overall Accuracy: "<<cmCalculator->GetOverallAccuracy()<<std::endl; - + // //Predict single samples. Written for benchmarking purposes, but // too long for regression testing // std::cout << "Predict single samples\n"; @@ -1244,27 +1194,24 @@ int otbSharkRFMachineLearningModel(int argc, char * argv[]) // { // classifier->Predict(sIt.GetMeasurementVector())[0]; // } - // auto duration = std::chrono::duration_cast< TimeT> + // auto duration = std::chrono::duration_cast< TimeT> // (std::chrono::system_clock::now() - start); // auto elapsed = duration.count(); // std::cout << "Predict took " << elapsed << " ms\n"; // std::cout << "Single sample OA = " << oa << '\n'; //Load Model to new RF - TargetListSampleType::Pointer predictedLoad = TargetListSampleType::New(); RandomForestType::Pointer classifierLoad = RandomForestType::New(); std::cout << "Load\n"; classifierLoad->Load(argv[2]); auto start = std::chrono::system_clock::now(); - classifierLoad->SetInputListSample(samples); - classifierLoad->SetTargetListSample(predictedLoad); std::cout << "Predict loaded\n"; - classifierLoad->PredictAll(); + TargetListSampleType::Pointer predictedLoad = classifierLoad->PredictBatch(samples, NULL); using TimeT = std::chrono::milliseconds; - auto duration = std::chrono::duration_cast< TimeT> + auto duration = std::chrono::duration_cast< TimeT> (std::chrono::system_clock::now() - start); auto elapsed = duration.count(); - std::cout << "PredictAll took " << elapsed << " ms\n"; + std::cout << "PredictBatch took " << elapsed << " ms\n"; ConfusionMatrixCalculatorType::Pointer cmCalculatorLoad = ConfusionMatrixCalculatorType::New(); cmCalculatorLoad->SetProducedLabels(predictedLoad); @@ -1286,7 +1233,7 @@ int otbSharkRFMachineLearningModel(int argc, char * argv[]) { return EXIT_FAILURE; } - + return EXIT_SUCCESS; } diff --git a/Modules/Learning/Supervised/test/tests-libsvm.cmake b/Modules/Learning/Supervised/test/tests-libsvm.cmake index a9f08a966682b39a7659e8711370f4d01c20f27b..bbf6647ab09866b3074d840a84e301f9956bc48f 100644 --- a/Modules/Learning/Supervised/test/tests-libsvm.cmake +++ b/Modules/Learning/Supervised/test/tests-libsvm.cmake @@ -45,3 +45,18 @@ set_property(TEST leTvLibSVMMachineLearningModelCanRead PROPERTY DEPENDS leTvLib otb_add_test(NAME leTvLibSVMMachineLearningModelReg COMMAND otbSupervisedTestDriver otbLibSVMRegressionTests ) + +#otb_add_test(NAME obTvLabelMapSVMClassifier COMMAND otbSupervisedTestDriver + #otbLabelMapClassifier + #${INPUTDATA}/maur.tif + #${INPUTDATA}/maur_labelled.tif + #${TEMP}/obTvLabelMapSVMClassifierLabeledOutput.tif) + +otb_add_test(NAME obTuLabelMapSVMClassifierNew COMMAND otbSupervisedTestDriver + otbLabelMapClassifierNew) + +otb_add_test(NAME leTuSVMCrossValidationCostFunctionNew COMMAND otbSupervisedTestDriver + otbSVMCrossValidationCostFunctionNew) + +otb_add_test(NAME leTuSVMMarginSamplerNew COMMAND otbSupervisedTestDriver + otbSVMMarginSamplerNew) diff --git a/Modules/Radiometry/SARCalibration/include/otbSarDeburstImageFilter.txx b/Modules/Radiometry/SARCalibration/include/otbSarDeburstImageFilter.txx index d868663b8e5c20ffa6828628b8b63877d8c2f0dd..ef9c1638a8b00694cb36e2dbf0f807f6196ac659 100644 --- a/Modules/Radiometry/SARCalibration/include/otbSarDeburstImageFilter.txx +++ b/Modules/Radiometry/SARCalibration/include/otbSarDeburstImageFilter.txx @@ -102,7 +102,7 @@ SarDeburstImageFilter<TImage>::GenerateOutputInformation() origin[1]=0.5+outputOriginLine; outputPtr->SetOrigin(origin); - // Update line records to accomodate actual input image region + // Update line records to accommodate actual input image region LinesRecordVectorType filteredRecords; for(LinesRecordVectorType::const_iterator it = m_LinesRecord.begin(); diff --git a/Modules/Radiometry/Simulation/otb-module.cmake b/Modules/Radiometry/Simulation/otb-module.cmake index 2676d932fb2f60e93e92aaca47b0477b86a137c4..a73fdf6edb8fb42f4a8e55e09dc84a8222ca23a7 100644 --- a/Modules/Radiometry/Simulation/otb-module.cmake +++ b/Modules/Radiometry/Simulation/otb-module.cmake @@ -47,7 +47,7 @@ ENABLE_SHARED OTBTestKernel OTBLearningBase OTBSupervised - OTBSVMLearning + OTBLibSVM OTBVectorDataIO DESCRIPTION diff --git a/Modules/Radiometry/Simulation/test/otbAtmosphericCorrectionsRSRSVMClassifier.cxx b/Modules/Radiometry/Simulation/test/otbAtmosphericCorrectionsRSRSVMClassifier.cxx index 1a98498bba41e5fce6bf39a432313d93e7ff1239..70bd23fb68614c46294fa3ae6dc369dc591638da 100644 --- a/Modules/Radiometry/Simulation/test/otbAtmosphericCorrectionsRSRSVMClassifier.cxx +++ b/Modules/Radiometry/Simulation/test/otbAtmosphericCorrectionsRSRSVMClassifier.cxx @@ -24,8 +24,7 @@ #include "otbSatelliteRSR.h" #include "otbReduceSpectralResponse.h" -#include "otbSVMSampleListModelEstimator.h" -#include "otbSVMClassifier.h" +#include "otbLibSVMMachineLearningModel.h" #include "otbConfusionMatrixCalculator.h" #include "itkMersenneTwisterRandomVariateGenerator.h" @@ -66,14 +65,12 @@ int otbAtmosphericCorrectionsRSRSVMClassifier(int argc, char * argv[]) typedef itk::VariableLengthVector<double> SampleType; typedef itk::Statistics::ListSample<SampleType> SampleListType; - typedef itk::FixedArray<unsigned long, 1> TrainingSampleType; - typedef itk::Statistics::ListSample<TrainingSampleType> TrainingSampleListType; + typedef itk::FixedArray<unsigned long, 1> TargetSampleType; + typedef itk::Statistics::ListSample<TargetSampleType> TargetSampleListType; - typedef otb::SVMSampleListModelEstimator<SampleListType, TrainingSampleListType> SVMModelEstimatorType; - typedef otb::SVMClassifier<SampleListType, unsigned long> SVMClassifierType; - typedef SVMClassifierType::OutputType ClassifierOutputType; + typedef otb::LibSVMMachineLearningModel<double, unsigned long> SVMType; - typedef otb::ConfusionMatrixCalculator<TrainingSampleListType, TrainingSampleListType> ConfusionMatrixCalculatorType; + typedef otb::ConfusionMatrixCalculator<TargetSampleListType, TargetSampleListType> ConfusionMatrixCalculatorType; if (argc != 20) { @@ -223,7 +220,7 @@ int otbAtmosphericCorrectionsRSRSVMClassifier(int argc, char * argv[]) //compute spectral response for all training files SampleListType::Pointer sampleList = SampleListType::New(); - TrainingSampleListType::Pointer trainingList = TrainingSampleListType::New(); + TargetSampleListType::Pointer trainingList = TargetSampleListType::New(); for (unsigned int i = 0; i < trainingFiles.size(); ++i) { @@ -246,7 +243,7 @@ int otbAtmosphericCorrectionsRSRSVMClassifier(int argc, char * argv[]) //Get the response in an itk::VariableLengthVector and add it to the sample list for SVMModelEstimator SampleType sample; - TrainingSampleType trainingSample; + TargetSampleType trainingSample; sample.SetSize(atmosphericEffectsFilter->GetCorrectedSpectralResponse()->Size()); std::cout << "corrected response : ["; for (unsigned int j = 0; j < atmosphericEffectsFilter->GetCorrectedSpectralResponse()->Size(); ++j) @@ -262,16 +259,16 @@ int otbAtmosphericCorrectionsRSRSVMClassifier(int argc, char * argv[]) } //SVM model estimator - SVMModelEstimatorType::Pointer estimator = SVMModelEstimatorType::New(); - estimator->SetInputSampleList(sampleList); - estimator->SetTrainingSampleList(trainingList); - estimator->DoProbabilityEstimates(true); - estimator->Update(); - estimator->GetModel()->SaveModel("model.txt"); + SVMType::Pointer classifier = SVMType::New(); + classifier->SetInputListSample(sampleList); + classifier->SetTargetListSample(trainingList); + classifier->SetDoProbabilityEstimates(true); + classifier->Train(); + classifier->Save("model.txt"); //compute spectral response for testing files sampleList->Clear(); //clear the sample list to re use it for testing samples - TrainingSampleListType::Pointer groundTruthClassList = TrainingSampleListType::New(); + TargetSampleListType::Pointer groundTruthClassList = TargetSampleListType::New(); for (unsigned int i = 0; i < testingFiles.size(); ++i) { SpectralResponsePointerType spectralResponse = SpectralResponseType::New(); @@ -293,7 +290,7 @@ int otbAtmosphericCorrectionsRSRSVMClassifier(int argc, char * argv[]) //Get the response in an itk::VariableLengthVector and add it to the sample list for SVMClassifier SampleType sample; - TrainingSampleType gtClass; + TargetSampleType gtClass; sample.SetSize(atmosphericEffectsFilter->GetCorrectedSpectralResponse()->Size()); for (unsigned int j = 0; j < atmosphericEffectsFilter->GetCorrectedSpectralResponse()->Size(); ++j) { @@ -305,21 +302,8 @@ int otbAtmosphericCorrectionsRSRSVMClassifier(int argc, char * argv[]) } //SVM Classifier - SVMClassifierType::Pointer classifier = SVMClassifierType::New(); - classifier->SetModel(estimator->GetModel()); - classifier->SetInput(sampleList); - classifier->SetNumberOfClasses(dirSR.size()); - classifier->Update(); + TargetSampleListType::Pointer classifierListLabel = classifier->PredictBatch(sampleList); - ClassifierOutputType::ConstIterator it = classifier->GetOutput()->Begin(); - - TrainingSampleListType::Pointer classifierListLabel = TrainingSampleListType::New(); - while (it != classifier->GetOutput()->End()) - { - std::cout << "class : " << it.GetClassLabel() << std::endl; - classifierListLabel->PushBack(it.GetClassLabel()); - ++it; - } for (unsigned int i = 0; i < testingFiles.size(); ++i) { std::cout << "ground truth class : " << testingGTClasses[i] << std::endl; diff --git a/Modules/Radiometry/Simulation/test/otbImageSimulationMethodSVMClassif.cxx b/Modules/Radiometry/Simulation/test/otbImageSimulationMethodSVMClassif.cxx index 302a06c2eb54cdd4d6b6ce2f52eaf9eebfcb32e0..639950e4b42b4455d56c4c1f3aa233e8ad4dce28 100644 --- a/Modules/Radiometry/Simulation/test/otbImageSimulationMethodSVMClassif.cxx +++ b/Modules/Radiometry/Simulation/test/otbImageSimulationMethodSVMClassif.cxx @@ -29,9 +29,10 @@ #include "otbSpatialisationFilter.h" #include "otbImageSimulationMethod.h" #include "otbAttributesMapLabelObject.h" -#include "otbSVMImageModelEstimator.h" -#include "otbSVMImageClassificationFilter.h" +#include "otbLibSVMMachineLearningModel.h" +#include "otbImageClassificationFilter.h" #include "otbImageFileReader.h" +#include "itkImageToListSampleAdaptor.h" int otbImageSimulationMethodSVMClassif(int itkNotUsed(argc), char * argv[]) { @@ -62,17 +63,16 @@ int otbImageSimulationMethodSVMClassif(int itkNotUsed(argc), char * argv[]) typedef otb::ImageSimulationMethod<VectorDataType, SpatialisationFilterType, SimulationStep1Type, SimulationStep2Type, FTMType , OutputImageType> ImageSimulationMethodType; - - typedef otb::SVMImageModelEstimator<OutputImageType, LabelImageType> SVMEstimatorType; - typedef otb::SVMImageClassificationFilter<OutputImageType, LabelImageType> SVMClassificationFilterType; + typedef otb::LibSVMMachineLearningModel<double, unsigned short> SVMType; + typedef otb::ImageClassificationFilter<OutputImageType,LabelImageType> ClassificationFilterType; /** Instantiation of pointer objects*/ ImageWriterType::Pointer writer = ImageWriterType::New(); LabelImageWriterType::Pointer labelWriter = LabelImageWriterType::New(); ImageSimulationMethodType::Pointer imageSimulation = ImageSimulationMethodType::New(); SpatialisationFilterType::Pointer spatialisationFilter = SpatialisationFilterType::New(); - SVMEstimatorType::Pointer svmEstimator = SVMEstimatorType::New(); - SVMClassificationFilterType::Pointer classifier = SVMClassificationFilterType::New(); + SVMType::Pointer model = SVMType::New(); + ClassificationFilterType::Pointer classifier = ClassificationFilterType::New(); SpatialisationFilterType::SizeType objectSize; @@ -132,15 +132,28 @@ int otbImageSimulationMethodSVMClassif(int itkNotUsed(argc), char * argv[]) // imageSimulation->SetVariance(); imageSimulation->UpdateData(); + + //~ svmEstimator->SetInputImage(imageSimulation->GetOutputReflectanceImage()); + //~ svmEstimator->SetTrainingImage(imageSimulation->GetOutputLabelImage()); + //~ svmEstimator->SetParametersOptimization(false); + //~ svmEstimator->DoProbabilityEstimates(true); + //~ svmEstimator->Update(); + + typedef itk::Statistics::ImageToListSampleAdaptor<OutputImageType> ListSampleAdaptorType; + typedef itk::Statistics::ImageToListSampleAdaptor<LabelImageType> TargetListSampleAdaptorType; - svmEstimator->SetInputImage(imageSimulation->GetOutputReflectanceImage()); - svmEstimator->SetTrainingImage(imageSimulation->GetOutputLabelImage()); - svmEstimator->SetParametersOptimization(false); - svmEstimator->DoProbabilityEstimates(true); - svmEstimator->Update(); + ListSampleAdaptorType::Pointer listSample = ListSampleAdaptorType::New(); + listSample->SetImage(imageSimulation->GetOutputReflectanceImage()); + TargetListSampleAdaptorType::Pointer targetListSample = TargetListSampleAdaptorType::New(); + targetListSample->SetImage(imageSimulation->GetOutputLabelImage()); - classifier->SetModel(svmEstimator->GetModel()); + model->SetInputListSample(listSample); + model->SetTargetListSample(targetListSample); + model->SetDoProbabilityEstimates(true); + model->Train(); + + classifier->SetModel(model); classifier->SetInput(imageSimulation->GetOutput()); //Write the result to an image file diff --git a/Modules/Radiometry/Simulation/test/otbReduceSpectralResponseSVMClassifier.cxx b/Modules/Radiometry/Simulation/test/otbReduceSpectralResponseSVMClassifier.cxx index 2c8a1b70a4c5e4c49b9ad81ca343c2746046cac3..71e0d85cd87830607f827888936db294044846d8 100644 --- a/Modules/Radiometry/Simulation/test/otbReduceSpectralResponseSVMClassifier.cxx +++ b/Modules/Radiometry/Simulation/test/otbReduceSpectralResponseSVMClassifier.cxx @@ -23,8 +23,7 @@ #include "otbSatelliteRSR.h" #include "otbReduceSpectralResponse.h" -#include "otbSVMSampleListModelEstimator.h" -#include "otbSVMClassifier.h" +#include "otbLibSVMMachineLearningModel.h" #include "otbConfusionMatrixCalculator.h" #include "itkMersenneTwisterRandomVariateGenerator.h" @@ -47,9 +46,7 @@ int otbReduceSpectralResponseSVMClassifier(int argc, char * argv[]) typedef itk::FixedArray<unsigned long, 1> TrainingSampleType; typedef itk::Statistics::ListSample<TrainingSampleType> TrainingSampleListType; - typedef otb::SVMSampleListModelEstimator<SampleListType, TrainingSampleListType> SVMModelEstimatorType; - typedef otb::SVMClassifier<SampleListType, unsigned long> SVMClassifierType; - typedef SVMClassifierType::OutputType ClassifierOutputType; + typedef otb::LibSVMMachineLearningModel<double, unsigned long> SVMType; typedef otb::ConfusionMatrixCalculator<TrainingSampleListType, TrainingSampleListType> ConfusionMatrixCalculatorType; @@ -174,19 +171,19 @@ int otbReduceSpectralResponseSVMClassifier(int argc, char * argv[]) } //SVM model estimator - SVMModelEstimatorType::Pointer estimator = SVMModelEstimatorType::New(); - estimator->SetInputSampleList(sampleList); - estimator->SetTrainingSampleList(trainingList); - estimator->SetNu(0.5); - estimator->SetKernelGamma(1); - estimator->SetKernelCoef0(1); - estimator->SetC(1); - estimator->SetEpsilon(0.001); - estimator->SetP(0.1); - estimator->DoProbabilityEstimates(true); - - estimator->Update(); - estimator->GetModel()->SaveModel("model.txt"); + SVMType::Pointer model = SVMType::New(); + model->SetInputListSample(sampleList); + model->SetTargetListSample(trainingList); + model->SetNu(0.5); + model->SetKernelGamma(1); + model->SetKernelCoef0(1); + model->SetC(1); + model->SetEpsilon(0.001); + model->SetP(0.1); + model->SetDoProbabilityEstimates(true); + + model->Train(); + model->Save("model.txt"); //compute spectral response for testing files sampleList->Clear(); //clear the sample list to re use it for testing samples @@ -219,19 +216,13 @@ int otbReduceSpectralResponseSVMClassifier(int argc, char * argv[]) } //SVM Classifier - SVMClassifierType::Pointer classifier = SVMClassifierType::New(); - classifier->SetModel(estimator->GetModel()); - classifier->SetInput(sampleList); - classifier->SetNumberOfClasses(dirSR.size()); - classifier->Update(); + TrainingSampleListType::Pointer classifierListLabel = + model->PredictBatch(sampleList); - ClassifierOutputType::ConstIterator it = classifier->GetOutput()->Begin(); - - TrainingSampleListType::Pointer classifierListLabel = TrainingSampleListType::New(); - while (it != classifier->GetOutput()->End()) + TrainingSampleListType::ConstIterator it = classifierListLabel->Begin(); + while (it != classifierListLabel->End()) { - std::cout << "class : " << it.GetClassLabel() << std::endl; - classifierListLabel->PushBack(it.GetClassLabel()); + std::cout << "class : " << it.GetMeasurementVector()[0] << std::endl; ++it; } for (unsigned int i = 0; i < testingFiles.size(); ++i) diff --git a/Modules/Registration/Stereo/include/otbStereoSensorModelToElevationMapFilter.h b/Modules/Registration/Stereo/include/otbStereoSensorModelToElevationMapFilter.h index 998e9f53703422171b14b42533a17d7932a74533..8a5137c4f662ce0aee315573f403199a363424a7 100644 --- a/Modules/Registration/Stereo/include/otbStereoSensorModelToElevationMapFilter.h +++ b/Modules/Registration/Stereo/include/otbStereoSensorModelToElevationMapFilter.h @@ -232,10 +232,6 @@ private: /** Step of the elevation exploration. */ double m_ElevationStep; - /** If set to true, the local elevation is extracted from a DEM + - geoid. If set to false, average elevation is used. Default is false. */ - bool m_UseDEM; - /** Threshold of the correlation to keep estimated height. */ double m_CorrelationThreshold; diff --git a/Modules/Registration/Stereo/include/otbStereoSensorModelToElevationMapFilter.txx b/Modules/Registration/Stereo/include/otbStereoSensorModelToElevationMapFilter.txx index 355a0cc1474cff614643f4f20f2543005284ae8f..a755dd1622f14a26edc1aa15244486c49053602f 100644 --- a/Modules/Registration/Stereo/include/otbStereoSensorModelToElevationMapFilter.txx +++ b/Modules/Registration/Stereo/include/otbStereoSensorModelToElevationMapFilter.txx @@ -54,9 +54,6 @@ StereoSensorModelToElevationFilter<TInputImage, TOutputHeight> m_CorrelationThreshold = 0.7; m_VarianceThreshold = 4; m_SubtractInitialElevation = false; - - // DEM handling (deprecated) - m_UseDEM = false; } template <class TInputImage, class TOutputHeight> diff --git a/Modules/Remote/otb-bv.remote.cmake b/Modules/Remote/otb-bv.remote.cmake index 7249a0443e46dc7e04d0c2fb0aeaa745133f3e5a..4816ae226460fae6d54424daa86edad2e8888ddd 100644 --- a/Modules/Remote/otb-bv.remote.cmake +++ b/Modules/Remote/otb-bv.remote.cmake @@ -25,5 +25,5 @@ A more detailed description can be found on the project website: http://tully.ups-tlse.fr/jordi/otb-bv " GIT_REPOSITORY http://tully.ups-tlse.fr/jordi/otb-bv.git - GIT_TAG d13a3b3febe61c3c67777eac8261e07a6257a519 + GIT_TAG master ) diff --git a/Modules/Remote/phenotb.remote.cmake b/Modules/Remote/phenotb.remote.cmake index 4ffba060cf56583604e568cfbe92664b85d0ecff..d76b4f1cc1b30d88f22aab7c036e413eeaf4c068 100644 --- a/Modules/Remote/phenotb.remote.cmake +++ b/Modules/Remote/phenotb.remote.cmake @@ -27,5 +27,5 @@ A more detailed description can be found on the project website: http://tully.ups-tlse.fr/jordi/phenotb " GIT_REPOSITORY http://tully.ups-tlse.fr/jordi/phenotb.git - GIT_TAG 17d69b1bc1f23041dafe265e320b46ffb20229b6 + GIT_TAG master ) diff --git a/Modules/Remote/temporal-gapfilling.remote.cmake b/Modules/Remote/temporal-gapfilling.remote.cmake index 0ef5cd29ba0af30cda3e5de29d57efe219c8608b..5570ceee08dc704ed1ea8e5897db93d88e03d711 100644 --- a/Modules/Remote/temporal-gapfilling.remote.cmake +++ b/Modules/Remote/temporal-gapfilling.remote.cmake @@ -26,5 +26,5 @@ A more detailed description can be found on the project website: http://tully.ups-tlse.fr/jordi/temporalgapfilling " GIT_REPOSITORY http://tully.ups-tlse.fr/jordi/temporalgapfilling.git - GIT_TAG 14c56cb73250861d8694effeba934cebde09424c + GIT_TAG master ) diff --git a/Modules/ThirdParty/ITK/include/otbWarpImageFilter.h b/Modules/ThirdParty/ITK/include/otbWarpImageFilter.h deleted file mode 100644 index 247153984566475a8bd09bba0c151880ff1e5fe9..0000000000000000000000000000000000000000 --- a/Modules/ThirdParty/ITK/include/otbWarpImageFilter.h +++ /dev/null @@ -1,286 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef otbWarpImageFilter_h -#define otbWarpImageFilter_h -#include "itkImageBase.h" -#include "itkImageToImageFilter.h" -#include "itkLinearInterpolateImageFunction.h" -#include "itkPoint.h" - -namespace otb -{ - -/** \class WarpImageFilter - * \brief Warps an image using an input deformation field. - * - * WarpImageFilter warps an existing image with respect to - * a given deformation field. - * - * A deformation field is represented as a image whose pixel type is some - * vector type with at least N elements, where N is the dimension of - * the input image. The vector type must support element access via operator - * []. - * - * The output image is produced by inverse mapping: the output pixels - * are mapped back onto the input image. This scheme avoids the creation of - * any holes and overlaps in the output image. - * - * Each vector in the deformation field represent the distance between - * a geometric point in the input space and a point in the output space such - * that: - * - * \f[ p_{in} = p_{out} + d \f] - * - * Typically the mapped position does not correspond to an integer pixel - * position in the input image. Interpolation via an image function - * is used to compute values at non-integer positions. The default - * interpolation typed used is the LinearInterpolateImageFunction. - * The user can specify a particular interpolation function via - * SetInterpolator(). Note that the input interpolator must derive - * from base class InterpolateImageFunction. - * - * Position mapped to outside of the input image buffer are assigned - * a edge padding value. - * - * The LargetPossibleRegion for the output is inherited - * from the input deformation field. The output image - * spacing, origin and orientation may be set via - * SetOutputSpacing, SetOutputOrigin and - * SetOutputDirection. The default are respectively a - * vector of 1's, a vector of 0's and an identity matrix. - * - * This class is templated over the type of the input image, the - * type of the output image and the type of the deformation field. - * - * The input image is set via SetInput. The input deformation field - * is set via SetDisplacementField. - * - * This filter is implemented as a multithreaded filter. - * - * \warning This filter assumes that the input type, output type - * and deformation field type all have the same number of dimensions. - * - * \ingroup GeometricTransforms MultiThreaded Streamed - * - * \ingroup OTBITK - */ -template < - class TInputImage, - class TOutputImage, - class TDisplacementField - > -class ITK_EXPORT WarpImageFilter : - public itk::ImageToImageFilter<TInputImage, TOutputImage> -{ -public: - /** Standard class typedefs. */ - typedef WarpImageFilter Self; - typedef itk::ImageToImageFilter<TInputImage,TOutputImage> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - /** Run-time type information (and related methods) */ - itkTypeMacro( WarpImageFilter, ImageToImageFilter ); - - /** Typedef to describe the output image region type. */ - typedef typename TOutputImage::RegionType OutputImageRegionType; - - /** Inherit some types from the superclass. */ - typedef typename Superclass::InputImageType InputImageType; - typedef typename Superclass::InputImagePointer InputImagePointer; - typedef typename Superclass::OutputImageType OutputImageType; - typedef typename Superclass::OutputImagePointer OutputImagePointer; - typedef typename Superclass::InputImageConstPointer InputImageConstPointer; - typedef typename OutputImageType::IndexType IndexType; - typedef typename OutputImageType::IndexValueType IndexValueType; - typedef typename OutputImageType::SizeType SizeType; - typedef typename OutputImageType::PixelType PixelType; - typedef typename OutputImageType::SpacingType SpacingType; - - /** Determine the image dimension. */ - itkStaticConstMacro(ImageDimension, unsigned int, - TOutputImage::ImageDimension ); - itkStaticConstMacro(InputImageDimension, unsigned int, - TInputImage::ImageDimension ); - itkStaticConstMacro(DisplacementFieldDimension, unsigned int, - TDisplacementField::ImageDimension ); - /** typedef for base image type at the current ImageDimension */ - typedef itk::ImageBase<itkGetStaticConstMacro(ImageDimension)> ImageBaseType; - - /** Displacement field typedef support. */ - typedef TDisplacementField DisplacementFieldType; - typedef typename DisplacementFieldType::Pointer DisplacementFieldPointer; - typedef typename DisplacementFieldType::PixelType DisplacementType; - - /** Interpolator typedef support. */ - typedef double CoordRepType; - typedef itk::InterpolateImageFunction<InputImageType,CoordRepType> InterpolatorType; - typedef typename InterpolatorType::Pointer InterpolatorPointer; - typedef itk::LinearInterpolateImageFunction<InputImageType,CoordRepType> - DefaultInterpolatorType; - - /** Point type */ - typedef itk::Point<CoordRepType,itkGetStaticConstMacro(ImageDimension)> PointType; - - /** Type for representing the direction of the output image */ - typedef typename TOutputImage::DirectionType DirectionType; - - /** Set the deformation field. */ - void SetDisplacementField( const DisplacementFieldType * field ); - - /** Get a pointer the deformation field. */ - DisplacementFieldType * GetDisplacementField(void); - - /** Set the interpolator function. */ - itkSetObjectMacro( Interpolator, InterpolatorType ); - - /** Get a pointer to the interpolator function. */ - itkGetObjectMacro( Interpolator, InterpolatorType ); - - /** Set the output image spacing. */ - itkSetMacro(OutputSpacing, SpacingType); - virtual void SetOutputSpacing( const double* values); - - /** Get the output image spacing. */ - itkGetConstReferenceMacro(OutputSpacing, SpacingType); - - /** Set the output image origin. */ - itkSetMacro(OutputOrigin, PointType); - virtual void SetOutputOrigin( const double* values); - - /** Get the output image origin. */ - itkGetConstReferenceMacro(OutputOrigin, PointType); - - /** Set/Get the direction (orientation) of the output image */ - itkSetMacro(OutputDirection, DirectionType ); - itkGetConstReferenceMacro(OutputDirection, DirectionType ); - - /** Helper method to set the output parameters based on this image */ - void SetOutputParametersFromImage ( const ImageBaseType *image ); - - /** Set the start index of the output largest possible region. - * The default is an index of all zeros. */ - itkSetMacro( OutputStartIndex, IndexType ); - - /** Get the start index of the output largest possible region. */ - itkGetConstReferenceMacro( OutputStartIndex, IndexType ); - - /** Set the size of the output image. */ - itkSetMacro( OutputSize, SizeType ); - - /** Get the size of the output image. */ - itkGetConstReferenceMacro( OutputSize, SizeType ); - - /** Set the edge padding value */ - itkSetMacro( EdgePaddingValue, PixelType ); - - /** Get the edge padding value */ - itkGetConstMacro( EdgePaddingValue, PixelType ); - - /** WarpImageFilter produces an image which is a different - * size than its input image. As such, it needs to provide an - * implementation for GenerateOutputInformation() which set - * the output information according the OutputSpacing, OutputOrigin - * and the deformation field's LargestPossibleRegion. */ - void GenerateOutputInformation() ITK_OVERRIDE; - - /** It is difficult to compute in advance the input image region - * required to compute the requested output region. Thus the safest - * thing to do is to request for the whole input image. - * - * For the deformation field, the input requested region - * set to be the same as that of the output requested region. */ - void GenerateInputRequestedRegion() ITK_OVERRIDE; - - /** This method is used to set the state of the filter before - * multi-threading. */ - void BeforeThreadedGenerateData() ITK_OVERRIDE; - - /** This method is used to set the state of the filter after - * multi-threading. */ - void AfterThreadedGenerateData() ITK_OVERRIDE; - -#ifdef ITK_USE_CONCEPT_CHECKING - /** Begin concept checking */ - itkConceptMacro(SameDimensionCheck1, - (itk::Concept::SameDimension<ImageDimension, InputImageDimension>)); - itkConceptMacro(SameDimensionCheck2, - (itk::Concept::SameDimension<ImageDimension, DisplacementFieldDimension>)); - /** itkConceptMacro(InputHasNumericTraitsCheck, - (Concept::HasNumericTraits<typename TInputImage::PixelType>)); */ - itkConceptMacro(DisplacementFieldHasNumericTraitsCheck, - (itk::Concept::HasNumericTraits<typename TDisplacementField::PixelType::ValueType>)); - /** End concept checking */ -#endif - -protected: - WarpImageFilter(); - ~WarpImageFilter() ITK_OVERRIDE {}; - void PrintSelf(std::ostream& os, itk::Indent indent) const ITK_OVERRIDE; - - /** WarpImageFilter is implemented as a multi-threaded filter. - * As such, it needs to provide and implementation for - * ThreadedGenerateData(). */ - void ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, - itk::ThreadIdType threadId ) ITK_OVERRIDE; - - /** Override VerifyInputInformation() since this filter's inputs do - * not need to occupy the same physical space. - * - * \sa ProcessObject::VerifyInputInformation - */ - void VerifyInputInformation() ITK_OVERRIDE {} - -private: - - WarpImageFilter(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - - /** This function should be in an interpolator but none of the ITK - * interpolators at this point handle edge conditions properly - */ - DisplacementType EvaluateDisplacementAtPhysicalPoint(const PointType &p, const DisplacementFieldType *fieldPtr); - - PixelType m_EdgePaddingValue; - SpacingType m_OutputSpacing; - PointType m_OutputOrigin; - DirectionType m_OutputDirection; - - InterpolatorPointer m_Interpolator; - SizeType m_OutputSize; // Size of the output image - IndexType m_OutputStartIndex; // output image start index - bool m_DefFieldSizeSame; - // variables for deffield interpoator - IndexType m_StartIndex,m_EndIndex; - - -}; - -} // end namespace otb - -#ifndef OTB_MANUAL_INSTANTIATION -#include "otbWarpImageFilter.txx" -#endif - -#endif diff --git a/Modules/ThirdParty/ITK/include/otbWarpImageFilter.txx b/Modules/ThirdParty/ITK/include/otbWarpImageFilter.txx deleted file mode 100644 index 1cb3955caf61be8b735e173d12fb6ba08c988456..0000000000000000000000000000000000000000 --- a/Modules/ThirdParty/ITK/include/otbWarpImageFilter.txx +++ /dev/null @@ -1,473 +0,0 @@ -/* - * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) - * - * This file is part of Orfeo Toolbox - * - * https://www.orfeo-toolbox.org/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef otbWarpImageFilter_txx -#define otbWarpImageFilter_txx -#include "otbWarpImageFilter.h" - -#include "itkImageRegionIterator.h" -#include "itkImageRegionIteratorWithIndex.h" -#include "itkProgressReporter.h" -#include "itkContinuousIndex.h" -#include "vnl/vnl_math.h" - -#include "itkVariableLengthVector.h" - -namespace otb -{ - -template <class PixelType> unsigned int PixelSizeFinder(itk::VariableLengthVector<PixelType> pix) -{ - return pix.Size(); -} -template <class PixelType> unsigned int PixelSizeFinder(PixelType itkNotUsed(pix)) -{ - return PixelType::Dimension; -} - -/** - * Default constructor. - */ -template <class TInputImage,class TOutputImage,class TDisplacementField> -WarpImageFilter<TInputImage,TOutputImage,TDisplacementField> -::WarpImageFilter() -{ - // Setup the number of required inputs - this->SetNumberOfRequiredInputs( 2 ); - - // Setup default values - m_OutputSpacing.Fill( 1.0 ); - m_OutputOrigin.Fill( 0.0 ); - m_OutputDirection.SetIdentity(); - m_OutputSize.Fill(0); - itk::NumericTraits<PixelType>::SetLength(m_EdgePaddingValue, 1); - m_OutputStartIndex.Fill(0); - // Setup default interpolator - typename DefaultInterpolatorType::Pointer interp = - DefaultInterpolatorType::New(); - - m_Interpolator = - static_cast<InterpolatorType*>( interp.GetPointer() ); -} - -/** - * Standard PrintSelf method. - */ -template <class TInputImage,class TOutputImage,class TDisplacementField> -void -WarpImageFilter<TInputImage,TOutputImage,TDisplacementField> -::PrintSelf(std::ostream& os, itk::Indent indent) const -{ - - Superclass::PrintSelf(os, indent); - - os << indent << "OutputSpacing: " << m_OutputSpacing << std::endl; - os << indent << "OutputOrigin: " << m_OutputOrigin << std::endl; - os << indent << "OutputDirection: " << m_OutputDirection << std::endl; - os << indent << "OutputSize: " << m_OutputSize << std::endl; - os << indent << "OutputStartIndex: " << m_OutputStartIndex << std::endl; - os << indent << "EdgePaddingValue: " - << static_cast<typename itk::NumericTraits<PixelType>::PrintType>(m_EdgePaddingValue) - << std::endl; - os << indent << "Interpolator: " << m_Interpolator.GetPointer() << std::endl; - -} - - -/** - * Set the output image spacing. - * - */ -template <class TInputImage,class TOutputImage,class TDisplacementField> -void -WarpImageFilter<TInputImage,TOutputImage,TDisplacementField> -::SetOutputSpacing( - const double* spacing) -{ - SpacingType s(spacing); - this->SetOutputSpacing( s ); -} - - -/** - * Set the output image origin. - * - */ -template <class TInputImage,class TOutputImage,class TDisplacementField> -void -WarpImageFilter<TInputImage,TOutputImage,TDisplacementField> -::SetOutputOrigin( - const double* origin) -{ - PointType p(origin); - this->SetOutputOrigin(p); -} - -/** Helper method to set the output parameters based on this image */ -template <class TInputImage,class TOutputImage,class TDisplacementField> -void -WarpImageFilter<TInputImage,TOutputImage,TDisplacementField> -::SetOutputParametersFromImage ( const ImageBaseType * image ) -{ - this->SetOutputOrigin ( image->GetOrigin() ); - this->SetOutputSpacing ( image->GetSpacing() ); - this->SetOutputDirection ( image->GetDirection() ); - this->SetOutputStartIndex ( image->GetLargestPossibleRegion().GetIndex() ); - this->SetOutputSize ( image->GetLargestPossibleRegion().GetSize() ); -} - -/** - * Set deformation field as Inputs[1] for this ProcessObject. - * - */ -template <class TInputImage,class TOutputImage,class TDisplacementField> -void -WarpImageFilter<TInputImage,TOutputImage,TDisplacementField> -::SetDisplacementField( - const DisplacementFieldType * field ) -{ - // const cast is needed because the pipeline is not const-correct. - DisplacementFieldType * input = - const_cast< DisplacementFieldType * >( field ); - this->itk::ProcessObject::SetNthInput( 1, input ); -} - - -/** - * Return a pointer to the deformation field. - */ -template <class TInputImage,class TOutputImage,class TDisplacementField> -typename WarpImageFilter<TInputImage,TOutputImage,TDisplacementField> -::DisplacementFieldType * -WarpImageFilter<TInputImage,TOutputImage,TDisplacementField> -::GetDisplacementField(void) -{ - return static_cast<DisplacementFieldType *> - ( this->itk::ProcessObject::GetInput( 1 )); -} - - -/** - * Setup state of filter before multi-threading. - * InterpolatorType::SetInputImage is not thread-safe and hence - * has to be setup before ThreadedGenerateData - */ -template <class TInputImage,class TOutputImage,class TDisplacementField> -void -WarpImageFilter<TInputImage,TOutputImage,TDisplacementField> -::BeforeThreadedGenerateData() -{ - - if( !m_Interpolator ) - { - itkExceptionMacro(<< "Interpolator not set"); - } - DisplacementFieldPointer fieldPtr = this->GetDisplacementField(); - - // Connect input image to interpolator - m_Interpolator->SetInputImage( this->GetInput() ); - typename DisplacementFieldType::RegionType defRegion = - fieldPtr->GetLargestPossibleRegion(); - typename OutputImageType::RegionType outRegion = - this->GetOutput()->GetLargestPossibleRegion(); - m_DefFieldSizeSame = outRegion == defRegion; - if(!m_DefFieldSizeSame) - { - m_StartIndex = fieldPtr->GetBufferedRegion().GetIndex(); - for(unsigned i = 0; i < ImageDimension; i++) - { - m_EndIndex[i] = m_StartIndex[i] + - fieldPtr->GetBufferedRegion().GetSize()[i] - 1; - } - } -} - -/** - * Setup state of filter after multi-threading. - */ -template <class TInputImage,class TOutputImage,class TDisplacementField> -void -WarpImageFilter<TInputImage,TOutputImage,TDisplacementField> -::AfterThreadedGenerateData() -{ - // Disconnect input image from interpolator - m_Interpolator->SetInputImage( ITK_NULLPTR ); -} - - -template <class TInputImage,class TOutputImage,class TDisplacementField> -typename WarpImageFilter<TInputImage, - TOutputImage, - TDisplacementField>::DisplacementType -WarpImageFilter<TInputImage,TOutputImage,TDisplacementField> -::EvaluateDisplacementAtPhysicalPoint(const PointType &point, const DisplacementFieldType *fieldPtr) -{ - itk::ContinuousIndex<double,ImageDimension> index; - fieldPtr->TransformPhysicalPointToContinuousIndex(point,index); - unsigned int dim; // index over dimension - /** - * Compute base index = closest index below point - * Compute distance from point to base index - */ - IndexType baseIndex; - IndexType neighIndex; - double distance[ImageDimension]; - - for( dim = 0; dim < ImageDimension; dim++ ) - { - baseIndex[dim] = itk::Math::Floor< IndexValueType >( index[dim] ); - - if( baseIndex[dim] >= m_StartIndex[dim] ) - { - if( baseIndex[dim] < m_EndIndex[dim] ) - { - distance[dim] = index[dim] - static_cast<double>( baseIndex[dim] ); - } - else - { - baseIndex[dim] = m_EndIndex[dim]; - distance[dim] = 0.0; - } - } - else - { - baseIndex[dim] = m_StartIndex[dim]; - distance[dim] = 0.0; - } - } - - /** - * Interpolated value is the weight some of each of the surrounding - * neighbors. The weight for each neighbour is the fraction overlap - * of the neighbor pixel with respect to a pixel centered on point. - */ - DisplacementType output; - output.Fill(0); - - double totalOverlap = 0.0; - unsigned int numNeighbors(1 << TInputImage::ImageDimension); - - for( unsigned int counter = 0; counter < numNeighbors; counter++ ) - { - double overlap = 1.0; // fraction overlap - unsigned int upper = counter; // each bit indicates upper/lower neighbour - - // get neighbor index and overlap fraction - for( dim = 0; dim < ImageDimension; dim++ ) - { - - if( upper & 1 ) - { - neighIndex[dim] = baseIndex[dim] + 1; - overlap *= distance[dim]; - } - else - { - neighIndex[dim] = baseIndex[dim]; - overlap *= 1.0 - distance[dim]; - } - - upper >>= 1; - - } - - // get neighbor value only if overlap is not zero - if( overlap ) - { - const DisplacementType input = - fieldPtr->GetPixel( neighIndex ); - for(unsigned int k = 0; k < otb::PixelSizeFinder(input); k++ ) - { - output[k] += overlap * static_cast<double>( input[k] ); - } - totalOverlap += overlap; - } - - if( totalOverlap == 1.0 ) - { - // finished - break; - } - - } - return ( output ); -} - -/** - * Compute the output for the region specified by outputRegionForThread. - */ -template <class TInputImage,class TOutputImage,class TDisplacementField> -void -WarpImageFilter<TInputImage,TOutputImage,TDisplacementField> -::ThreadedGenerateData( - const OutputImageRegionType& outputRegionForThread, - itk::ThreadIdType threadId ) -{ - - InputImageConstPointer inputPtr = this->GetInput(); - OutputImagePointer outputPtr = this->GetOutput(); - DisplacementFieldPointer fieldPtr = this->GetDisplacementField(); - - // support progress methods/callbacks - itk::ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels()); - - // iterator for the output image - itk::ImageRegionIteratorWithIndex<OutputImageType> outputIt( - outputPtr, outputRegionForThread ); - IndexType index; - PointType point; - DisplacementType displacement; - if(this->m_DefFieldSizeSame) - { - // iterator for the deformation field - itk::ImageRegionIterator<DisplacementFieldType> - fieldIt(fieldPtr, outputRegionForThread ); - - while( !outputIt.IsAtEnd() ) - { - // get the output image index - index = outputIt.GetIndex(); - outputPtr->TransformIndexToPhysicalPoint( index, point ); - - // get the required displacement - displacement = fieldIt.Get(); - - // compute the required input image point - for(unsigned int j = 0; j < ImageDimension; j++ ) - { - point[j] += displacement[j]; - } - - // get the interpolated value - if( m_Interpolator->IsInsideBuffer( point ) ) - { - PixelType value = - static_cast<PixelType>(m_Interpolator->Evaluate( point ) ); - outputIt.Set( value ); - } - else - { - outputIt.Set( m_EdgePaddingValue ); - } - ++outputIt; - ++fieldIt; - progress.CompletedPixel(); - } - } - else - { - while( !outputIt.IsAtEnd() ) - { - // get the output image index - index = outputIt.GetIndex(); - outputPtr->TransformIndexToPhysicalPoint( index, point ); - - displacement = this->EvaluateDisplacementAtPhysicalPoint( point, fieldPtr ); - // compute the required input image point - for(unsigned int j = 0; j < ImageDimension; j++ ) - { - point[j] += displacement[j]; - } - - // get the interpolated value - if( m_Interpolator->IsInsideBuffer( point ) ) - { - PixelType value = - static_cast<PixelType>(m_Interpolator->Evaluate( point ) ); - outputIt.Set( value ); - } - else - { - outputIt.Set( m_EdgePaddingValue ); - } - ++outputIt; - progress.CompletedPixel(); - } - } -} - - -template <class TInputImage,class TOutputImage,class TDisplacementField> -void -WarpImageFilter<TInputImage,TOutputImage,TDisplacementField> -::GenerateInputRequestedRegion() -{ - - // call the superclass's implementation - Superclass::GenerateInputRequestedRegion(); - - // request the largest possible region for the input image - InputImagePointer inputPtr = - const_cast< InputImageType * >( this->GetInput() ); - - if( inputPtr ) - { - inputPtr->SetRequestedRegionToLargestPossibleRegion(); - } - - // just propagate up the output requested region for the - // deformation field. - DisplacementFieldPointer fieldPtr = this->GetDisplacementField(); - OutputImagePointer outputPtr = this->GetOutput(); - if(fieldPtr.IsNotNull() ) - { - fieldPtr->SetRequestedRegion( outputPtr->GetRequestedRegion() ); - if(!fieldPtr->VerifyRequestedRegion()) - { - fieldPtr->SetRequestedRegion(fieldPtr->GetLargestPossibleRegion()); - } - } -} - - -template <class TInputImage,class TOutputImage,class TDisplacementField> -void -WarpImageFilter<TInputImage,TOutputImage,TDisplacementField> -::GenerateOutputInformation() -{ - // call the superclass's implementation of this method - Superclass::GenerateOutputInformation(); - - OutputImagePointer outputPtr = this->GetOutput(); - - outputPtr->SetSpacing( m_OutputSpacing ); - outputPtr->SetOrigin( m_OutputOrigin ); - outputPtr->SetDirection( m_OutputDirection ); - - DisplacementFieldPointer fieldPtr = this->GetDisplacementField(); - if( this->m_OutputSize[0] == 0 && - fieldPtr.IsNotNull()) - { - outputPtr->SetLargestPossibleRegion( fieldPtr-> - GetLargestPossibleRegion() ); - } - else - { - OutputImageRegionType region; - region.SetSize(this->m_OutputSize); - region.SetIndex(this->m_OutputStartIndex); - outputPtr->SetLargestPossibleRegion(region); - } -} - - -} // end namespace otb - -#endif diff --git a/Modules/Visualization/Monteverdi/src/mvdMainWindow.cxx b/Modules/Visualization/Monteverdi/src/mvdMainWindow.cxx index fada47696774b0d1bc6faaef8213a0abf146808a..84f7085b12557fd24f2d79a448ea5799071c3294 100644 --- a/Modules/Visualization/Monteverdi/src/mvdMainWindow.cxx +++ b/Modules/Visualization/Monteverdi/src/mvdMainWindow.cxx @@ -2515,8 +2515,8 @@ MainWindow text = tr( "(%1 %2 ; %3 %4 ; %5)" ) - .arg( wgs84[ 0 ]>=0.0 ? "N" : "S" ).arg( fabs( wgs84[ 1 ] ) ) - .arg( wgs84[ 1 ]>=0.0 ? "E" : "W" ).arg( fabs( wgs84[ 0 ] ) ) + .arg( wgs84[ 1 ]>=0.0 ? "N" : "S" ).arg( fabs( wgs84[ 1 ] ) ) + .arg( wgs84[ 0 ]>=0.0 ? "E" : "W" ).arg( fabs( wgs84[ 0 ] ) ) .arg( alt ); } diff --git a/Modules/Visualization/MonteverdiGui/include/mvdStatusBarWidget.h b/Modules/Visualization/MonteverdiGui/include/mvdStatusBarWidget.h index 714a100883da50fc0dad696e9b29a8ea4739e8b7..6ff51de45d94a3a60c3d4a89471e3d4d28f6ccd1 100644 --- a/Modules/Visualization/MonteverdiGui/include/mvdStatusBarWidget.h +++ b/Modules/Visualization/MonteverdiGui/include/mvdStatusBarWidget.h @@ -161,6 +161,11 @@ private: */ Ui::StatusBarWidget * m_UI; + /** + * \brief Change the scale when scaleLineEdit is pressed or editing is finished with change. + */ + void ChangeScale(); + /*-[ PRIVATE SLOTS SECTION ]-----------------------------------------------*/ // @@ -175,6 +180,9 @@ private slots: /** */ void on_pixelIndexLineEdit_returnPressed(); + /** + */ + void on_scaleLineEdit_returnPressed(); }; } // end namespace 'mvd' diff --git a/Modules/Visualization/MonteverdiGui/src/mvdStatusBarWidget.cxx b/Modules/Visualization/MonteverdiGui/src/mvdStatusBarWidget.cxx index 358bc123cf9450e7ceb5fa881fc5317342a6dae1..6091f79e077190b7a0d00e963f3643b6bd0eb11e 100644 --- a/Modules/Visualization/MonteverdiGui/src/mvdStatusBarWidget.cxx +++ b/Modules/Visualization/MonteverdiGui/src/mvdStatusBarWidget.cxx @@ -217,9 +217,26 @@ StatusBarWidget } /*****************************************************************************/ +void +StatusBarWidget +::on_scaleLineEdit_returnPressed() +{ + ChangeScale(); +} + void StatusBarWidget ::on_scaleLineEdit_editingFinished() +{ + if(m_UI->scaleLineEdit->isModified()) + { + ChangeScale(); + } +} + +void +StatusBarWidget +::ChangeScale() { // // Cancel if scale text is empty. diff --git a/Modules/Wrappers/ApplicationEngine/include/otbWrapperInputImageParameter.txx b/Modules/Wrappers/ApplicationEngine/include/otbWrapperInputImageParameter.txx index b60be0d0230b40ad01653b60fbbbe753e411d282..f8aa185cedefc55657c3cbc98c2fa6abdf78f72b 100644 --- a/Modules/Wrappers/ApplicationEngine/include/otbWrapperInputImageParameter.txx +++ b/Modules/Wrappers/ApplicationEngine/include/otbWrapperInputImageParameter.txx @@ -178,7 +178,7 @@ template <class TInputImage, class TOutputImage> TOutputImage* InputImageParameter::CastImage() { - itkExceptionMacro("Cast from "<<typeid(TInputImage).name()<<" to "<<typeid(TInputImage).name()<<" not authorized."); + itkExceptionMacro("Cast from "<<typeid(TInputImage).name()<<" to "<<typeid(TOutputImage).name()<<" not authorized."); } diff --git a/Modules/Wrappers/ApplicationEngine/src/otbWrapperMapProjectionParametersHandler.cxx b/Modules/Wrappers/ApplicationEngine/src/otbWrapperMapProjectionParametersHandler.cxx index 8c00e08c56cc8a22971a4b69aa2bcc635e5dd9ee..364fb600359f0964f7d4b35a99e5a8bb0e63c0ec 100644 --- a/Modules/Wrappers/ApplicationEngine/src/otbWrapperMapProjectionParametersHandler.cxx +++ b/Modules/Wrappers/ApplicationEngine/src/otbWrapperMapProjectionParametersHandler.cxx @@ -134,8 +134,8 @@ const std::string MapProjectionParametersHandler::GetProjectionRefFromChoice(con { case Map_Utm: { - typedef UtmInverseProjection UtmProjectionType; - UtmProjectionType::Pointer utmProjection = UtmProjectionType::New(); + otb::UtmInverseProjection::Pointer utmProjection = + otb::UtmInverseProjection::New(); // Set the zone utmProjection->SetZone(app->GetParameterInt(zoneKey.str())); @@ -152,15 +152,15 @@ const std::string MapProjectionParametersHandler::GetProjectionRefFromChoice(con break; case Map_Lambert2: { - typedef Lambert2EtenduForwardProjection Lambert2ProjectionType; - Lambert2ProjectionType::Pointer lambert2Projection = Lambert2ProjectionType::New(); + otb::Lambert2EtenduForwardProjection::Pointer lambert2Projection = + otb::Lambert2EtenduForwardProjection::New(); return lambert2Projection->GetWkt(); } break; case Map_Lambert93: { - typedef otb::Lambert93InverseProjection Lambert93ProjectionType; - Lambert93ProjectionType::Pointer lambert93Projection = Lambert93ProjectionType::New(); + otb::Lambert93InverseProjection::Pointer lambert93Projection = + otb::Lambert93InverseProjection::New(); return lambert93Projection->GetWkt(); } break; diff --git a/Modules/Wrappers/CommandLine/include/otbWrapperCommandLineLauncher.h b/Modules/Wrappers/CommandLine/include/otbWrapperCommandLineLauncher.h index 06220687cf0d516c974a31c6556e31334e70f926..36b0b0de538b3e8362eb558f66186557c662a317 100644 --- a/Modules/Wrappers/CommandLine/include/otbWrapperCommandLineLauncher.h +++ b/Modules/Wrappers/CommandLine/include/otbWrapperCommandLineLauncher.h @@ -118,12 +118,6 @@ protected: /** Constructor */ CommandLineLauncher(); - /** \deprecated - * Constructor with exp argument is deprecated because class - * CommandLineLauncher does not have expression attribute anymore. Use instead the - * default constructor. It is included for backwards compatibility. */ - CommandLineLauncher(const char * exp); - /** Destructor */ ~CommandLineLauncher() ITK_OVERRIDE; diff --git a/Modules/Wrappers/CommandLine/src/otbApplicationLauncherCommandLine.cxx b/Modules/Wrappers/CommandLine/src/otbApplicationLauncherCommandLine.cxx index 6250dbc1983e2dde2d17994c74280a43fac8fb15..c684158fccf30be7fa54c11ddd20343cc141f96d 100644 --- a/Modules/Wrappers/CommandLine/src/otbApplicationLauncherCommandLine.cxx +++ b/Modules/Wrappers/CommandLine/src/otbApplicationLauncherCommandLine.cxx @@ -306,13 +306,13 @@ int main(int argc, char* argv[]) LauncherType::Pointer launcher = LauncherType::New(); //if (launcher->Load(exp) == true) - bool sucess = launcher->Load(vexp) && launcher->ExecuteAndWriteOutput(); + bool success = launcher->Load(vexp) && launcher->ExecuteAndWriteOutput(); // shutdown MPI after application finished #ifdef OTB_USE_MPI otb::MPIConfig::Instance()->terminate(); #endif - return sucess ? EXIT_SUCCESS : EXIT_FAILURE; + return success ? EXIT_SUCCESS : EXIT_FAILURE; } const std::string GetChildNodeTextOf(TiXmlElement *parentElement, std::string key) diff --git a/Modules/Wrappers/CommandLine/src/otbWrapperCommandLineLauncher.cxx b/Modules/Wrappers/CommandLine/src/otbWrapperCommandLineLauncher.cxx index 0ad102b08e36b3d72de28354d8f90a99e78061e8..f25b914587791a67a54460821c1fdb14817bd4e2 100644 --- a/Modules/Wrappers/CommandLine/src/otbWrapperCommandLineLauncher.cxx +++ b/Modules/Wrappers/CommandLine/src/otbWrapperCommandLineLauncher.cxx @@ -67,13 +67,6 @@ CommandLineLauncher::CommandLineLauncher() : m_AddProcessCommand->SetCallbackFunction(this, &CommandLineLauncher::LinkWatchers); } -CommandLineLauncher::CommandLineLauncher(const char *) /*: - m_Expression(exp)*/ -{ - m_Application = ITK_NULLPTR; - m_Parser = CommandLineParser::New(); -} - CommandLineLauncher::~CommandLineLauncher() { this->DeleteWatcherList(); diff --git a/Utilities/Maintenance/fix_typos.sh b/Utilities/Maintenance/fix_typos.sh index 7e427029e156b8dba8c11d1671fa850a6d3485f6..f70e52e25db84ada8b94190687b6401163ccf2a2 100755 --- a/Utilities/Maintenance/fix_typos.sh +++ b/Utilities/Maintenance/fix_typos.sh @@ -54,20 +54,8 @@ EXCLUDED_FILES="$EXCLUDED_FILES,*/Utilities/Maintenance/fix_typos.sh,*/fix_typos #This list should be updated after each release when deprecated classes/methods are removed # use with --words-white-list=$WORDS_WHITE_LIST -#for deprecated class AssymmetricFusionOfLineDetectorImageFilter -WORDS_WHITE_LIST="Assymmetric" -#for deprecated method InstanciateProjection in multiple classes -WORDS_WHITE_LIST="$WORDS_WHITE_LIST,Instanciate" -#for deprecated method DoFinalizeInitialisation in otbGeometriesToGeometriesFilter.h -WORDS_WHITE_LIST="$WORDS_WHITE_LIST,Initialisation" -#for deprecated method getSubstraction -WORDS_WHITE_LIST="$WORDS_WHITE_LIST,Substraction" -#for deprecated method ParseFileNameForAdditonalInfo -WORDS_WHITE_LIST="$WORDS_WHITE_LIST,Additonal" # for "Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France" in LabelMapToLabelImageFilter -WORDS_WHITE_LIST="$WORDS_WHITE_LIST,Developement" -# for deprecated method GetShrinkedOutput in otbStreamingShrinkImageFilter -WORDS_WHITE_LIST="$WORDS_WHITE_LIST,Shrinked" +WORDS_WHITE_LIST="Developement" # for dum variable in prosail WORDS_WHITE_LIST="$WORDS_WHITE_LIST,dum" # for pary variable