diff --git a/Code/IO/CMakeLists.txt b/Code/IO/CMakeLists.txt index ca46f119444a0b711fe12966dd636e10bacbaa59..c678c371d324cea979272d5fe9ea03e00b0b835e 100644 --- a/Code/IO/CMakeLists.txt +++ b/Code/IO/CMakeLists.txt @@ -11,11 +11,6 @@ IF(NOT OTB_COMPILE_JPEG2000) ADD_DEFINITIONS(-DOTB_JPEG2000_DISABLED) ENDIF(NOT OTB_COMPILE_JPEG2000) -IF( NOT OTB_USE_CURL ) - LIST(REMOVE_ITEM OTBIO_SRCS "${CMAKE_CURRENT_SOURCE_DIR}/otbTileMapFetcher.cxx" ) -ENDIF( NOT OTB_USE_CURL ) - - # otbopenjpeg IF(OTB_COMPILE_JPEG2000) IF(WIN32) @@ -69,11 +64,6 @@ IF(NOT OTB_INSTALL_NO_DEVELOPMENT) FILE(GLOB __files1 "${CMAKE_CURRENT_SOURCE_DIR}/*.h") FILE(GLOB __files2 "${CMAKE_CURRENT_SOURCE_DIR}/*.txx") - IF( NOT OTB_USE_CURL ) - LIST(REMOVE_ITEM __files1 "${CMAKE_CURRENT_SOURCE_DIR}/otbTileMapFetcher.h" ) - ENDIF( NOT OTB_USE_CURL ) - - IF(NOT OTB_COMPILE_JPEG2000) LIST(REMOVE_ITEM __files1 "${CMAKE_CURRENT_SOURCE_DIR}/otbJpeg2000ImageIOFactory.h" ) LIST(REMOVE_ITEM __files1 "${CMAKE_CURRENT_SOURCE_DIR}/otbJpeg2000ImageIO.h" ) diff --git a/Code/IO/otbGDALImageIO.cxx b/Code/IO/otbGDALImageIO.cxx index b2eb559ac0c5c66d0b0e48445a7d816f9c368dcb..0cb544d97e47f9750551c08d13aafd1f32659107 100644 --- a/Code/IO/otbGDALImageIO.cxx +++ b/Code/IO/otbGDALImageIO.cxx @@ -1110,7 +1110,6 @@ std::string GDALImageIO::TypeConversion(std::string name) //Pas JPEG car BUG !! // else if ((extension=="jpg")||(extension=="JPG")||(extension=="jpeg")||(extension=="JPEG")) // extGDAL="JPEG"; - else if ((extension=="pix")||(extension=="PIX")) extGDAL="PCIDSK"; else extGDAL = "NOT-FOUND"; return extGDAL; } diff --git a/Code/IO/otbTileMapFetcher.cxx b/Code/IO/otbTileMapFetcher.cxx deleted file mode 100644 index e1cae3bd8dfb00e502a3a1e487bd7bb79e1b4687..0000000000000000000000000000000000000000 --- a/Code/IO/otbTileMapFetcher.cxx +++ /dev/null @@ -1,573 +0,0 @@ -/*========================================================================= - - Program: ORFEO Toolbox - Language: C++ - Date: $Date$ - Version: $Revision$ - - - Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. - See OTBCopyright.txt for details. - - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ - -#include "otbTileMapFetcher.h" -#include "itkImageFileReader.h" - -namespace otb -{ -/** Constructor */ -TileMapFetcher::TileMapFetcher() -{ - // Set server name - m_ServerName = ""; - - // Set Extension - m_FileSuffix = ".png"; - - // Set Cache size - m_CacheSize = 100; - - // Set cache directory - m_CacheDirectory = ""; - - // Set coordinates - m_X = 0; - m_Y = 0; - m_Z = 1; - - // Generate Logo tile - this->GenerateLogoTile(); -} - -/** Destructor */ -TileMapFetcher::~TileMapFetcher() -{ - // Remove all tiles in cache directory - this->UnregisterAllCachedTiles(); -} - -/** FetchTile */ -TileMapFetcher::ImagePointerType TileMapFetcher::FetchTile(unsigned int x, unsigned int y, unsigned int z) -{ - bool isInCache = false; - bool fetchingIsOK = true; - - /* Set coordinates */ - m_X = x; - m_Y = y; - m_Z = z; - - /* Create filename */ - this->GenerateFileName(); - - /* Check if tile is in cache */ - isInCache = this->IsTileInCache(); - - /* Fetch tile from web (check if local tile is out to date) */ - if (!isInCache) - { - // If fetching is ok - if (this->FetchTileFromServer()) - { - fetchingIsOK = true; - // Register tile in cache - this->RegisterTileInCache(); - } - else - { - // Else get tile from cache - fetchingIsOK = false; - } - - } - - /* fetch tile from cache */ - return (this->ReadTileFromCache(fetchingIsOK)); -} - -/** Fetch Tile from Server and set it in cache */ -bool TileMapFetcher::FetchTileFromServer() -{ - bool result = false; - - // Path and filename for this tile - std::ostringstream pathAndFileName; - - pathAndFileName << m_CacheDirectory; - - if (m_CacheDirectory.at(m_CacheDirectory.size() - 1) != '/') pathAndFileName << "/"; - - pathAndFileName << m_FileName; - - // Open file - FILE* output_file = fopen(pathAndFileName.str().c_str(), "w"); - if (output_file == NULL) - { - itkExceptionMacro(<< "FetchTileFromServer : bad file name."); - return result; - } - - // Browser type - std::ostringstream browserStream; - browserStream << "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-GB; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11"; - - // Init curl - CURL * curl; - CURLcode res; - curl = curl_easy_init(); - - // Generate URL - this->GenerateOSMurl(); - - if (m_OsmUrl == "") - { - itkExceptionMacro(<< "FetchTileFromServer : bad url."); - return false; - } - - char url[200]; - strcpy(url, m_OsmUrl.data()); - - char browser[200]; - strcpy(browser, browserStream.str().data()); - - //Download the file - if (curl) - { - curl_easy_setopt(curl, CURLOPT_USERAGENT, browser); - curl_easy_setopt(curl, CURLOPT_URL, url); - curl_easy_setopt(curl, CURLOPT_WRITEDATA, output_file); - res = curl_easy_perform(curl); - - // If res != 0 there is a problem while downloading (connection error) - if (res != 0) - { - // Close and remove file in cache - fclose(output_file); - if (remove(pathAndFileName.str().c_str()) != 0) - { - itkDebugMacro(<< "FetchTileFromServer : transfert error - Error while deleting tile in cache!"); - } - itkDebugMacro(<< "FetchTileFromServer : transfert error."); - return false; - } - // Else download was proceed - else - { - // Get error code - int code; - curl_easy_getinfo(curl, CURLINFO_HTTP_CODE, &code); - - // 404 Error (not found) - if (code == 404) - { - // Close and remove file in cache - fclose(output_file); - if (remove(pathAndFileName.str().c_str()) != 0) - { - itkDebugMacro(<< "FetchTileFromServer : HTTP Error 404 - Error while deleting tile in cache!"); - } - itkDebugMacro(<< "FetchTileFromServer : HTTP Error 404"); - return false; - } - // Tile is ok - else - { - result = true; - } - } - } - // close file - fclose(output_file); - // Cleanup curl - curl_easy_cleanup(curl); - return result; -} - -/** Generate Tile FileName */ -void TileMapFetcher::GenerateFileName() -{ - std::string server = m_ServerName.substr(7, m_ServerName.size()); // Get online server name without "http://" - - // replace "/" by "_" in server name - for (unsigned int i = 0; i < server.size(); i++) - { - if (server[i] == '/') server[i] = '_'; - } - - std::ostringstream filename; - - // Generate file name : serverName_Z_X_Y.png - filename << server; - filename << m_Z; - filename << "_"; - filename << m_X; - filename << "_"; - filename << m_Y; - filename << m_FileSuffix; - - m_FileName = filename.str(); -} - -/** Generate OSM url */ -void TileMapFetcher::GenerateOSMurl() -{ - /* Check server name */ - if (m_ServerName[0] != 'h' - || m_ServerName[1] != 't' - || m_ServerName[2] != 't' - || m_ServerName[3] != 'p') - { - itkExceptionMacro(<< "Bad server name!"); - } - - /* Generate urlStream */ - std::ostringstream urlStream; - - urlStream << m_ServerName; - if (m_ServerName.at(m_ServerName.size() - 1) != '/') urlStream << "/"; - urlStream << m_Z; - urlStream << "/"; - urlStream << m_X; - urlStream << "/"; - urlStream << m_Y; - urlStream << m_FileSuffix; - - m_OsmUrl = urlStream.str(); -} - -/** Check if tile is in cache */ -bool TileMapFetcher::IsTileInCache() -{ - bool result = false; - - // First if filename exists - if (m_FileName == "") - { - itkDebugMacro(<< "No filename specified."); - return result; - } - - std::deque<otb::TileRecord>::iterator it; - - // Search tile with its filename - for (it = m_CacheManagement.begin(); it != m_CacheManagement.end(); it++) - { - if (it->GetFileName() == m_FileName) - { - result = true; - break; - } - } - return result; -} - -/** Register Tile in cache */ -bool TileMapFetcher::RegisterTileInCache() -{ - otb::TileRecord tr; - - // Configure Record - tr.SetFileName(m_FileName); - tr.SetDate(); - - if (m_CacheManagement.size() > m_CacheSize) - { - this->UnregisterFirstCachedTile(); - } - - // Add record in deque - m_CacheManagement.push_back(tr); - - return true; -} - -/** Unregister Cached Tile */ -bool TileMapFetcher::UnregisterFirstCachedTile() -{ - std::deque<otb::TileRecord>::iterator it; - - it = m_CacheManagement.begin(); - - // Filename of the first input tile - std::string filename = it->GetFileName(); - - // Generate path and filename - std::ostringstream pathAndFileName; - - pathAndFileName << m_CacheDirectory; - - if (m_CacheDirectory.at(m_CacheDirectory.size() - 1) != '/') pathAndFileName << "/"; - - pathAndFileName << filename; - - // Remove tile in deque - m_CacheManagement.pop_front(); - - // Remove tile file on hard drive - if (remove(pathAndFileName.str().c_str()) != 0) - { - itkDebugMacro(<< "Error when deleting tile in cache!"); - return false; - } - return true; -} - -/** Remove all tiles in cache */ -bool TileMapFetcher::UnregisterAllCachedTiles() -{ - bool result = true; - std::deque<otb::TileRecord>::iterator it; - std::string filename; - - /* Loop on deque to get filename and delete file */ - for (it = m_CacheManagement.begin(); it != m_CacheManagement.end(); it++) - { - filename = it->GetFileName(); - - std::ostringstream pathAndFileName; - - pathAndFileName << m_CacheDirectory; - - if (m_CacheDirectory.at(m_CacheDirectory.size() - 1) != '/') pathAndFileName << "/"; - - pathAndFileName << filename; - - if (remove(pathAndFileName.str().c_str()) != 0) - { - itkDebugMacro(<< "Error when deleting tile in cache!"); - result = false; - } - } - // Clear deque - m_CacheManagement.clear(); - return result; -} - -/** Read tile in cache directory */ -TileMapFetcher::ImagePointerType TileMapFetcher::ReadTileFromCache(bool fetchingIsOK) -{ - // Create an output image - ImagePointerType tempImage; - - // If fetch tile from server is ok - if (fetchingIsOK) - { - // Create a reader - itk::ImageFileReader<ImageType>::Pointer reader = itk::ImageFileReader<ImageType>::New(); - - // Create path and filename - std::ostringstream pathAndFileName; - - pathAndFileName << m_CacheDirectory; - - if (m_CacheDirectory.at(m_CacheDirectory.size() - 1) != '/') pathAndFileName << "/"; - - pathAndFileName << m_FileName; - - // Read file in cache directory - reader->SetFileName(pathAndFileName.str()); - reader->Update(); - - tempImage = reader->GetOutput(); - - } - // Else we return logo tile - else - { - // Read logo tile - tempImage = m_LogoTile; - } - - return (tempImage); -} - -/** Generate logo tile */ -void TileMapFetcher::GenerateLogoTile() -{ - // Create image size - ImageType::SizeType size; - size.Fill(256); - - // Create index start - ImageType::IndexType start; - start.Fill(0); - - // Create region size - ImageType::RegionType region; - region.SetIndex(start); - region.SetSize(size); - - // Create image, set properties, and allocate - m_LogoTile = ImageType::New(); - m_LogoTile->SetRegions(region); - m_LogoTile->SetNumberOfComponentsPerPixel(3); - m_LogoTile->Allocate(); - - // Create pixel - ImageType::PixelType white(3); - - // Fill with white - white.Fill(255); - - // Fill image buffer with white pixel - m_LogoTile->FillBuffer(white); -} - -/** Fetch Tile from Server and set it in cache - Check if tile must be update */ -/** Comment because cache is not persistant */ -/* bool TileMapFetcher::FetchTileFromServer(bool isInCache) - { - bool result = false; - - std::ostringstream pathAndFileName; - - pathAndFileName << m_CacheDirectory; - - if (m_CacheDirectory.at(m_CacheDirectory.size()-1) != '/') - pathAndFileName << "/"; - - pathAndFileName << m_FileName; - - FILE* output_file = fopen(pathAndFileName.str().c_str(),"w"); - if (output_file == NULL) - { - itkExceptionMacro(<<"FetchTileFromServer : bad file name."); - return result; - } - - std::ostringstream browserStream; - browserStream << "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-GB; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11"; - - CURL *curl; - CURLcode res; - curl = curl_easy_init(); - - this->GenerateOSMurl(); - - std::cout<<std::endl; - std::cout<<"URL: "<<m_OsmUrl<<std::endl; - std::cout<<"FILENAME: "<<pathAndFileName.str()<<std::endl; - std::cout<<"IS IN CACHE: "<<isInCache<<std::endl; - std::cout<<std::endl; - - if (m_OsmUrl == "") - { - itkExceptionMacro(<<"FetchTileFromServer : bad url."); - return false; - } - - char url[200]; - strcpy(url,m_OsmUrl.data()); - - char browser[200]; - strcpy(browser,browserStream.str().data()); - - //Download the file - if (curl) - { - curl_easy_setopt(curl, CURLOPT_USERAGENT, browser); - curl_easy_setopt(curl, CURLOPT_URL, url); - curl_easy_setopt(curl, CURLOPT_WRITEDATA, output_file); - - // If tile is in cache, ask curl to check if tile is out to date - if(isInCache) - { - // Search for time condition - long time_condition; - - std::deque<otb::TileRecord>::iterator it; - std::deque<otb::TileRecord>::iterator it2; - - for(it=m_CacheManagement.begin(); it!=m_CacheManagement.end(); it++) - { - if(it->GetFileName() == m_FileName) - { - it2 = it; - break; - } - } - - time_condition = static_cast<long>(it2->GetDate()); - - std::cout<<time_condition<<std::endl; - - curl_easy_setopt(curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE); - curl_easy_setopt(curl, CURLOPT_TIMEVALUE, time_condition); - - res = curl_easy_perform(curl); - - if (res == 0) - { - long response; - curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response); - // 304 = Not Modified - if (response == 304) - { - std::cout<<"TUILE NON MODIFIEE"<<std::endl; - result = true; - } - // 200 = Ok - else if (response == 200) - { - double size; - // verify if curl sends us any data - this is a workaround on using CURLOPT_TIMECONDITION - // when the server has a (incorrect) time earlier than the time on the file we already have - curl_easy_getinfo(curl, CURLINFO_SIZE_DOWNLOAD, &size); - if (size == 0) - { - itkExceptionMacro(<<"FetchTileFromServer : transfert error - Size == 0."); - return false; - } - else - { - // Update time in cache - std::cout<<"TUILE MODIFIEE MISE A JOUR DU CACHE"<<std::endl; - it2->SetDate(); - result = true; - } - } - else - { - itkExceptionMacro(<<"FetchTileFromServer : transfert error."); - return false; - } - } - else - { - itkExceptionMacro(<<"FetchTileFromServer : transfert error."); - return false; - } - } - // Not in cache - else - { - res = curl_easy_perform(curl); - if (res != 0) - { - itkExceptionMacro(<<"FetchTileFromServer : transfert error."); - return false; - } - else - { - std::cout<<"RECUPERATION DE LA TUILE"<<std::endl; - result = true; - } - } - - fclose(output_file); - // always cleanup - curl_easy_cleanup(curl); - return result; - } - return false; - } - */ - -} diff --git a/Code/IO/otbTileMapFetcher.h b/Code/IO/otbTileMapFetcher.h deleted file mode 100644 index 612ac1f4562bbf3d5e29ac0bc3f7229ff25c58e3..0000000000000000000000000000000000000000 --- a/Code/IO/otbTileMapFetcher.h +++ /dev/null @@ -1,140 +0,0 @@ -/*========================================================================= - - Program: ORFEO Toolbox - Language: C++ - Date: $Date$ - Version: $Revision$ - - - Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. - See OTBCopyright.txt for details. - - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ -#ifndef __otbTileMapFetcher_h -#define __otbTileMapFetcher_h - -#if defined(_MSC_VER) -#pragma warning ( disable : 4786 ) -#endif - -#include <deque> -#include <string> - -#include "otbVectorImage.h" -#include "otbTileRecord.h" - -/* Curl Library*/ -#include <curl/curl.h> - -namespace otb -{ -/** \class TileMapFetcher - * \brief Get tiles from servers like Open street map. - * - */ -class ITK_EXPORT TileMapFetcher : public itk::Object -{ -public: - /** Standard typedefs */ - typedef TileMapFetcher Self; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - typedef unsigned char PixelType; - typedef otb::VectorImage<PixelType, 2> ImageType; - typedef ImageType::Pointer ImagePointerType; - - itkNewMacro(Self); - - /** Constructor */ - TileMapFetcher(); - - /** Destructor */ - virtual ~TileMapFetcher(); - - /** Accessors */ - itkSetStringMacro(ServerName); - itkGetStringMacro(ServerName); - - itkSetStringMacro(CacheDirectory); - itkGetStringMacro(CacheDirectory); - - itkSetMacro(CacheSize, unsigned int); - itkGetMacro(CacheSize, unsigned int); - - /** Fetcher */ - ImagePointerType FetchTile(unsigned int x, unsigned int y, unsigned int z); - -protected: - -private: - /** Generate filename */ - void GenerateFileName(); - - /** Generate OSM URL */ - void GenerateOSMurl(); - - /** Check if file is in cache */ - bool IsTileInCache(); - - /** Fetch Tile from Server */ -// bool FetchTileFromServer(bool isInCache); // Comment because cache is not persistant - bool FetchTileFromServer(); - - /** Read Tile From Cache */ - ImagePointerType ReadTileFromCache(bool fetchingIsOk); - - /** Register Tile in cache */ - bool RegisterTileInCache(); - - /** Unregister cached tile */ - bool UnregisterFirstCachedTile(); - - /** Unregister All Cached Tiles */ - bool UnregisterAllCachedTiles(); - - /** Generate Tile with logo */ - void GenerateLogoTile(); - - /** Fill buffer with a logo */ - void LogoToBuffer(PixelType* buffer); - - /** File suffix */ - std::string m_FileSuffix; - - /** Server Name */ - std::string m_ServerName; - - /** Cache directory */ - std::string m_CacheDirectory; - - /** Cache Size */ - unsigned int m_CacheSize; - - /** Coordinates */ - unsigned int m_X; - unsigned int m_Y; - unsigned int m_Z; - - /** FileName */ - std::string m_FileName; - - /** OSM Url */ - std::string m_OsmUrl; - - /** Cache Management */ - std::deque<otb::TileRecord> m_CacheManagement; - - /** Logo tile */ - ImagePointerType m_LogoTile; - -}; - -} // end namespace otb - -#endif diff --git a/Code/OBIA/otbBandsStatisticsAttributesLabelMapFilter.h b/Code/OBIA/otbBandsStatisticsAttributesLabelMapFilter.h new file mode 100644 index 0000000000000000000000000000000000000000..b7564bd125ef89148d7a2dc73f4b8dade17d9950 --- /dev/null +++ b/Code/OBIA/otbBandsStatisticsAttributesLabelMapFilter.h @@ -0,0 +1,209 @@ +/*========================================================================= + + Program: ORFEO Toolbox + Language: C++ + Date: $Date$ + Version: $Revision$ + + + Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. + See OTBCopyright.txt for details. + + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __otbBandsStatisticsAttributesLabelMapFilter_h +#define __otbBandsStatisticsAttributesLabelMapFilter_h + +#include "otbStatisticsAttributesLabelMapFilter.h" +#include "otbMultiToMonoChannelExtractROI.h" + +namespace otb +{ +namespace Functor +{ +/** \class BandStatsAttributesLabelObjectFunctor +* \brief Functor to compute multiple statistics attributes. +* +* For one label object, this functors applies the +* StatisticsAttributesLabelObjectFunctor for each feature +* +* As such, it allows to compute in one pass statistics related to +* multiple features. It is used in the +* BandsStatisticsAttributesLabelMapFilter. +* +* Features can be added, removed or cleared via the appropriate +* methods. +* +* \sa BandsStatisticsAttributesLabelMapFilter +* \sa StatisticsAttributesLabelObjectFunctor +*/ +template <class TLabelObject, class TFeatureImage> +class BandStatsAttributesLabelObjectFunctor +{ +public: + // Self typedef + typedef BandStatsAttributesLabelObjectFunctor Self; + + /// Typedef of the feature image type + typedef typename TFeatureImage::PixelType FeatureType; + + /// Typedef of the label object + typedef TLabelObject LabelObjectType; + + /// Feature image const pointer + typedef typename TFeatureImage::ConstPointer FeatureImageConstPointer; + + /// Statistics functor + typedef StatisticsAttributesLabelObjectFunctor + <TLabelObject, TFeatureImage> StatsFunctorType; + + /// Map to store the functors + typedef std::map<std::string, StatsFunctorType> StatsFunctorsMapType; + + /** Constructor */ + BandStatsAttributesLabelObjectFunctor(); + + /** Destructor */ + virtual ~BandStatsAttributesLabelObjectFunctor(); + + /** The comparators */ + bool operator !=(const Self& self); + bool operator ==(const Self& self); + + /** This is the functor implementation + * Calling the functor on a label object + * will update its statistics attributes */ + inline void operator ()(LabelObjectType * lo) const; + + /** Add a feature with the given name */ + void AddFeature(const std::string& name, const TFeatureImage * img); + + /** Remove the feature with this name if it exists */ + bool RemoveFeature(const std::string& name); + + /** Get the feature image with this name */ + const TFeatureImage * GetFeatureImage(const std::string& name) const; + + /** Clear all the features */ + void ClearAllFeatures(); + + /** Get the number of features */ + unsigned int GetNumberOfFeatures() const; + + /** Set the reduced attribute set */ + void SetReducedAttributeSet(bool flag); + + /** Get the reduced attribute set */ + bool GetReducedAttributeSet() const; + +private: + /// True to compute only a reduced attribute set + bool m_ReducedAttributeSet; + + /// The Stat functors map + StatsFunctorsMapType m_StatsFunctorsMap; +}; +} // End namespace Functor + +/** \class BandsStatisticsAttributesLabelMapFilter + * \brief This filter computes band statistics attributes for each object. + * + * Images are supposed to be compatible with otb::VectorImage + * + * This filter internally applies the + * StatisticsAttributesLabelMapFilter each channel independently + * + * The feature name is constructed as: + * 'STATS' + '::' + 'Band' + #BandIndex + '::' + StatisticName + * + * The ReducedAttributesSet flag allows to tell the internal + * statistics filter to compute only the main attributes (mean, variance, skewness and kurtosis). + * + * \sa MultiStatsAttributesLabelObjectFunctor AttributesMapLabelObject + * + * \ingroup ImageEnhancement MathematicalMorphologyImageFilters + */ +template<class TImage, class TFeatureImage> +class ITK_EXPORT BandsStatisticsAttributesLabelMapFilter + : public LabelMapFeaturesFunctorImageFilter + <TImage, + typename Functor::BandStatsAttributesLabelObjectFunctor + <typename TImage::LabelObjectType, otb::Image<double, 2> > > +{ +public: + /** Some convenient typedefs. */ + typedef TImage ImageType; + typedef typename ImageType::LabelObjectType LabelObjectType; + typedef TFeatureImage FeatureImageType; + typedef typename FeatureImageType::InternalPixelType FeatureInternalPixelType; + typedef double InternalPrecisionType; + typedef Image<InternalPrecisionType, 2> InternalImageType; + + /** Functor typedef */ + typedef Functor::BandStatsAttributesLabelObjectFunctor + <LabelObjectType, InternalImageType> FunctorType; + + /** Standard class typedefs. */ + typedef BandsStatisticsAttributesLabelMapFilter Self; + typedef LabelMapFeaturesFunctorImageFilter + <ImageType, FunctorType> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** ImageDimension constants */ + itkStaticConstMacro(ImageDimension, unsigned int, TImage::ImageDimension); + + /** Standard New method. */ + itkNewMacro(Self); + + /** Runtime information support. */ + itkTypeMacro(BandsStatisticsAttributesLabelMapFilter, LabelMapFeaturesFunctorImageFilter); + + // Channels + typedef MultiToMonoChannelExtractROI + <FeatureInternalPixelType, InternalPrecisionType> ChannelFilterType; + typedef typename ChannelFilterType::Pointer ChannelFilterPointerType; + + /** Set the feature image */ + void SetFeatureImage(const TFeatureImage *input); + + /** Get the feature image */ + const FeatureImageType * GetFeatureImage() const; + + /** Set the reduced attribute set */ + void SetReducedAttributeSet(bool flag); + + /** Get the reduced attribute set */ + bool GetReducedAttributeSet() const; + + itkBooleanMacro(ReducedAttributeSet); + +protected: + /** Constructor */ + BandsStatisticsAttributesLabelMapFilter(); + /** Destructor */ + ~BandsStatisticsAttributesLabelMapFilter() {} + + /** Before threaded data generation */ + virtual void BeforeThreadedGenerateData(); + + /** PrintSelf method */ + void PrintSelf(std::ostream& os, itk::Indent indent) const; + +private: + BandsStatisticsAttributesLabelMapFilter(const Self &); //purposely not implemented + void operator =(const Self&); //purposely not implemented + +}; // end of class + +} // end namespace itk + +#ifndef OTB_MANUAL_INSTANTIATION +#include "otbBandsStatisticsAttributesLabelMapFilter.txx" +#endif + +#endif diff --git a/Code/OBIA/otbBandsStatisticsAttributesLabelMapFilter.txx b/Code/OBIA/otbBandsStatisticsAttributesLabelMapFilter.txx new file mode 100644 index 0000000000000000000000000000000000000000..224bbd7f904177924ddb1a121b9a885389309117 --- /dev/null +++ b/Code/OBIA/otbBandsStatisticsAttributesLabelMapFilter.txx @@ -0,0 +1,249 @@ +/*========================================================================= + + Program: ORFEO Toolbox + Language: C++ + Date: $Date$ + Version: $Revision$ + + + Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. + See OTBCopyright.txt for details. + + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __otbBandsStatisticsAttributesLabelMapFilter_txx +#define __otbBandsStatisticsAttributesLabelMapFilter_txx + +#include "otbBandsStatisticsAttributesLabelMapFilter.h" + +namespace otb +{ +namespace Functor +{ +/** Constructor */ +template <class TLabelObject, class TFeatureImage> +BandStatsAttributesLabelObjectFunctor<TLabelObject, TFeatureImage> +::BandStatsAttributesLabelObjectFunctor() : m_ReducedAttributeSet(true), + m_StatsFunctorsMap() +{} + +/** Destructor */ +template <class TLabelObject, class TFeatureImage> +BandStatsAttributesLabelObjectFunctor<TLabelObject, TFeatureImage> +::~BandStatsAttributesLabelObjectFunctor(){} + +/** The comparators */ +template <class TLabelObject, class TFeatureImage> +bool +BandStatsAttributesLabelObjectFunctor<TLabelObject, TFeatureImage> +::operator != (const Self &self) + { + bool resp = true; + resp = resp && (m_ReducedAttributeSet != self.m_ReducedAttributeSet); + resp = resp && (m_StatsFunctorsMap != self.m_StatsFunctorsMap); + return resp; + } + +template <class TLabelObject, class TFeatureImage> +bool +BandStatsAttributesLabelObjectFunctor<TLabelObject, TFeatureImage> +::operator == (const Self &self) + { + return !(this != self); + } + +/** This is the functor implementation + * Calling the functor on a label object + * will update its statistics attributes */ +template <class TLabelObject, class TFeatureImage> +void +BandStatsAttributesLabelObjectFunctor<TLabelObject, TFeatureImage> +::operator() (LabelObjectType * lo) const +{ + // Walk every registered functors + for (typename StatsFunctorsMapType::const_iterator it = m_StatsFunctorsMap.begin(); + it != m_StatsFunctorsMap.end(); ++it) + { + (it->second)(lo); + } +} + +/** Add a feature with the given name */ +template <class TLabelObject, class TFeatureImage> +void +BandStatsAttributesLabelObjectFunctor<TLabelObject, TFeatureImage> +::AddFeature(const std::string& name, const TFeatureImage * img) +{ + // Create a new functor + StatsFunctorType newFunctor; + + // Set the reduced attribute set option + newFunctor.SetReducedAttributeSet(m_ReducedAttributeSet); + + // Set the feature and its name + newFunctor.SetFeatureName(name); + + // Set the feature image + newFunctor.SetFeatureImage(img); + + // Add it to the map + m_StatsFunctorsMap[name] = newFunctor; +} + +/** Remove the feature with this name if it exists */ +template <class TLabelObject, class TFeatureImage> +bool +BandStatsAttributesLabelObjectFunctor<TLabelObject, TFeatureImage> +::RemoveFeature(const std::string& name) +{ + return (m_StatsFunctorsMap.erase(name) == 1); +} + +/** Get the feature image with this name */ +template <class TLabelObject, class TFeatureImage> +const TFeatureImage * +BandStatsAttributesLabelObjectFunctor<TLabelObject, TFeatureImage> +::GetFeatureImage(const std::string& name) const +{ + if (m_StatsFunctorsMap.count(name) == 0) + { + itkGenericExceptionMacro(<< "No feature named " << name << " in map."); + } + return m_StatsFunctorsMap[name].GetFeatureImage(); +} + +/** Clear all the features */ +template <class TLabelObject, class TFeatureImage> +void +BandStatsAttributesLabelObjectFunctor<TLabelObject, TFeatureImage> +::ClearAllFeatures() +{ + m_StatsFunctorsMap.clear(); +} + +/** Get the number of features */ +template <class TLabelObject, class TFeatureImage> +unsigned int +BandStatsAttributesLabelObjectFunctor<TLabelObject, TFeatureImage> +::GetNumberOfFeatures() const +{ + return m_StatsFunctorsMap.size(); +} + +/** Set the reduced attribute set */ +template <class TLabelObject, class TFeatureImage> +void +BandStatsAttributesLabelObjectFunctor<TLabelObject, TFeatureImage> +::SetReducedAttributeSet(bool flag) +{ + // Set the flag + m_ReducedAttributeSet = flag; + + // Set the flag to all the already existing functors + for (typename StatsFunctorsMapType::iterator it = m_StatsFunctorsMap.begin(); + it != m_StatsFunctorsMap.end(); ++it) + { + it->second.SetReducedAttributeSet(m_ReducedAttributeSet); + } +} +/** Get the reduced attribute set */ +template <class TLabelObject, class TFeatureImage> +bool +BandStatsAttributesLabelObjectFunctor<TLabelObject, TFeatureImage> +::GetReducedAttributeSet() const +{ + return m_ReducedAttributeSet; +} +} // End namespace Functor + +template <class TImage, class TFeatureImage> +BandsStatisticsAttributesLabelMapFilter<TImage, TFeatureImage> +::BandsStatisticsAttributesLabelMapFilter() +{ + this->SetNumberOfRequiredInputs(2); +} + +/** Set the feature image */ +template <class TImage, class TFeatureImage> +void +BandsStatisticsAttributesLabelMapFilter<TImage, TFeatureImage> +::SetFeatureImage(const TFeatureImage *input) +{ + // Set the Nth input + this->SetNthInput(1, const_cast<TFeatureImage*>(input)); +} + +/** Get the feature image */ +template <class TImage, class TFeatureImage> +const typename BandsStatisticsAttributesLabelMapFilter<TImage, TFeatureImage> +::FeatureImageType * +BandsStatisticsAttributesLabelMapFilter<TImage, TFeatureImage> +::GetFeatureImage() const +{ + return static_cast<const TFeatureImage *>(this->itk::ProcessObject::GetInput(1)); +} + +/** Set the reduced attribute set */ +template <class TImage, class TFeatureImage> +void +BandsStatisticsAttributesLabelMapFilter<TImage, TFeatureImage> +::SetReducedAttributeSet(bool flag) +{ + if (this->GetFunctor().GetReducedAttributeSet() != flag) + { + this->GetFunctor().SetReducedAttributeSet(flag); + this->Modified(); + } +} + +/** Get the reduced attribute set */ +template <class TImage, class TFeatureImage> +bool +BandsStatisticsAttributesLabelMapFilter<TImage, TFeatureImage> +::GetReducedAttributeSet() const +{ + return this->GetFunctor().GetReducedAttributeSet(); +} + +template <class TImage, class TFeatureImage> +void +BandsStatisticsAttributesLabelMapFilter<TImage, TFeatureImage> +::BeforeThreadedGenerateData() +{ + // First call superclass implementation + Superclass::BeforeThreadedGenerateData(); + + unsigned long nbComponents = this->GetFeatureImage()->GetNumberOfComponentsPerPixel(); + + // Clear any previous feature + this->GetFunctor().ClearAllFeatures(); + + // Add each band of the feature image to the statistics functor + for (unsigned int i = 0; i < nbComponents; ++i) + { + ChannelFilterPointerType band = ChannelFilterType::New(); + band->SetChannel(i + 1); + band->SetInput(this->GetFeatureImage()); + band->GetOutput()->SetRequestedRegion(this->GetOutput()->GetRequestedRegion()); + band->Update(); + std::ostringstream oss; + oss << "Band" << i + 1; // [1..N] convention in feature naming + this->GetFunctor().AddFeature(oss.str(), band->GetOutput()); + } + +} + +template <class TImage, class TFeatureImage> +void +BandsStatisticsAttributesLabelMapFilter<TImage, TFeatureImage> +::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf(os, indent); +} + +} // end namespace itk +#endif diff --git a/Code/OBIA/otbLabelMapSVMClassifier.h b/Code/OBIA/otbLabelMapSVMClassifier.h index b63fdd7debea54e0a658ccb403ece0fa2b5d9fc2..dba609d66febf7c542519fd1a50aec86aaa291b6 100644 --- a/Code/OBIA/otbLabelMapSVMClassifier.h +++ b/Code/OBIA/otbLabelMapSVMClassifier.h @@ -85,6 +85,9 @@ protected: virtual void ThreadedProcessLabelObject( LabelObjectType * labelObject ); + virtual void ReleaseInputs(); + + private: LabelMapSVMClassifier(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented diff --git a/Code/OBIA/otbLabelMapSVMClassifier.txx b/Code/OBIA/otbLabelMapSVMClassifier.txx index 8ee5cff68f9ef778a31d576b08a6fcd954003579..eb507f4e3bf85000035b0d57fcafe81fc448530e 100644 --- a/Code/OBIA/otbLabelMapSVMClassifier.txx +++ b/Code/OBIA/otbLabelMapSVMClassifier.txx @@ -33,6 +33,14 @@ LabelMapSVMClassifier<TInputImage> this->SetNumberOfThreads(1); } +template<class TInputImage> +void +LabelMapSVMClassifier<TInputImage> +::ReleaseInputs( ) +{ + this->itk::LabelMapFilter<TInputImage, TInputImage>::ReleaseInputs(); +} + template<class TInputImage> void LabelMapSVMClassifier<TInputImage> diff --git a/Code/OBIA/otbLabelMapWithClassLabelToClassLabelImageFilter.txx b/Code/OBIA/otbLabelMapWithClassLabelToClassLabelImageFilter.txx index 1e02a6e0751ecf428bda65ead7568f5148767923..510a5194bc9af037da82f25b0d6a394c243f9bdd 100644 --- a/Code/OBIA/otbLabelMapWithClassLabelToClassLabelImageFilter.txx +++ b/Code/OBIA/otbLabelMapWithClassLabelToClassLabelImageFilter.txx @@ -39,11 +39,8 @@ LabelMapWithClassLabelToClassLabelImageFilter<TInputImage, TOutputImage> { OutputImageType * output = this->GetOutput(); const InputImageType * input = this->GetInput(); - output->FillBuffer( input->GetBackgroundValue() ); - Superclass::BeforeThreadedGenerateData(); - } @@ -53,7 +50,6 @@ LabelMapWithClassLabelToClassLabelImageFilter<TInputImage, TOutputImage> ::ThreadedProcessLabelObject( LabelObjectType * labelObject ) { typename LabelObjectType::ClassLabelType label = itk::NumericTraits<typename LabelObjectType::ClassLabelType>::max(); - if(labelObject->HasClassLabel()) { label = labelObject->GetClassLabel(); diff --git a/Code/OBIA/otbStatisticsAttributesLabelMapFilter.txx b/Code/OBIA/otbStatisticsAttributesLabelMapFilter.txx index b3169c545a5799b0eb29f6c860eb8549f10ffce7..45d0973fe353856f0b4df6bdea3f26764834bd9c 100644 --- a/Code/OBIA/otbStatisticsAttributesLabelMapFilter.txx +++ b/Code/OBIA/otbStatisticsAttributesLabelMapFilter.txx @@ -78,15 +78,17 @@ StatisticsAttributesLabelObjectFunctor<TLabelObject, TFeatureImage> ::operator() (LabelObjectType * lo) const { typename LabelObjectType::LineContainerType::const_iterator lit; - typename LabelObjectType::LineContainerType& lineContainer = lo->GetLineContainer(); - - FeatureType min = itk::NumericTraits<FeatureType>::max(); - FeatureType max = itk::NumericTraits<FeatureType>::NonpositiveMin(); - double sum = 0; - double sum2 = 0; - double sum3 = 0; - double sum4 = 0; - unsigned int totalFreq = 0; + typename LabelObjectType::LineContainerType& lineContainer = lo->GetLineContainer(); + + itk::OStringStream oss; + + FeatureType min = itk::NumericTraits<FeatureType>::max(); + FeatureType max = itk::NumericTraits<FeatureType>::NonpositiveMin(); + double sum = 0; + double sum2 = 0; + double sum3 = 0; + double sum4 = 0; + unsigned int totalFreq = 0; typename TFeatureImage::IndexType minIdx; minIdx.Fill(0); typename TFeatureImage::IndexType maxIdx; @@ -104,7 +106,7 @@ StatisticsAttributesLabelObjectFunctor<TLabelObject, TFeatureImage> for (lit = lineContainer.begin(); lit != lineContainer.end(); lit++) { const typename TFeatureImage::IndexType& firstIdx = lit->GetIndex(); - unsigned long length = lit->GetLength(); + unsigned long length = lit->GetLength(); long endIdx0 = firstIdx[0] + length; for (typename TFeatureImage::IndexType idx = firstIdx; idx[0] < endIdx0; idx[0]++) @@ -125,34 +127,38 @@ StatisticsAttributesLabelObjectFunctor<TLabelObject, TFeatureImage> } //increase the sums + const double v2 = v * v; + sum += v; - sum2 += vcl_pow((double) v, 2); - sum3 += vcl_pow((double) v, 3); - sum4 += vcl_pow((double) v, 4); + sum2 += v2; + sum3 += v2 * v; + sum4 += v2 * v2; - // moments - typename TFeatureImage::PointType physicalPosition; - m_FeatureImage->TransformIndexToPhysicalPoint(idx, physicalPosition); - for (unsigned int i = 0; i < TFeatureImage::ImageDimension; i++) + if (!m_ReducedAttributeSet) { - centerOfGravity[i] += physicalPosition[i] * v; - centralMoments[i][i] += v * physicalPosition[i] * physicalPosition[i]; - for (unsigned int j = i + 1; j < TFeatureImage::ImageDimension; j++) + // moments + typename TFeatureImage::PointType physicalPosition; + m_FeatureImage->TransformIndexToPhysicalPoint(idx, physicalPosition); + for (unsigned int i = 0; i < TFeatureImage::ImageDimension; i++) { - double weight = v * physicalPosition[i] * physicalPosition[j]; - centralMoments[i][j] += weight; - centralMoments[j][i] += weight; + centerOfGravity[i] += physicalPosition[i] * v; + centralMoments[i][i] += v * physicalPosition[i] * physicalPosition[i]; + for (unsigned int j = i + 1; j < TFeatureImage::ImageDimension; j++) + { + const double weight = v * physicalPosition[i] * physicalPosition[j]; + centralMoments[i][j] += weight; + centralMoments[j][i] += weight; + } } } - } } // final computations - double mean = sum / totalFreq; - double variance = (sum2 - (vcl_pow(sum, 2) / totalFreq)) / (totalFreq - 1); - double sigma = vcl_sqrt(variance); - double mean2 = mean * mean; + const double mean = sum / totalFreq; + const double variance = (sum2 - (sum * sum / totalFreq)) / (totalFreq - 1); + const double sigma = vcl_sqrt(variance); + const double mean2 = mean * mean; double skewness = 0; double kurtosis = 0; @@ -160,82 +166,10 @@ StatisticsAttributesLabelObjectFunctor<TLabelObject, TFeatureImage> if (vcl_abs(variance) > epsilon) { skewness = ((sum3 - 3.0 * mean * sum2) / totalFreq + 2.0 * mean * mean2) / (variance * sigma); - kurtosis = - ((sum4 - 4.0 * mean * sum3 + 6.0 * mean2 * - sum2) / totalFreq - 3.0 * mean2 * mean2) / (variance * variance) - 3.0; + kurtosis = ((sum4 - 4.0 * mean * sum3 + 6.0 * mean2 * sum2) / totalFreq - 3.0 * mean2 * mean2) / (variance + * variance) - 3.0; } - double elongation = 0; - if (sum != 0) - { - // Normalize using the total mass - for (unsigned int i = 0; i < TFeatureImage::ImageDimension; i++) - { - centerOfGravity[i] /= sum; - for (unsigned int j = 0; j < TFeatureImage::ImageDimension; j++) - { - centralMoments[i][j] /= sum; - } - } - - // Center the second order moments - for (unsigned int i = 0; i < TFeatureImage::ImageDimension; i++) - { - for (unsigned int j = 0; j < TFeatureImage::ImageDimension; j++) - { - centralMoments[i][j] -= centerOfGravity[i] * centerOfGravity[j]; - } - } - - // Compute principal moments and axes - vnl_symmetric_eigensystem<double> eigen(centralMoments.GetVnlMatrix()); - vnl_diag_matrix<double> pm = eigen.D; - for (unsigned int i = 0; i < TFeatureImage::ImageDimension; i++) - { - // principalMoments[i] = 4 * vcl_sqrt( pm(i,i) ); - principalMoments[i] = pm(i, i); - } - principalAxes = eigen.V.transpose(); - - // Add a final reflection if needed for a proper rotation, - // by multiplying the last row by the determinant - vnl_real_eigensystem eigenrot(principalAxes.GetVnlMatrix()); - vnl_diag_matrix<vcl_complex<double> > eigenval = eigenrot.D; - vcl_complex<double> det(1.0, 0.0); - - for (unsigned int i = 0; i < TFeatureImage::ImageDimension; i++) - { - det *= eigenval(i, i); - } - - for (unsigned int i = 0; i < TFeatureImage::ImageDimension; i++) - { - principalAxes[TFeatureImage::ImageDimension - 1][i] *= std::real(det); - } - - if (principalMoments[0] != 0) - { - // elongation = principalMoments[TFeatureImage::ImageDimension-1] / principalMoments[0]; - elongation = vcl_sqrt(principalMoments[TFeatureImage::ImageDimension - 1] / principalMoments[0]); - } - } - else - { - // can't compute anything in that case - just set everything to a default value - // Normalize using the total mass - for (unsigned int i = 0; i < TFeatureImage::ImageDimension; i++) - { - centerOfGravity[i] = 0; - principalMoments[i] = 0; - for (unsigned int j = 0; j < TFeatureImage::ImageDimension; j++) - { - principalAxes[i][j] = 0; - } - } - } - itk::OStringStream oss; - - // finally put the values in the label object oss.str(""); oss << "STATS::" << m_FeatureName << "::Mean"; lo->SetAttribute(oss.str().c_str(), mean); @@ -250,55 +184,124 @@ StatisticsAttributesLabelObjectFunctor<TLabelObject, TFeatureImage> oss.str(""); oss << "STATS::" << m_FeatureName << "::Kurtosis"; - lo->SetAttribute(oss.str().c_str(), kurtosis); + lo->SetAttribute(oss.str().c_str(), kurtosis); - // If we want all the features if (!m_ReducedAttributeSet) { - oss.str(""); - oss << "STATS::" << m_FeatureName << "::Minimum"; - lo->SetAttribute(oss.str().c_str(), (double) min); + double elongation = 0; + if (sum != 0) + { + // Normalize using the total mass + for (unsigned int i = 0; i < TFeatureImage::ImageDimension; i++) + { + centerOfGravity[i] /= sum; + for (unsigned int j = 0; j < TFeatureImage::ImageDimension; j++) + { + centralMoments[i][j] /= sum; + } + } + + // Center the second order moments + for (unsigned int i = 0; i < TFeatureImage::ImageDimension; i++) + { + for (unsigned int j = 0; j < TFeatureImage::ImageDimension; j++) + { + centralMoments[i][j] -= centerOfGravity[i] * centerOfGravity[j]; + } + } + + // Compute principal moments and axes + vnl_symmetric_eigensystem<double> eigen(centralMoments.GetVnlMatrix()); + vnl_diag_matrix<double> pm = eigen.D; + for (unsigned int i = 0; i < TFeatureImage::ImageDimension; i++) + { + // principalMoments[i] = 4 * vcl_sqrt( pm(i,i) ); + principalMoments[i] = pm(i, i); + } + principalAxes = eigen.V.transpose(); - oss.str(""); - oss << "STATS::" << m_FeatureName << "::Maximum"; - lo->SetAttribute(oss.str().c_str(), (double) max); + // Add a final reflection if needed for a proper rotation, + // by multiplying the last row by the determinant + vnl_real_eigensystem eigenrot(principalAxes.GetVnlMatrix()); + vnl_diag_matrix<vcl_complex<double> > eigenval = eigenrot.D; + vcl_complex<double> det(1.0, 0.0); - oss.str(""); - oss << "STATS::" << m_FeatureName << "::Sum"; - lo->SetAttribute(oss.str().c_str(), sum); + for (unsigned int i = 0; i < TFeatureImage::ImageDimension; i++) + { + det *= eigenval(i, i); + } - oss.str(""); - oss << "STATS::" << m_FeatureName << "::Sigma"; - lo->SetAttribute(oss.str().c_str(), sigma); + for (unsigned int i = 0; i < TFeatureImage::ImageDimension; i++) + { + principalAxes[TFeatureImage::ImageDimension - 1][i] *= std::real(det); + } + + if (principalMoments[0] != 0) + { + // elongation = principalMoments[TFeatureImage::ImageDimension-1] / principalMoments[0]; + elongation = vcl_sqrt(principalMoments[TFeatureImage::ImageDimension - 1] / principalMoments[0]); + } + } + else + { + // can't compute anything in that case - just set everything to a default value + // Normalize using the total mass + for (unsigned int i = 0; i < TFeatureImage::ImageDimension; i++) + { + centerOfGravity[i] = 0; + principalMoments[i] = 0; + for (unsigned int j = 0; j < TFeatureImage::ImageDimension; j++) + { + principalAxes[i][j] = 0; + } + } + } - for (unsigned int dim = 0; dim < TFeatureImage::ImageDimension; ++dim) - { oss.str(""); - oss << "STATS::" << m_FeatureName << "::CenterOfGravity" << dim; - lo->SetAttribute(oss.str().c_str(), centerOfGravity[dim]); + oss << "STATS::" << m_FeatureName << "::Minimum"; + lo->SetAttribute(oss.str().c_str(), (double) min); oss.str(""); - oss << "STATS::" << m_FeatureName << "::PrincipalMoments" << dim; - lo->SetAttribute(oss.str().c_str(), principalMoments[dim]); + oss << "STATS::" << m_FeatureName << "::Maximum"; + lo->SetAttribute(oss.str().c_str(), (double) max); oss.str(""); - oss << "STATS::" << m_FeatureName << "::FirstMinimumIndex" << dim; - lo->SetAttribute(oss.str().c_str(), minIdx[dim]); + oss << "STATS::" << m_FeatureName << "::Sum"; + lo->SetAttribute(oss.str().c_str(), sum); oss.str(""); - oss << "STATS::" << m_FeatureName << "::FirstMaximumIndex" << dim; - lo->SetAttribute(oss.str().c_str(), maxIdx[dim]); + oss << "STATS::" << m_FeatureName << "::Sigma"; + lo->SetAttribute(oss.str().c_str(), sigma); - for (unsigned int dim2 = 0; dim2 < TFeatureImage::ImageDimension; ++dim2) + for (unsigned int dim = 0; dim < TFeatureImage::ImageDimension; ++dim) { oss.str(""); - oss << "STATS::" << m_FeatureName << "::PrincipalAxis" << dim << dim2; - lo->SetAttribute(oss.str().c_str(), principalAxes(dim, dim2)); + oss << "STATS::" << m_FeatureName << "::CenterOfGravity" << dim; + lo->SetAttribute(oss.str().c_str(), centerOfGravity[dim]); + + oss.str(""); + oss << "STATS::" << m_FeatureName << "::PrincipalMoments" << dim; + lo->SetAttribute(oss.str().c_str(), principalMoments[dim]); + + oss.str(""); + oss << "STATS::" << m_FeatureName << "::FirstMinimumIndex" << dim; + lo->SetAttribute(oss.str().c_str(), minIdx[dim]); + + oss.str(""); + oss << "STATS::" << m_FeatureName << "::FirstMaximumIndex" << dim; + lo->SetAttribute(oss.str().c_str(), maxIdx[dim]); + + for (unsigned int dim2 = 0; dim2 < TFeatureImage::ImageDimension; ++dim2) + { + oss.str(""); + oss << "STATS::" << m_FeatureName << "::PrincipalAxis" << dim << dim2; + lo->SetAttribute(oss.str().c_str(), principalAxes(dim, dim2)); + } } } - } } + /** Set the name of the feature */ template <class TLabelObject, class TFeatureImage> void @@ -352,6 +355,7 @@ StatisticsAttributesLabelObjectFunctor<TLabelObject, TFeatureImage> { return m_ReducedAttributeSet; } + } // End namespace Functor template <class TImage, class TFeatureImage> diff --git a/Code/Projections/otbGenericRSResampleImageFilter.h b/Code/Projections/otbGenericRSResampleImageFilter.h index cbe76bfdb0acddf42f59317ffaf8ed2739715e2e..2063f98153af1d86c8b3fb694d8c86ec24f288d1 100644 --- a/Code/Projections/otbGenericRSResampleImageFilter.h +++ b/Code/Projections/otbGenericRSResampleImageFilter.h @@ -67,6 +67,7 @@ public: typedef TInputImage InputImageType; typedef TOutputImage OutputImageType; typedef typename OutputImageType::InternalPixelType OutputInternalPixelType; + typedef typename OutputImageType::PointType OutputPointType; /** Internal filters typedefs*/ typedef StreamingResampleImageFilter<InputImageType, @@ -79,13 +80,13 @@ public: typedef typename ResamplerType::IndexType IndexType; typedef typename ResamplerType::RegionType RegionType; typedef typename ResamplerType::InterpolatorType InterpolatorType; - + /** Estimate the rpc model */ typedef PhysicalToRPCSensorModelImageFilter<InputImageType> InputRpcModelEstimatorType; typedef typename InputRpcModelEstimatorType::Pointer InputRpcModelEstimatorPointerType; - typedef PhysicalToRPCSensorModelImageFilter<OutputImageType> OutputRpcModelEstimatorType; - typedef typename OutputRpcModelEstimatorType::Pointer OutputRpcModelEstimatorPointerType; + typedef PhysicalToRPCSensorModelImageFilter<OutputImageType> OutputRpcModelEstimatorType; + typedef typename OutputRpcModelEstimatorType::Pointer OutputRpcModelEstimatorPointerType; /** Specialisation of OptResampleFilter with a remote @@ -155,7 +156,7 @@ public: this->Modified(); } - std::string GetInputProjectionRef() + std::string GetInputProjectionRef() const { return m_Transform->GetOutputProjectionRef(); } @@ -166,7 +167,7 @@ public: this->Modified(); } - std::string GetOutputProjectionRef() + std::string GetOutputProjectionRef() const { return m_Transform->GetInputProjectionRef(); } @@ -214,9 +215,11 @@ public: } otbGetObjectMemberConstMacro(Transform,AverageElevation,double); - /** Useful to set the output parameters from an existing image*/ void SetOutputParametersFromImage(const ImageBaseType * image); + + /** Useful to set the output parameters from an existing image*/ + void SetOutputParametersFromMap(const std::string map, const SpacingType& spacing); /** Set/Get the grid size for rpc estimator*/ void SetInputRpcGridSize(const SizeType& gridSize) diff --git a/Code/Projections/otbGenericRSResampleImageFilter.txx b/Code/Projections/otbGenericRSResampleImageFilter.txx index 70620a8e494f558f3ba3be65be77239f47d84840..589a2e0f673c2d467c04e20f0118c69c1f308193 100644 --- a/Code/Projections/otbGenericRSResampleImageFilter.txx +++ b/Code/Projections/otbGenericRSResampleImageFilter.txx @@ -21,8 +21,9 @@ #include "itkMetaDataDictionary.h" #include "itkMetaDataObject.h" #include "otbMetaDataKey.h" -#include "itkIdentityTransform.h" -#include "itkContinuousIndex.h" + +#include "projection/ossimUtmProjection.h" +#include "itkPoint.h" namespace otb { @@ -230,6 +231,149 @@ GenericRSResampleImageFilter<TInputImage, TOutputImage> this->SetOutputSpacing ( image->GetSpacing() ); this->SetOutputStartIndex ( image->GetLargestPossibleRegion().GetIndex() ); this->SetOutputSize ( image->GetLargestPossibleRegion().GetSize() ); + this->SetOutputProjectionRef(image->GetProjectionRef()); + this->SetOutputKeywordList(image->GetImageKeywordlist()); +} +/** + * Method used to copy the parameters of the input image + * + */ +template <class TInputImage, class TOutputImage> +void +GenericRSResampleImageFilter<TInputImage, TOutputImage> +::SetOutputParametersFromMap(const std::string map, const SpacingType& spacing) +{ + // Get the input Image + const InputImageType* input = this->GetInput(); + + // Update the transform with input information + // Done here because the transform is not instanciated + // yet + this->UpdateTransform(); + + // The inverse transform is need here + GenericRSTransformPointerType invTransform = GenericRSTransformType::New(); + m_Transform->GetInverse(invTransform); + + // Build the UTM transform : Need the zone & the hemisphere + // For this we us the geographic coordinate of the input UL corner + typedef ossimRefPtr<ossimUtmProjection> OssimMapProjectionPointerType; + typedef itk::Point<double,2> GeoPointType; + + // instanciate the projection to get the utm zone + OssimMapProjectionPointerType utmMapProjection = new ossimUtmProjection(); + + // get the utm zone and hemisphere using the input UL corner + // geographic coordinates + typename InputImageType::PointType pSrc; + IndexType index; + GeoPointType geoPoint; + index[0] = input->GetLargestPossibleRegion().GetIndex()[0]; + index[1] = input->GetLargestPossibleRegion().GetIndex()[1]; + input->TransformIndexToPhysicalPoint(index,pSrc); + + // The first transform of the inverse transform : input -> WGS84 + geoPoint = invTransform->GetTransform()->GetFirstTransform()->TransformPoint(pSrc); + + // Guess the zone and the hemisphere + ossimGpt point(geoPoint[1], geoPoint[0]); + int zone = utmMapProjection->computeZone(point); + bool hem = (geoPoint[1]>1e-10)?true:false; + + // Build the output UTM projection ref + OGRSpatialReference oSRS; + oSRS.SetProjCS("UTM"); + oSRS.SetWellKnownGeogCS("WGS84"); + oSRS.SetUTM(zone, hem); + + char * utmRef = NULL; + oSRS.exportToWkt(&utmRef); + + // Update the transform + this->SetOutputProjectionRef(utmRef); + this->SetOutputSpacing(spacing); + this->UpdateTransform(); + + // Get the inverse transform again : used later + m_Transform->GetInverse(invTransform); + + // Compute the 4 corners in the cartographic coordinate system + std::vector<IndexType> vindex; + std::vector<OutputPointType> voutput; + + IndexType index1, index2, index3, index4; + SizeType size; + + // Image size + size = input->GetLargestPossibleRegion().GetSize(); + + // project the 4 corners + index1 = input->GetLargestPossibleRegion().GetIndex(); + index2 = input->GetLargestPossibleRegion().GetIndex(); + index3 = input->GetLargestPossibleRegion().GetIndex(); + index4 = input->GetLargestPossibleRegion().GetIndex(); + + index2[0] += size[0] - 1; + index3[0] += size[0] - 1; + index3[1] += size[1] - 1; + index4[1] += size[1] - 1; + + vindex.push_back(index1); + vindex.push_back(index2); + vindex.push_back(index3); + vindex.push_back(index4); + + for (unsigned int i = 0; i < vindex.size(); i++) + { + OutputPointType physicalPoint; + this->GetInput()->TransformIndexToPhysicalPoint(vindex[i], physicalPoint); + voutput.push_back(invTransform->TransformPoint(physicalPoint)); + } + + // Compute the boundaries + double minX = voutput[0][0]; + double maxX = voutput[0][0]; + double minY = voutput[0][1]; + double maxY = voutput[0][1]; + + for (unsigned int i = 0; i < voutput.size(); i++) + { + // Origins + if (minX > voutput[i][0]) + minX = voutput[i][0]; + if (minY > voutput[i][1]) + minY = voutput[i][1]; + + // Sizes + if (maxX < voutput[i][0]) + maxX = voutput[i][0]; + + if (maxY < voutput[i][1]) + maxY = voutput[i][1]; + } + + // Compute the output size + double sizeCartoX = vcl_abs(maxX - minX); + double sizeCartoY = vcl_abs(minY - maxY); + + // Set the output orgin in carto + // projection + OriginType origin; + origin[0] = minX; + origin[1] = maxY; + this->SetOutputOrigin(origin); + + // Evaluate output size + SizeType outputSize; + outputSize[0] = static_cast<unsigned int>(vcl_floor(vcl_abs(sizeCartoX / this->GetOutputSpacing()[0]))); + outputSize[1] = static_cast<unsigned int>(vcl_floor(vcl_abs(sizeCartoY / this->GetOutputSpacing()[1]))); + this->SetOutputSize(outputSize); + + std::cout <<"Output Image params :" + << " \n OutputSize " << outputSize + << " \n OutputOrigin " << origin + << " \n OutputSpacing "<< this->GetOutputSpacing() + << std::endl; } } diff --git a/Code/Projections/otbOrthoRectificationFilter.h b/Code/Projections/otbOrthoRectificationFilter.h index 7ea0d9dc149c31a5cdd91da52d1f5f2d2999c6ed..7e01fad8915dab1b998cd5936ddcaeeada9c0e24 100644 --- a/Code/Projections/otbOrthoRectificationFilter.h +++ b/Code/Projections/otbOrthoRectificationFilter.h @@ -89,6 +89,12 @@ public: } } itkGetObjectMacro(MapProjection, MapProjectionType); + + /** + * Set the output size. This method is deprecated and is + * maintained for backward compatibility only + */ + itkLegacyMacro(void SetSize(const SizeType& size){this->SetOutputSize(size);}); protected: OrthoRectificationFilter(); diff --git a/Code/Radiometry/otbAtmosphericRadiativeTerms.cxx b/Code/Radiometry/otbAtmosphericRadiativeTerms.cxx index 8d9998213b5c1e7c02e6144d81d50a2683f7a265..c8e213b55ec35e8a43985f9162f68d45bf0e5de6 100644 --- a/Code/Radiometry/otbAtmosphericRadiativeTerms.cxx +++ b/Code/Radiometry/otbAtmosphericRadiativeTerms.cxx @@ -20,7 +20,7 @@ namespace otb { -/*********************************** AtmosphericRadiativeTermsSingleChannel***********************************************/ +/************** AtmosphericRadiativeTermsSingleChannel******************/ /** Constructor */ AtmosphericRadiativeTermsSingleChannel::AtmosphericRadiativeTermsSingleChannel() : m_IntrinsicAtmosphericReflectance(0.04), @@ -53,7 +53,7 @@ AtmosphericRadiativeTermsSingleChannel os << indent << "Upward Diffuse Transmittance for aerosols: " << m_UpwardDiffuseTransmittanceForAerosol << std::endl; } -/*********************************** AtmosphericRadiativeTerms **********************************************************/ +/***************** AtmosphericRadiativeTerms **************************/ /**CONSTRUCTOR. */ AtmosphericRadiativeTerms ::AtmosphericRadiativeTerms() @@ -217,7 +217,7 @@ AtmosphericRadiativeTerms { if (m_Values.size() < id + 1) { - for (unsigned int j = 0; j < (id + 1 - m_Values.size()); ++j) + while (id >= m_Values.size()) { ValueType temp = AtmosphericRadiativeTermsSingleChannel::New(); m_Values.push_back(temp); @@ -236,7 +236,7 @@ AtmosphericRadiativeTerms { if (m_Values.size() < id + 1) { - for (unsigned int j = 0; j < (id + 1 - m_Values.size()); ++j) + while (id >= m_Values.size()) { ValueType temp = AtmosphericRadiativeTermsSingleChannel::New(); m_Values.push_back(temp); @@ -250,7 +250,7 @@ AtmosphericRadiativeTerms { if (m_Values.size() < id + 1) { - for (unsigned int j = 0; j < (id + 1 - m_Values.size()); ++j) + while (id >= m_Values.size()) { ValueType temp = AtmosphericRadiativeTermsSingleChannel::New(); m_Values.push_back(temp); @@ -264,7 +264,7 @@ AtmosphericRadiativeTerms { if (m_Values.size() < id + 1) { - for (unsigned int j = 0; j < (id + 1 - m_Values.size()); ++j) + while (id >= m_Values.size()) { ValueType temp = AtmosphericRadiativeTermsSingleChannel::New(); m_Values.push_back(temp); @@ -278,7 +278,7 @@ AtmosphericRadiativeTerms { if (m_Values.size() < id + 1) { - for (unsigned int j = 0; j < (id + 1 - m_Values.size()); ++j) + while (id >= m_Values.size()) { ValueType temp = AtmosphericRadiativeTermsSingleChannel::New(); m_Values.push_back(temp); @@ -292,7 +292,7 @@ AtmosphericRadiativeTerms { if (m_Values.size() < id + 1) { - for (unsigned int j = 0; j < (id + 1 - m_Values.size()); ++j) + while (id >= m_Values.size()) { ValueType temp = AtmosphericRadiativeTermsSingleChannel::New(); m_Values.push_back(temp); @@ -306,7 +306,7 @@ AtmosphericRadiativeTerms { if (m_Values.size() < id + 1) { - for (unsigned int j = 0; j < (id + 1 - m_Values.size()); ++j) + while (id >= m_Values.size()) { ValueType temp = AtmosphericRadiativeTermsSingleChannel::New(); m_Values.push_back(temp); @@ -320,7 +320,7 @@ AtmosphericRadiativeTerms { if (m_Values.size() < id + 1) { - for (unsigned int j = 0; j < (id + 1 - m_Values.size()); ++j) + while (id >= m_Values.size()) { ValueType temp = AtmosphericRadiativeTermsSingleChannel::New(); m_Values.push_back(temp); @@ -334,7 +334,7 @@ AtmosphericRadiativeTerms { if (m_Values.size() < id + 1) { - for (unsigned int j = 0; j < (id + 1 - m_Values.size()); ++j) + while (id >= m_Values.size()) { ValueType temp = AtmosphericRadiativeTermsSingleChannel::New(); m_Values.push_back(temp); @@ -348,7 +348,7 @@ AtmosphericRadiativeTerms { if (m_Values.size() < id + 1) { - for (unsigned int j = 0; j < (id + 1 - m_Values.size()); ++j) + while (id >= m_Values.size()) { ValueType temp = AtmosphericRadiativeTermsSingleChannel::New(); m_Values.push_back(temp); @@ -362,7 +362,7 @@ AtmosphericRadiativeTerms { if (m_Values.size() < id + 1) { - for (unsigned int j = 0; j < (id + 1 - m_Values.size()); ++j) + while (id >= m_Values.size()) { ValueType temp = AtmosphericRadiativeTermsSingleChannel::New(); m_Values.push_back(temp); @@ -488,60 +488,80 @@ double AtmosphericRadiativeTerms ::GetIntrinsicAtmosphericReflectance(unsigned int id) const { + if (id >= m_Values.size()) itkExceptionMacro(<< " band index out of bounds: " << id + << " for " << m_Values.size() << " bands."); return m_Values[id]->GetIntrinsicAtmosphericReflectance(); } double AtmosphericRadiativeTerms ::GetSphericalAlbedo(unsigned int id) const { + if (id >= m_Values.size()) itkExceptionMacro(<< " band index out of bounds: " << id + << " for " << m_Values.size() << " bands."); return m_Values[id]->GetSphericalAlbedo(); } double AtmosphericRadiativeTerms ::GetTotalGaseousTransmission(unsigned int id) const { + if (id >= m_Values.size()) itkExceptionMacro(<< " band index out of bounds: " << id + << " for " << m_Values.size() << " bands."); return m_Values[id]->GetTotalGaseousTransmission(); } double AtmosphericRadiativeTerms ::GetDownwardTransmittance(unsigned int id) const { + if (id >= m_Values.size()) itkExceptionMacro(<< " band index out of bounds: " << id + << " for " << m_Values.size() << " bands."); return m_Values[id]->GetDownwardTransmittance(); } double AtmosphericRadiativeTerms ::GetUpwardTransmittance(unsigned int id) const { + if (id >= m_Values.size()) itkExceptionMacro(<< " band index out of bounds: " << id + << " for " << m_Values.size() << " bands."); return m_Values[id]->GetUpwardTransmittance(); } double AtmosphericRadiativeTerms ::GetUpwardDiffuseTransmittance(unsigned int id) const { + if (id >= m_Values.size()) itkExceptionMacro(<< " band index out of bounds: " << id + << " for " << m_Values.size() << " bands."); return m_Values[id]->GetUpwardDiffuseTransmittance(); } double AtmosphericRadiativeTerms ::GetUpwardDirectTransmittance(unsigned int id) const { + if (id >= m_Values.size()) itkExceptionMacro(<< " band index out of bounds: " << id + << " for " << m_Values.size() << " bands."); return m_Values[id]->GetUpwardDirectTransmittance(); } double AtmosphericRadiativeTerms ::GetUpwardDiffuseTransmittanceForRayleigh(unsigned int id) const { + if (id >= m_Values.size()) itkExceptionMacro(<< " band index out of bounds: " << id + << " for " << m_Values.size() << " bands."); return m_Values[id]->GetUpwardDiffuseTransmittanceForRayleigh(); } double AtmosphericRadiativeTerms ::GetUpwardDiffuseTransmittanceForAerosol(unsigned int id) const { + if (id >= m_Values.size()) itkExceptionMacro(<< " band index out of bounds: " << id + << " for " << m_Values.size() << " bands."); return m_Values[id]->GetUpwardDiffuseTransmittanceForAerosol(); } double AtmosphericRadiativeTerms ::GetWavelengthSpectralBand(unsigned int id) const { + if (id >= m_Values.size()) itkExceptionMacro(<< " band index out of bounds: " << id + << " for " << m_Values.size() << " bands."); return m_Values[id]->GetWavelengthSpectralBand(); } @@ -549,6 +569,8 @@ const AtmosphericRadiativeTerms::ValueType AtmosphericRadiativeTerms ::GetValueByIndex(unsigned int id) const { + if (id >= m_Values.size()) itkExceptionMacro(<< " band index out of bounds: " << id + << " for " << m_Values.size() << " bands."); return m_Values[id]; } diff --git a/Code/Radiometry/otbSarParametricMapFunction.txx b/Code/Radiometry/otbSarParametricMapFunction.txx index 2fb68b428fb9ab5505d271b1ed24c62bc201c6d5..592f8737d3bdde1e5a12fdef314357129035336a 100644 --- a/Code/Radiometry/otbSarParametricMapFunction.txx +++ b/Code/Radiometry/otbSarParametricMapFunction.txx @@ -70,25 +70,26 @@ void SarParametricMapFunction<TInputImage, TCoordRep> ::SetPolynomalSize(const IndexType PolynomalSize) { - unsigned int pointId = 0; - PointType coef; + typedef typename IndexType::IndexValueType IndexValueType; + IndexValueType pointId = 0; + PointType coef; - m_IsInitialize = false; - for(unsigned int i = 0; i <= PolynomalSize[0]; ++i) + m_IsInitialize = false; + for (IndexValueType i = 0; i <= PolynomalSize[0]; ++i) { - coef[0] = i; - for(unsigned int j = 0; j <= PolynomalSize[1]; ++j) + coef[0] = i; + for (IndexValueType j = 0; j <= PolynomalSize[1]; ++j) { - coef[1] = j; - m_Coeff->SetPoint(pointId,coef); - ++pointId; - } + coef[1] = j; + m_Coeff->SetPoint(pointId, coef); + ++pointId; + } } - if(m_PointSet->GetNumberOfPoints() > 0) + if (m_PointSet->GetNumberOfPoints() > 0) { - EvaluateParametricCoefficient(); + EvaluateParametricCoefficient(); } - this->Modified(); + this->Modified(); } template <class TInputImage, class TCoordRep> diff --git a/Code/Radiometry/otbTerraSarCalibrationFunctor.h b/Code/Radiometry/otbTerraSarCalibrationFunctor.h index 5f0a4f20cce4886d0b886cf1cabb6817c08322b3..f71c9d604072d3d8e1f239f07d27be0e53c24936 100644 --- a/Code/Radiometry/otbTerraSarCalibrationFunctor.h +++ b/Code/Radiometry/otbTerraSarCalibrationFunctor.h @@ -22,6 +22,8 @@ #ifndef __otbTerraSarCalibrationFunctor_h #define __otbTerraSarCalibrationFunctor_h +#include "vcl_deprecated_header.h" + #include "otbMath.h" #include "otbTerraSarBrightnessFunctor.h" diff --git a/Code/Radiometry/otbTerraSarCalibrationImageFilter.h b/Code/Radiometry/otbTerraSarCalibrationImageFilter.h index 167ef8f8ccb188fd7575b6d2b60674db546906df..05eb7b03fbae8dc92b2ade7415cdac55581dc8d9 100644 --- a/Code/Radiometry/otbTerraSarCalibrationImageFilter.h +++ b/Code/Radiometry/otbTerraSarCalibrationImageFilter.h @@ -22,6 +22,9 @@ #ifndef __otbTerraSarCalibrationImageFilter_h #define __otbTerraSarCalibrationImageFilter_h + +#include "vcl_deprecated_header.h" + #include "itkImageToImageFilter.h" #include "otbTerraSarCalibrationFunctor.h" #include "itkMetaDataDictionary.h" diff --git a/Code/Visualization/otbImageLayer.txx b/Code/Visualization/otbImageLayer.txx index 68676200849ddd95a785b47b219b865d7c42c185..08d97e5b5cc449879fb7212d79f1a11aea89f578 100644 --- a/Code/Visualization/otbImageLayer.txx +++ b/Code/Visualization/otbImageLayer.txx @@ -258,11 +258,12 @@ ImageLayer<TImage, TOutputImage> // The ouptut stringstream itk::OStringStream oss; oss << otbGetTextMacro("Layer") << ": " << this->GetName(); - oss << std::endl << otbGetTextMacro("Image size") << ": " << m_Image->GetLargestPossibleRegion().GetSize(); + oss << std::endl << otbGetTextMacro("Image size") << ": " << m_Image->GetLargestPossibleRegion().GetSize() << std::endl; + // If we are inside the buffered region if (m_Image->GetBufferedRegion().IsInside(index)) { - oss << std::endl << m_RenderingFunction->Describe(m_Image->GetPixel(index)); + oss << m_RenderingFunction->Describe(m_Image->GetPixel(index)); } else if (m_Quicklook.IsNotNull()) // Else we extrapolate the value from the quicklook diff --git a/Testing/Code/IO/CMakeLists.txt b/Testing/Code/IO/CMakeLists.txt index 66b5fe243ee2f7987b34b904beccafecb4ac8ac3..a57438d3788a4e0db85abc5df64ae448c93401c1 100644 --- a/Testing/Code/IO/CMakeLists.txt +++ b/Testing/Code/IO/CMakeLists.txt @@ -220,6 +220,15 @@ ADD_TEST(ioTvImageFileReaderTIF2MW ${IO_TESTS1} ${TEMP}/ioImageFileReaderTIF2MW.mw ) +# We use the original file as a baseline for the comparison + ADD_TEST(ioTvImageFileReaderPCI2JPG ${IO_TESTS1} + --compare-image ${EPSILON_9} ${INPUTDATA}/QB_Toulouse_Ortho_PAN.tif + ${TEMP}/ioImageFileReaderPCI2JPG.tif + otbImageFileReaderTestFloat + ${INPUTDATA}/QB_Toulouse_Ortho_PAN.pix + ${TEMP}/ioImageFileReaderPCI2JPG.tif ) + + #------------- otbImageIOFactoryNew ADD_TEST(ioTuImageIOFactoryNew ${IO_TESTS1} otbImageIOFactoryNew ) @@ -592,7 +601,9 @@ ADD_TEST(ioTuGDALImageIOCanRead_SPOT5TIF ${IO_TESTS5} otbGDALImageIOTestCanRead ADD_TEST(ioTuGDALImageIOCanRead_HFA ${IO_TESTS5} otbGDALImageIOTestCanRead ${INPUTDATA}/HFAGeoreferenced.img) - +ADD_TEST(ioTuGDALImageIOCanRead_PCI ${IO_TESTS5} otbGDALImageIOTestCanRead + ${INPUTDATA}/QB_Toulouse_Ortho_PAN.pix) + ADD_TEST(ioTvThreadsTest ${IO_TESTS5} otbThreadsTest) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -676,6 +687,7 @@ ADD_TEST(ioTvImageFileReaderPNG2PNG ${IO_TESTS7} otbImageFileReaderTest ${INPUTDATA}/cthead1.png ${TEMP}/ioImageFileReaderPNG2PNG_cthead1.png ) + # RGB ADD_TEST(ioTvImageFileReaderRGB_PNG2PNG ${IO_TESTS7} --compare-image ${EPSILON_9} ${INPUTDATA}/couleurs_extrait.png @@ -683,12 +695,14 @@ ADD_TEST(ioTvImageFileReaderRGB_PNG2PNG ${IO_TESTS7} otbImageFileReaderRGBTest ${INPUTDATA}/couleurs_extrait.png ${TEMP}/ioImageFileReaderRGB_PNG2PNG.png ) + ADD_TEST(ioTvImageFileReaderRGB_PNG2TIFF ${IO_TESTS7} --compare-image ${EPSILON_9} ${BASELINE}/ioImageFileReaderRGB_PNG2TIFF.tiff ${TEMP}/ioImageFileReaderRGB_PNG2TIFF.tiff otbImageFileReaderRGBTest ${INPUTDATA}/couleurs_extrait.png ${TEMP}/ioImageFileReaderRGB_PNG2TIFF.tiff ) + ADD_TEST(ioTvImageFileReaderRGB_BSQ2PNG ${IO_TESTS7} --compare-image ${EPSILON_9} ${INPUTDATA}/poupees.hdr ${TEMP}/ioImageFileReaderRGB_BSQ2PNG_poupees.png @@ -2498,20 +2512,6 @@ ADD_TEST(ioTuTileMapImageSourceNew ${IO_TESTS19} # ${TEMP}/ioTileMapImageSourceToulouse.png # 256) -ADD_TEST(ioTuTileMapFetcherNew ${IO_TESTS19} - otbTileMapFetcherNew ) - -ADD_TEST(ioTvTileMapFetcherTest ${IO_TESTS19} - otbTileMapFetcherTest - 132122 - 95719 - 18 - http://tile.openstreetmap.org/ - #http://andy.sandbox.cloudmade.com/tiles/cycle/ - ${TEMP}/ - 2 - ${TEMP}/) - # We do not perform regression testing here because images on server might change ADD_TEST(ioTvTileMapImageIOFile ${IO_TESTS19} otbTileMapImageIOTest @@ -2797,8 +2797,6 @@ otbIOTests19.cxx otbImageFileReaderServerName.cxx otbTileMapImageSourceNew.cxx otbTileMapImageSource.cxx -otbTileMapFetcherNew.cxx -otbTileMapFetcherTest.cxx otbTileMapImageIOTest.cxx otbTileMapWriter.cxx ) diff --git a/Testing/Code/IO/otbIOTests19.cxx b/Testing/Code/IO/otbIOTests19.cxx index 967b0c3bc5ad9d20e2021a1304ad64114891b90b..7804d3612a337b63dfd541c95f27d6ed3f11c94b 100644 --- a/Testing/Code/IO/otbIOTests19.cxx +++ b/Testing/Code/IO/otbIOTests19.cxx @@ -29,8 +29,6 @@ void RegisterTests() REGISTER_TEST(otbImageFileReaderServerName); REGISTER_TEST(otbTileMapImageSourceNew); REGISTER_TEST(otbTileMapImageSource); - REGISTER_TEST(otbTileMapFetcherNew); - REGISTER_TEST(otbTileMapFetcherTest); REGISTER_TEST(otbTileMapImageIOTest); REGISTER_TEST(otbTileMapWriter); } diff --git a/Testing/Code/IO/otbSarImageMetadataInterfaceTest.cxx b/Testing/Code/IO/otbSarImageMetadataInterfaceTest.cxx index 1e90d7a8f80625ffa6a705eb3228b1862c5facd6..f0153d22b8b10ba88d1514508ac5fc7a15f5c0aa 100644 --- a/Testing/Code/IO/otbSarImageMetadataInterfaceTest.cxx +++ b/Testing/Code/IO/otbSarImageMetadataInterfaceTest.cxx @@ -47,17 +47,26 @@ int otbSarImageMetadataInterfaceTest(int argc, char* argv[]) std::ofstream file; file.open(outputFilename); - file << "GetRadiometricCalibrationScale: " << lImageMetadata->GetRadiometricCalibrationScale() << std::endl; - file << "GetRadiometricCalibrationNoise: " << lImageMetadata->GetRadiometricCalibrationNoise() << std::endl; - file << "GetRadiometricCalibrationAntennaPatternNewGain: " << lImageMetadata->GetRadiometricCalibrationAntennaPatternNewGain() << std::endl; - file << "GetRadiometricCalibrationAntennaPatternOldGain: " << lImageMetadata->GetRadiometricCalibrationAntennaPatternOldGain() << std::endl; - file << "GetRadiometricCalibrationIncidenceAngle: " << lImageMetadata->GetRadiometricCalibrationIncidenceAngle() << std::endl; - file << "GetRadiometricCalibrationRangeSpreadLoss: " << lImageMetadata->GetRadiometricCalibrationRangeSpreadLoss() << std::endl; - file << "GetRadiometricCalibrationNoisePolynomialDegree: " << lImageMetadata->GetRadiometricCalibrationNoisePolynomialDegree() << std::endl; - file << "GetRadiometricCalibrationAntennaPatternNewGainPolynomialDegree: " << lImageMetadata->GetRadiometricCalibrationAntennaPatternNewGainPolynomialDegree() << std::endl; - file << "GetRadiometricCalibrationAntennaPatternOldGainPolynomialDegree: " << lImageMetadata->GetRadiometricCalibrationAntennaPatternOldGainPolynomialDegree() << std::endl; - file << "GetRadiometricCalibrationIncidenceAnglePolynomialDegree: " << lImageMetadata->GetRadiometricCalibrationIncidenceAnglePolynomialDegree() << std::endl; - file << "GetRadiometricCalibrationRangeSpreadLossPolynomialDegree: " << lImageMetadata->GetRadiometricCalibrationRangeSpreadLossPolynomialDegree() << std::endl; + file << "GetRadiometricCalibrationScale : " << lImageMetadata->GetRadiometricCalibrationScale() << std::endl; + file << "NumberOfPoints for GetRadiometricCalibrationNoise() : " << lImageMetadata->GetRadiometricCalibrationNoise()->GetNumberOfPoints() << std::endl; + file << "NumberOfPoints for GetRadiometricCalibrationAntennaPatternNewGain: " + << lImageMetadata->GetRadiometricCalibrationAntennaPatternNewGain()->GetNumberOfPoints() << std::endl; + file << "NumberOfPoints for GetRadiometricCalibrationAntennaPatternOldGain: " + << lImageMetadata->GetRadiometricCalibrationAntennaPatternOldGain()->GetNumberOfPoints() << std::endl; + file << "NumberOfPoints for GetRadiometricCalibrationIncidenceAngle: " + << lImageMetadata->GetRadiometricCalibrationIncidenceAngle()->GetNumberOfPoints() << std::endl; + file << "NumberOfPoints for GetRadiometricCalibrationRangeSpreadLoss: " + << lImageMetadata->GetRadiometricCalibrationRangeSpreadLoss()->GetNumberOfPoints() << std::endl; + file << "NumberOfPoints for GetRadiometricCalibrationNoisePolynomialDegree: " + << lImageMetadata->GetRadiometricCalibrationNoisePolynomialDegree() << std::endl; + file << "NumberOfPoints for GetRadiometricCalibrationAntennaPatternNewGainPolynomialDegree: " + << lImageMetadata->GetRadiometricCalibrationAntennaPatternNewGainPolynomialDegree() << std::endl; + file << "NumberOfPoints for GetRadiometricCalibrationAntennaPatternOldGainPolynomialDegree: " + << lImageMetadata->GetRadiometricCalibrationAntennaPatternOldGainPolynomialDegree() << std::endl; + file << "NumberOfPoints for GetRadiometricCalibrationIncidenceAnglePolynomialDegree: " + << lImageMetadata->GetRadiometricCalibrationIncidenceAnglePolynomialDegree() << std::endl; + file << "NumberOfPoints for GetRadiometricCalibrationRangeSpreadLossPolynomialDegree: " + << lImageMetadata->GetRadiometricCalibrationRangeSpreadLossPolynomialDegree() << std::endl; file.close(); std::cout << lImageMetadata << std::endl; diff --git a/Testing/Code/IO/otbTileMapFetcherNew.cxx b/Testing/Code/IO/otbTileMapFetcherNew.cxx deleted file mode 100644 index 5491e106ffaeb7808d8798f43669472e04179a40..0000000000000000000000000000000000000000 --- a/Testing/Code/IO/otbTileMapFetcherNew.cxx +++ /dev/null @@ -1,30 +0,0 @@ -/*========================================================================= - - Program: ORFEO Toolbox - Language: C++ - Date: $Date$ - Version: $Revision$ - - - Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. - See OTBCopyright.txt for details. - - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ -#include "itkExceptionObject.h" - -#include "otbTileMapFetcher.h" - -int otbTileMapFetcherNew(int argc, char * argv[]) -{ - typedef otb::TileMapFetcher TileMapFetcherType; - typedef TileMapFetcherType::Pointer TileMapFetcherPointerType; - - TileMapFetcherPointerType tmf = TileMapFetcherType::New(); - - return EXIT_SUCCESS; -} diff --git a/Testing/Code/IO/otbTileMapFetcherTest.cxx b/Testing/Code/IO/otbTileMapFetcherTest.cxx deleted file mode 100644 index 272d1665db01d326cf3e7b4d2b21c6e6db0cc499..0000000000000000000000000000000000000000 --- a/Testing/Code/IO/otbTileMapFetcherTest.cxx +++ /dev/null @@ -1,87 +0,0 @@ -/*========================================================================= - - Program: ORFEO Toolbox - Language: C++ - Date: $Date$ - Version: $Revision$ - - - Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. - See OTBCopyright.txt for details. - - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ -#include "itkExceptionObject.h" -#include "otbTileMapFetcher.h" -#include "otbVectorImage.h" -#include "otbImageFileWriter.h" - -#include <stdio.h> - -int otbTileMapFetcherTest(int argc, char * argv[]) -{ - if (argc != 8) - { - std::cout << "<x> <y> <z> <server name> <cache directory> <cache size> <output directory>" << std::endl; - return EXIT_FAILURE; - } - else - { - typedef unsigned char PixelType; - typedef otb::VectorImage<PixelType, 2> ImageType; - typedef otb::ImageFileWriter<ImageType> WriterType; - typedef otb::TileMapFetcher TileMapFetcherType; - typedef TileMapFetcherType::Pointer TileMapFetcherPointerType; - - unsigned int x = static_cast<unsigned int>(atoi(argv[1])); - unsigned int y = static_cast<unsigned int>(atoi(argv[2])); - unsigned int z = static_cast<unsigned int>(atoi(argv[3])); - std::string serverName = argv[4]; - std::string cacheDirectory = argv[5]; - unsigned int cacheSize = static_cast<unsigned int>(atoi(argv[6])); - std::string directory = argv[7]; - - std::ostringstream filename; - std::ostringstream filename2; - std::ostringstream filename3; - - TileMapFetcherPointerType tmf = TileMapFetcherType::New(); - ImageType::Pointer img = ImageType::New(); - WriterType::Pointer writer = WriterType::New(); - - tmf->SetServerName(serverName); - tmf->SetCacheDirectory(cacheDirectory); - tmf->SetCacheSize(cacheSize); - - /** Test fetching tile */ - img = tmf->FetchTile(x, y, z); - - filename << directory; - filename << "otTileMapFetcherTest_Toulouse.png"; - - writer->SetFileName(filename.str()); - writer->SetInput(img); - writer->Update(); - - /** Test out of range */ - img = tmf->FetchTile(x, y, 1); - - filename2 << directory; - filename2 << "otTileMapFetcherTest_OutOfRange.png"; - - writer->SetFileName(filename2.str()); - writer->SetInput(img); - writer->Update(); - - /* Test Cache */ - for (unsigned int i = x; i < x + (5 * cacheSize); i++) - { - img = tmf->FetchTile(i, y, z); - } - } - return EXIT_SUCCESS; -} diff --git a/Testing/Code/OBIA/CMakeLists.txt b/Testing/Code/OBIA/CMakeLists.txt index 46bd283112a8f1b0ce60ee9df1eaaf164bd9a1ba..8492d043e6b727a63223dc835d19d3eb9d722d6b 100644 --- a/Testing/Code/OBIA/CMakeLists.txt +++ b/Testing/Code/OBIA/CMakeLists.txt @@ -1,9 +1,9 @@ IF( NOT OTB_DISABLE_CXX_TESTING AND BUILD_TESTING ) -SET(BASELINE ${OTB_DATA_ROOT}/Baseline/OTB/Images) +SET(BASELINE ${OTB_DATA_ROOT}/Baseline/OTB/Images) SET(BASELINE_FILES ${OTB_DATA_ROOT}/Baseline/OTB/Files) -SET(INPUTDATA ${OTB_DATA_ROOT}/Input) -SET(TEMP ${OTBTesting_BINARY_DIR}/Temporary) +SET(INPUTDATA ${OTB_DATA_ROOT}/Input) +SET(TEMP ${OTBTesting_BINARY_DIR}/Temporary) #Remote sensing images (large images ) IF(OTB_DATA_USE_LARGEINPUT) @@ -39,21 +39,21 @@ ADD_TEST(obTuImageToLabelMapWithAttributesFilterNew ${OBIA_TESTS1} ADD_TEST(obTvImageToLabelMapWithAttributesFilter ${OBIA_TESTS1} otbImageToLabelMapWithAttributesFilter - ${INPUTDATA}/calanques.tif - ${INPUTDATA}/cala_labelled.tif) + ${INPUTDATA}/maur.tif + ${INPUTDATA}/maur_labelled.tif) ADD_TEST(obTuLabelMapSourceNew ${OBIA_TESTS1} - otbLabelMapSourceNew) + otbLabelMapSourceNew) ADD_TEST(obTvLabelMapToVectorDataFilter ${OBIA_TESTS1} otbLabelMapToVectorDataFilter - ${INPUTDATA}/rcc8_mire1.png - ${TEMP}/rcc8_mire2_vectorizer.shp) + ${INPUTDATA}/rcc8_mire1.png + ${TEMP}/rcc8_mire2_vectorizer.shp) ADD_TEST(obTvVectorDataToLabelMapFilter ${OBIA_TESTS1} otbVectorDataToLabelMapFilter - ${INPUTDATA}/vectorIOexample_gis_to_vec.shp - ${TEMP}/vectordataToLabelMap.png) + ${INPUTDATA}/vectorIOexample_gis_to_vec.shp + ${TEMP}/vectordataToLabelMap.png) ADD_TEST(obTuLabelMapToSampleListFilterNew ${OBIA_TESTS1} otbLabelMapToSampleListFilterNew) @@ -66,14 +66,12 @@ ADD_TEST(obTvLabelMapToSampleListFilter ${OBIA_TESTS1} SHAPE::Flusser09 SHAPE::Flusser10 SHAPE::Flusser11) ADD_TEST(obTuLabelMapToVectorDataFilterNew ${OBIA_TESTS1} -otbLabelMapToVectorDataFilterNew -) + otbLabelMapToVectorDataFilterNew) ADD_TEST(obTvLabelMapToVectorDataFilter ${OBIA_TESTS1} -otbLabelMapToVectorDataFilter - ${INPUTDATA}/rcc8_mire1.png - ${TEMP}/rcc8_mire2_vectorizer.shp -) + otbLabelMapToVectorDataFilter + ${INPUTDATA}/rcc8_mire1.png + ${TEMP}/rcc8_mire2_vectorizer.shp) ADD_TEST(obTuLabelMapWithClassLabelToLabeledSampleListFilterNew ${OBIA_TESTS1} otbLabelMapWithClassLabelToLabeledSampleListFilterNew) @@ -86,47 +84,52 @@ ADD_TEST(obTvLabelMapWithClassLabelToLabeledSampleListFilter ${OBIA_TESTS1} SHAPE::Flusser09 SHAPE::Flusser10 SHAPE::Flusser11) ADD_TEST(otbLabelObjectMapVectorizer ${OBIA_TESTS1} - otbLabelObjectMapVectorizer - ${INPUTDATA}/rcc8_mire1.png - rcc8_mire1_label_vectorizer.gml) + otbLabelObjectMapVectorizer + ${INPUTDATA}/rcc8_mire1.png + rcc8_mire1_label_vectorizer.gml) ADD_TEST(obTuLabelObjectToPolygonFunctorNew ${OBIA_TESTS1} -otbLabelObjectToPolygonFunctorNew -) + otbLabelObjectToPolygonFunctorNew) ADD_TEST(obTuMinMaxAttributesLabelMapFilterNew ${OBIA_TESTS1} -otbMinMaxAttributesLabelMapFilterNew -) + otbMinMaxAttributesLabelMapFilterNew) ADD_TEST(obTvMinMaxAttributesLabelMapFilter ${OBIA_TESTS1} - otbMinMaxAttributesLabelMapFilter - ${INPUTDATA}/calanques.tif - ${INPUTDATA}/cala_labelled.tif - ${TEMP}/obTvMinMaxAttributesLabelMapFilter.txt) + otbMinMaxAttributesLabelMapFilter + ${INPUTDATA}/maur.tif + ${INPUTDATA}/maur_labelled.tif + ${TEMP}/obTvMinMaxAttributesLabelMapFilter.txt) ADD_TEST(obTuNormalizeAttributesLabelMapFilterNew ${OBIA_TESTS1} - otbNormalizeAttributesLabelMapFilterNew -) + otbNormalizeAttributesLabelMapFilterNew) ADD_TEST(obTvNormalizeAttributesLabelMapFilter ${OBIA_TESTS1} - otbNormalizeAttributesLabelMapFilter - ${INPUTDATA}/calanques.tif - ${INPUTDATA}/cala_labelled.tif - ${TEMP}/obTvNormalizeAttributesLabelMapFilter.txt) + otbNormalizeAttributesLabelMapFilter + ${INPUTDATA}/maur.tif + ${INPUTDATA}/maur_labelled.tif + ${TEMP}/obTvNormalizeAttributesLabelMapFilter.txt) ADD_TEST(obTuKMeansAttributesLabelMapFilterNew ${OBIA_TESTS1} - otbKMeansAttributesLabelMapFilterNew) + otbKMeansAttributesLabelMapFilterNew) ADD_TEST(obTvKMeansAttributesLabelMapFilter ${OBIA_TESTS1} - otbKMeansAttributesLabelMapFilter - ${INPUTDATA}/calanques.tif - ${INPUTDATA}/cala_labelled.tif - ${TEMP}/obTvKMeansAttributesLabelMapFilter.txt) + otbKMeansAttributesLabelMapFilter + ${INPUTDATA}/maur.tif + ${INPUTDATA}/maur_labelled.tif + ${TEMP}/obTvKMeansAttributesLabelMapFilter.txt) ADD_TEST(obTuRadiometricAttributesLabelMapFilterNew ${OBIA_TESTS1} -otbRadiometricAttributesLabelMapFilterNew -) + otbRadiometricAttributesLabelMapFilterNew) +ADD_TEST(obTuBandsStatisticsAttributesLabelMapFilterNew ${OBIA_TESTS1} + otbBandsStatisticsAttributesLabelMapFilterNew) + +ADD_TEST(obTvBandsStatisticsAttributesLabelMapFilter ${OBIA_TESTS1} + otbBandsStatisticsAttributesLabelMapFilter + ${INPUTDATA}/maur.tif + ${INPUTDATA}/maur_labelled.tif + ${TEMP}/obTvBandsStatisticsAttributesLabelMapFilter.txt) + ADD_TEST(obTuShapeAttributesLabelMapFilterNew ${OBIA_TESTS1} otbShapeAttributesLabelMapFilterNew) @@ -134,26 +137,24 @@ ADD_TEST(obTuStatisticsAttributesLabelMapFilterNew ${OBIA_TESTS1} otbStatisticsAttributesLabelMapFilterNew) ADD_TEST(obTuVectorDataToLabelMapFilterNew ${OBIA_TESTS1} -otbVectorDataToLabelMapFilterNew -) + otbVectorDataToLabelMapFilterNew) ADD_TEST(obTvVectorDataToLabelMapFilter ${OBIA_TESTS1} -otbVectorDataToLabelMapFilter - ${INPUTDATA}/vectorIOexample_gis_to_vec.shp - ${TEMP}/vectordataToLabelMap.png -) + otbVectorDataToLabelMapFilter + ${INPUTDATA}/vectorIOexample_gis_to_vec.shp + ${TEMP}/vectordataToLabelMap.png) # OBIATests2 (need PQXX) IF(OTB_USE_PQXX) ADD_TEST(obTuLabelMapToGISTableFilterNew ${OBIA_TESTS2} - otbLabelMapToGISTableFilterNew) + otbLabelMapToGISTableFilterNew) ADD_TEST(obTuGISTableToLabelMapFilterNew ${OBIA_TESTS2} - otbGISTableToLabelMapFilterNew) + otbGISTableToLabelMapFilterNew) ADD_TEST(obTvLabelMapToGISTableFilter ${OBIA_TESTS2} - otbLabelMapToGISTableFilter + otbLabelMapToGISTableFilter ${INPUTDATA}/rcc8_mire1.png orfeotoolbox_test labelmaptogis_test_table @@ -192,6 +193,7 @@ otbMinMaxAttributesLabelMapFilter.cxx otbNormalizeAttributesLabelMapFilter.cxx otbKMeansAttributesLabelMapFilter.cxx otbRadiometricAttributesLabelMapFilterNew.cxx +otbBandsStatisticsAttributesLabelMapFilter.cxx otbShapeAttributesLabelMapFilterNew.cxx otbStatisticsAttributesLabelMapFilterNew.cxx otbVectorDataToLabelMapFilter.cxx diff --git a/Testing/Code/OBIA/otbBandsStatisticsAttributesLabelMapFilter.cxx b/Testing/Code/OBIA/otbBandsStatisticsAttributesLabelMapFilter.cxx new file mode 100644 index 0000000000000000000000000000000000000000..69a5037a1741adb609b24e926bdfa0408411f3e0 --- /dev/null +++ b/Testing/Code/OBIA/otbBandsStatisticsAttributesLabelMapFilter.cxx @@ -0,0 +1,112 @@ +/*========================================================================= + + Program: ORFEO Toolbox + Language: C++ + Date: $Date$ + Version: $Revision$ + + + Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. + See OTBCopyright.txt for details. + + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#if defined(_MSC_VER) +#pragma warning ( disable : 4786 ) +#endif + +#include <fstream> +#include <iostream> + +#include "otbImage.h" +#include "otbVectorImage.h" +#include "otbImageFileReader.h" +#include "otbImageFileWriter.h" +#include "otbAttributesMapLabelObject.h" +#include "itkLabelImageToLabelMapFilter.h" +#include "otbBandsStatisticsAttributesLabelMapFilter.h" + +const unsigned int Dimension = 2; +typedef unsigned short LabelType; +typedef double PixelType; + +typedef otb::AttributesMapLabelObject<LabelType, Dimension, double> LabelObjectType; +typedef itk::LabelMap<LabelObjectType> LabelMapType; +typedef otb::VectorImage<PixelType, Dimension> VectorImageType; +typedef otb::Image<unsigned int,2> LabeledImageType; + +typedef LabelMapType::LabelObjectContainerType LabelObjectContainerType; +typedef LabelObjectContainerType::const_iterator LabelObjectIterator; + +typedef otb::ImageFileReader<VectorImageType> ReaderType; +typedef otb::ImageFileReader<LabeledImageType> LabeledReaderType; +typedef otb::ImageFileWriter<VectorImageType> WriterType; +typedef otb::ImageFileWriter<LabeledImageType> LabeledWriterType; + +typedef itk::LabelImageToLabelMapFilter<LabeledImageType,LabelMapType> LabelMapFilterType; +typedef otb::BandsStatisticsAttributesLabelMapFilter<LabelMapType,VectorImageType> BandsStatisticsFilterType; + + +int otbBandsStatisticsAttributesLabelMapFilterNew(int argc, char* argv[]) +{ + BandsStatisticsFilterType::Pointer object = BandsStatisticsFilterType::New(); + return EXIT_SUCCESS; +} + +int otbBandsStatisticsAttributesLabelMapFilter(int argc, char* argv[]) +{ + const char * infname = argv[1]; + const char * lfname = argv[2]; + const char * outfname = argv[3]; + + // Filters instanciation + ReaderType::Pointer reader = ReaderType::New(); + LabeledReaderType::Pointer labeledReader = LabeledReaderType::New(); + LabelMapFilterType::Pointer filter = LabelMapFilterType::New(); + BandsStatisticsFilterType::Pointer stats = BandsStatisticsFilterType::New(); + + // Read inputs + reader->SetFileName(infname); + labeledReader->SetFileName(lfname); + + // Make a LabelMap out of it + filter->SetInput(labeledReader->GetOutput()); + filter->SetBackgroundValue(itk::NumericTraits<LabelType>::max()); + + //Compute band statistics attributes + stats->SetInput(filter->GetOutput()); + stats->SetFeatureImage(reader->GetOutput()); + + stats->Update(); + + LabelMapType::Pointer labelMap = stats->GetOutput(); + + // Dump all results in the output file + std::ofstream outfile(outfname); + LabelObjectIterator it = labelMap->GetLabelObjectContainer().begin(); + LabelObjectIterator end = labelMap->GetLabelObjectContainer().end(); + for (; it != end; ++it) + { + LabelType label = it->first; + LabelObjectType::Pointer labelObject = it->second; + + outfile << "Label " << label << " : " << std::endl; + + std::vector<std::string> attributes = labelObject->GetAvailableAttributes(); + std::vector<std::string>::const_iterator attrIt = attributes.begin(); + std::vector<std::string>::const_iterator attrEnd = attributes.end(); + for (; attrIt != attrEnd; ++attrIt) + { + LabelObjectType::AttributesValueType value = labelObject->GetAttribute(attrIt->c_str()); + outfile << " " << *attrIt << " : "<< std::fixed << std::setprecision(6) << value << std::endl; + } + outfile << std::endl; + } + + return EXIT_SUCCESS; +} + diff --git a/Testing/Code/OBIA/otbLabelMapSVMClassifier.cxx b/Testing/Code/OBIA/otbLabelMapSVMClassifier.cxx index 1c7ecafcec3535c200ce8f5f40b3dbefa9541557..66af9c2dc7022f008b9124f52427a8d21876ddc2 100644 --- a/Testing/Code/OBIA/otbLabelMapSVMClassifier.cxx +++ b/Testing/Code/OBIA/otbLabelMapSVMClassifier.cxx @@ -57,14 +57,16 @@ typedef itk::FixedArray<LabelType,1> TrainingVectorTyp typedef itk::Statistics::ListSample<VectorType> ListSampleType; typedef itk::Statistics::ListSample<TrainingVectorType> TrainingListSampleType; typedef otb::LabelMapWithClassLabelToLabeledSampleListFilter<LabelMapType,ListSampleType,TrainingListSampleType> - LabelMap2ListSampleFilterType; + ListSampleFilterType; typedef otb::Functor::VariableLengthVectorToMeasurementVectorFunctor<VectorType> MeasurementVectorFunctorType; typedef otb::SVMSampleListModelEstimator<ListSampleType,TrainingListSampleType, MeasurementVectorFunctorType> SVMEstimatorType; typedef otb::LabelMapSVMClassifier<LabelMapType> ClassifierType; -typedef otb::LabelMapWithClassLabelToClassLabelImageFilter<LabelMapType,LabeledImageType> LabelMapWithClassLabelToClassLabelImageFilterType; +typedef otb::LabelMapWithClassLabelToClassLabelImageFilter + <LabelMapType,LabeledImageType> ClassifImageGeneratorType; + LabelObjectType::Pointer makeTrainingSample(LabelMapType* labelMap, LabelType labelObjectId, LabelType classLabel) { @@ -86,33 +88,37 @@ int otbLabelMapSVMClassifier(int argc, char * argv[]) const char * lfname = argv[2]; const char * outfname = argv[3]; - // SmartPointer instanciation - ReaderType::Pointer reader = ReaderType::New(); - LabeledReaderType::Pointer labeledReader = LabeledReaderType::New(); - LabelMapFilterType::Pointer filter = LabelMapFilterType::New(); - ShapeFilterType::Pointer shapeFilter = ShapeFilterType::New(); - RadiometricFilterType::Pointer radiometricFilter = RadiometricFilterType::New(); - ClassifierType::Pointer classifier = ClassifierType::New(); - - // Inputs + // Filters instanciation + ReaderType::Pointer reader = ReaderType::New(); + LabeledReaderType::Pointer labeledReader = LabeledReaderType::New(); + LabelMapFilterType::Pointer filter = LabelMapFilterType::New(); + ShapeFilterType::Pointer shapeFilter = ShapeFilterType::New(); + RadiometricFilterType::Pointer radiometricFilter = RadiometricFilterType::New(); + LabelMapType::Pointer trainingLabelMap = LabelMapType::New(); + ListSampleFilterType::Pointer labelMap2SampleList = ListSampleFilterType::New(); + SVMEstimatorType::Pointer svmEstim = SVMEstimatorType::New(); + ClassifierType::Pointer classifier = ClassifierType::New(); + ClassifImageGeneratorType::Pointer imGenerator = ClassifImageGeneratorType::New(); + LabeledWriterType::Pointer writer = LabeledWriterType::New(); + + // Read inputs reader->SetFileName(infname); labeledReader->SetFileName(lfname); - // Filter + // Make a LabelMap out of it filter->SetInput(labeledReader->GetOutput()); filter->SetBackgroundValue(itk::NumericTraits<LabelType>::max()); + //Compute shape and radimometric attributes shapeFilter->SetInput(filter->GetOutput()); - radiometricFilter->SetInput(shapeFilter->GetOutput()); radiometricFilter->SetFeatureImage(reader->GetOutput()); radiometricFilter->Update(); - // Build training samples + // Build a sub-LabelMap with class-labeled LabelObject LabelMapType::Pointer labelMap = radiometricFilter->GetOutput(); - LabelMapType::Pointer trainingLabelMap = LabelMapType::New(); - // The following is specific to the input specified in CMakeLists + // The following is very specific to the input specified in CMakeLists // water trainingLabelMap->PushLabelObject(makeTrainingSample(labelMap, 13, 0)); // road @@ -132,7 +138,7 @@ int otbLabelMapSVMClassifier(int argc, char * argv[]) trainingLabelMap->PushLabelObject(makeTrainingSample(labelMap, 161, 4)); trainingLabelMap->PushLabelObject(makeTrainingSample(labelMap, 46, 4)); - LabelMap2ListSampleFilterType::Pointer labelMap2SampleList = LabelMap2ListSampleFilterType::New(); + // Make a ListSample out of trainingLabelMap labelMap2SampleList->SetInputLabelMap(trainingLabelMap); std::vector<std::string> attributes = labelMap->GetLabelObject(0)->GetAvailableAttributes(); @@ -144,13 +150,14 @@ int otbLabelMapSVMClassifier(int argc, char * argv[]) labelMap2SampleList->Update(); - SVMEstimatorType::Pointer svmEstim = SVMEstimatorType::New(); + // Estimate SVM model svmEstim->SetInputSampleList(labelMap2SampleList->GetOutputSampleList()); svmEstim->SetTrainingSampleList(labelMap2SampleList->GetOutputTrainingSampleList()); svmEstim->SetNumberOfClasses(5); svmEstim->Modified(); svmEstim->Update(); + // Classify using the whole LabelMap with estimated model classifier->SetInput(labelMap); classifier->SetModel(svmEstim->GetModel()); @@ -161,10 +168,9 @@ int otbLabelMapSVMClassifier(int argc, char * argv[]) classifier->Update(); - LabelMapWithClassLabelToClassLabelImageFilterType::Pointer imGenerator = LabelMapWithClassLabelToClassLabelImageFilterType::New(); + // Make a labeled image with the classification result imGenerator->SetInput(classifier->GetOutput()); - LabeledWriterType::Pointer writer = LabeledWriterType::New(); writer->SetInput(imGenerator->GetOutput()); writer->SetFileName(outfname); writer->Update(); diff --git a/Testing/Code/OBIA/otbOBIATests1.cxx b/Testing/Code/OBIA/otbOBIATests1.cxx index 993822ec7868a47ad06b4b2f007179e8c0ccabfd..7ecc330f96653b1f40bf5a2d5b516988b5aee1e3 100644 --- a/Testing/Code/OBIA/otbOBIATests1.cxx +++ b/Testing/Code/OBIA/otbOBIATests1.cxx @@ -48,6 +48,8 @@ REGISTER_TEST(otbNormalizeAttributesLabelMapFilter); REGISTER_TEST(otbKMeansAttributesLabelMapFilterNew); REGISTER_TEST(otbKMeansAttributesLabelMapFilter); REGISTER_TEST(otbRadiometricAttributesLabelMapFilterNew); +REGISTER_TEST(otbBandsStatisticsAttributesLabelMapFilterNew); +REGISTER_TEST(otbBandsStatisticsAttributesLabelMapFilter); REGISTER_TEST(otbShapeAttributesLabelMapFilterNew); REGISTER_TEST(otbStatisticsAttributesLabelMapFilterNew); REGISTER_TEST(otbVectorDataToLabelMapFilterNew); diff --git a/Testing/Code/Projections/CMakeLists.txt b/Testing/Code/Projections/CMakeLists.txt index bd605777671f0a87eb4d9d1028ec77d56c3afecf..651b0d3d256687e7225d1ad26fa7cb7cf163bc9c 100644 --- a/Testing/Code/Projections/CMakeLists.txt +++ b/Testing/Code/Projections/CMakeLists.txt @@ -364,6 +364,7 @@ ADD_TEST(prTlOrthoRectificationSPOT5 ${PROJECTIONS_TESTS2} -5 39 N + 5 ) ENDIF(OTB_DATA_USE_LARGEINPUT) @@ -601,7 +602,7 @@ ADD_TEST(prTvPhysicalToRPCSensorModelImageFilter ${PROJECTIONS_TESTS4} ) ADD_TEST(prTuotbGenericRSResampleImageFilterNew ${PROJECTIONS_TESTS4} - otbGenericRSResampleImageFilter + otbGenericRSResampleImageFilterNew ) IF(OTB_DATA_USE_LARGEINPUT) @@ -615,6 +616,33 @@ ADD_TEST(prTvotbGenericRSResampleImageFilter ${PROJECTIONS_TESTS4} 1 ${TEMP}/prTvotbGenericRSResampleImageFilterOutput.tif ) + + +# Experimental : Set a variable with the several sensors image +# paths +# TODO : parse it with a cmake file in OTB-Data-LargeInput directory +# Done here for the moment + +SET(SENSOR_TYPES + "QUICKBIRD/TOULOUSE/000000128955_01_P001_PAN/02APR01105228-P1BS-000000128955_01_P001.TIF" + "GEOEYE/LES_ROCHES/po_350134_bgrn_0000000.tif" + "WORLDVIEW2/ROME/WV-2_standard_8band_bundle_16bit/052298844010_01_P001_MUL/09DEC10103019-M2AS-052298844010_01_P001.TIF" +) + +FOREACH( file ${SENSOR_TYPES}) + # Get the sensor name + SET(sharp_regexp "([0-9A-Za-z_]*)[ ]*/[ ]*(.*)") + STRING(REGEX REPLACE "${sharp_regexp}" "\\1" sensor_name "${file}") + # Tests + ADD_TEST(prTvotbGenericRSResampleImageFilterFromMap_${sensor_name} ${PROJECTIONS_TESTS4} + otbGenericRSResampleImageFilterFromMap + ${LARGEINPUT}/${file} + 15 + 0 + ${TEMP}/prTvotbGenericRSResampleImageFilterOutputFromMap_${sensor_name}.tif + ) +ENDFOREACH( file ${SENSOR_TYPES}) + ENDIF(OTB_DATA_USE_LARGEINPUT) diff --git a/Testing/Code/Projections/otbGenericRSResampleImageFilter.cxx b/Testing/Code/Projections/otbGenericRSResampleImageFilter.cxx index 06a7224ac6d4dc982a8062127622179cc0a359ec..d18c3ee225eda665e3ed5fd1954e027ba2a29772 100644 --- a/Testing/Code/Projections/otbGenericRSResampleImageFilter.cxx +++ b/Testing/Code/Projections/otbGenericRSResampleImageFilter.cxx @@ -18,8 +18,6 @@ #include "otbGenericRSResampleImageFilter.h" #include "otbVectorImage.h" -#include "itkVector.h" -#include "otbImage.h" #include "otbImageFileReader.h" #include "otbStreamingImageFileWriter.h" @@ -29,107 +27,181 @@ // Default value #include "itkPixelBuilder.h" +// Extract ROI +#include "otbMultiChannelExtractROI.h" + +// Images definition +const unsigned int Dimension = 2; +typedef double PixelType; +typedef otb::VectorImage<PixelType, Dimension> ImageType; +typedef ImageType::SizeType SizeType; + +typedef otb::GenericRSResampleImageFilter<ImageType, + ImageType> ImageResamplerType; +typedef ImageResamplerType::OriginType OriginType; +typedef ImageResamplerType::SpacingType SpacingType; + +typedef otb::ImageFileReader<ImageType> ReaderType; +typedef otb::StreamingImageFileWriter<ImageType> WriterType; + +int otbGenericRSResampleImageFilterNew(int argc, char* argv[]) +{ + // SmartPointer instanciation + ImageResamplerType::Pointer resampler = ImageResamplerType::New(); + return EXIT_SUCCESS; +} + int otbGenericRSResampleImageFilter(int argc, char* argv[]) { - // Images definition - const unsigned int Dimension = 2; - typedef double PixelType; - typedef otb::VectorImage<PixelType, Dimension> ImageType; - typedef ImageType::SizeType SizeType; - - typedef itk::Vector<PixelType, 2> DeformationValueType; - typedef otb::Image<DeformationValueType, Dimension> DeformationFieldType; - - typedef otb::GenericRSResampleImageFilter<ImageType, - ImageType> ImageResamplerType; - typedef ImageResamplerType::OriginType OriginType; - typedef ImageResamplerType::SpacingType SpacingType; - // SmartPointer instanciation ImageResamplerType::Pointer resampler = ImageResamplerType::New(); + + const char * infname = argv[1]; + const char * outfname = argv[6]; + unsigned int isize = atoi(argv[2]); + double iGridSpacing = atof(argv[3]); + int useInRpc = atoi(argv[4]); + int useOutRpc = atoi(argv[5]); - // Check if it's a unit test. - if (argc == 7 ) - { - const char * infname = argv[1]; - const char * outfname = argv[6]; - unsigned int isize = atoi(argv[2]); - double iGridSpacing = atof(argv[3]); - int useInRpc = atoi(argv[4]); - int useOutRpc = atoi(argv[5]); - - typedef otb::ImageFileReader<ImageType> ReaderType; - ReaderType::Pointer reader = ReaderType::New(); - - // Read the input image - reader->SetFileName(infname); - reader->UpdateOutputInformation(); - - // Fill the output size with the user selection - SizeType size; - size.Fill(isize); - - // Set the origin & the spacing of the output - OriginType origin; - origin[0] = 367340; - origin[1] = 4.83467e+06; - - SpacingType spacing; - spacing[0] = 0.6; - spacing[1] = -0.6; - - // Build the ouput projection ref : UTM ref - OGRSpatialReference oSRS; - oSRS.SetProjCS("UTM"); - oSRS.SetUTM(31, true); - char * utmRef = NULL; - oSRS.exportToWkt(&utmRef); - - // Deformation Field spacing - SpacingType gridSpacing; - gridSpacing[0] = iGridSpacing; - gridSpacing[1] = -iGridSpacing; - - // Default value builder - ImageType::PixelType defaultValue; - itk::PixelBuilder<ImageType::PixelType>::Zero(defaultValue, - reader->GetOutput()->GetNumberOfComponentsPerPixel()); - - // Set the Resampler Parameters - resampler->SetInput(reader->GetOutput()); - resampler->SetDeformationFieldSpacing(gridSpacing); - resampler->SetOutputOrigin(origin); - resampler->SetOutputSize(size); - resampler->SetOutputSpacing(spacing); - resampler->SetOutputProjectionRef(utmRef); -// resampler->SetInputProjectionRef(reader->GetOutput()->GetProjectionRef()); -// resampler->SetInputKeywordList(reader->GetOutput()->GetImageKeywordlist()); - resampler->SetEdgePaddingValue(defaultValue); - if (useInRpc) - { - resampler->SetInputRpcGridSize(20); - resampler->EstimateInputRpcModelOn(); - } - - if (useOutRpc) - { - resampler->SetOutputRpcGridSize(20); - resampler->EstimateOutputRpcModelOn(); - } + + ReaderType::Pointer reader = ReaderType::New(); + + // Read the input image + reader->SetFileName(infname); + reader->UpdateOutputInformation(); + + // Fill the output size with the user selection + SizeType size; + size.Fill(isize); + + // Set the origin & the spacing of the output + OriginType origin; + origin[0] = 367340; + origin[1] = 4.83467e+06; + + SpacingType spacing; + spacing[0] = 0.6; + spacing[1] = -0.6; + + // Build the ouput projection ref : UTM ref + OGRSpatialReference oSRS; + oSRS.SetProjCS("UTM"); + oSRS.SetUTM(31, true); + char * utmRef = NULL; + oSRS.exportToWkt(&utmRef); + + // Deformation Field spacing + SpacingType gridSpacing; + gridSpacing[0] = iGridSpacing; + gridSpacing[1] = -iGridSpacing; + + // Default value builder + ImageType::PixelType defaultValue; + itk::PixelBuilder<ImageType::PixelType>::Zero(defaultValue, + reader->GetOutput()->GetNumberOfComponentsPerPixel()); - // Write the resampled image - typedef otb::StreamingImageFileWriter<ImageType> WriterType; - WriterType::Pointer writer= WriterType::New(); - writer->SetTilingStreamDivisions(4); - writer->SetFileName(outfname); - writer->SetInput(resampler->GetOutput()); - writer->Update(); + // Set the Resampler Parameters + resampler->SetInput(reader->GetOutput()); + resampler->SetDeformationFieldSpacing(gridSpacing); + resampler->SetOutputOrigin(origin); + resampler->SetOutputSize(size); + resampler->SetOutputSpacing(spacing); + resampler->SetOutputProjectionRef(utmRef); + resampler->SetEdgePaddingValue(defaultValue); + if (useInRpc) + { + resampler->SetInputRpcGridSize(20); + resampler->EstimateInputRpcModelOn(); } - else + + if (useOutRpc) { - std::cout <<"Unit Test " << std::endl; + resampler->SetOutputRpcGridSize(20); + resampler->EstimateOutputRpcModelOn(); } + + // Write the resampled image + WriterType::Pointer writer= WriterType::New(); + writer->SetTilingStreamDivisions(4); + writer->SetFileName(outfname); + writer->SetInput(resampler->GetOutput()); + writer->Update(); + + return EXIT_SUCCESS; +} + + +int otbGenericRSResampleImageFilterFromMap(int argc, char* argv[]) +{ + typedef otb::MultiChannelExtractROI<PixelType,PixelType> ExtractROIType; + + // SmartPointer instanciation + ExtractROIType::Pointer extractor = ExtractROIType::New(); + ImageResamplerType::Pointer resampler = ImageResamplerType::New(); + + const char * infname = argv[1]; + const char * outfname = argv[4]; + double iGridSpacing = atof(argv[2]); + int useInRpc = atoi(argv[3]); + + // Reader Instanciation + ReaderType::Pointer reader = ReaderType::New(); + reader->SetFileName(infname); + reader->UpdateOutputInformation(); + + SpacingType spacing; + spacing[0] = 2.5; + spacing[1] = -2.5; + + // Deformation Field spacing + SpacingType gridSpacing; + gridSpacing[0] = iGridSpacing; + gridSpacing[1] = -iGridSpacing; + + // Default value builder + ImageType::PixelType defaultValue; + itk::PixelBuilder<ImageType::PixelType>::Zero(defaultValue, + reader->GetOutput()->GetNumberOfComponentsPerPixel()); + + // Extract a roi centered on the input center + ImageType::RegionType roi; + ImageType::IndexType roiIndex; + SizeType roiSize; + + // Fill the size + roiSize.Fill(1000); + + // Fill the start index + roiIndex[0] = (unsigned int)((reader->GetOutput()->GetLargestPossibleRegion().GetSize()[0] - roiSize[0]) /2); + roiIndex[1] = (unsigned int)((reader->GetOutput()->GetLargestPossibleRegion().GetSize()[1] - roiSize[1]) /2); + + roi.SetIndex(roiIndex); + roi.SetSize(roiSize); + + extractor->SetExtractionRegion(roi); + extractor->SetInput(reader->GetOutput()); + extractor->UpdateOutputInformation(); + + // Set the Resampler Parameters + resampler->SetInput(extractor->GetOutput()); + resampler->SetDeformationFieldSpacing(gridSpacing); + resampler->SetOutputParametersFromMap("UTM",spacing); - return 0; + if (useInRpc) + { + resampler->SetInputRpcGridSize(20); + resampler->EstimateInputRpcModelOn(); + } + + // Write the resampled image + typedef otb::StreamingImageFileWriter<ImageType> WriterType; + WriterType::Pointer writer= WriterType::New(); + writer->SetTilingStreamDivisions(); + writer->SetFileName(outfname); + writer->SetInput(resampler->GetOutput()); + writer->Update(); + + return EXIT_SUCCESS; } + diff --git a/Testing/Code/Projections/otbOrthoRectificationFilter.cxx b/Testing/Code/Projections/otbOrthoRectificationFilter.cxx index 73556babaeb64a7f34723d5f9d415a09167933ea..ceb1148352710967b0b54a3791d6703c603e1ae1 100644 --- a/Testing/Code/Projections/otbOrthoRectificationFilter.cxx +++ b/Testing/Code/Projections/otbOrthoRectificationFilter.cxx @@ -76,7 +76,7 @@ int otbOrthoRectificationFilter(int argc, char* argv[]) ImageType::SizeType size; size[0] = atoi(argv[5]); // X size size[1] = atoi(argv[6]); //Y size - orthoRectifFilter->SetOutputSize(size); + orthoRectifFilter->SetSize(size); ImageType::SpacingType spacing; spacing[0] = atof(argv[7]); @@ -91,7 +91,7 @@ int otbOrthoRectificationFilter(int argc, char* argv[]) utmMapProjection->SetZone(atoi(argv[9])); utmMapProjection->SetHemisphere(argv[10][0]); orthoRectifFilter->SetMapProjection(utmMapProjection); - + // Deformation Field spacing ImageType::SpacingType gridSpacing; gridSpacing[0] = atof(argv[11]); diff --git a/Testing/Code/Projections/otbProjectionsTests4.cxx b/Testing/Code/Projections/otbProjectionsTests4.cxx index 5b7fb5334f22a8f7c9cef57ba99e36231a0f26cd..b7c7a4e802b46916ae7bdab6cb8edebf65e62ffc 100644 --- a/Testing/Code/Projections/otbProjectionsTests4.cxx +++ b/Testing/Code/Projections/otbProjectionsTests4.cxx @@ -27,5 +27,7 @@ void RegisterTests() { REGISTER_TEST(otbPhysicalToRPCSensorModelImageFilter); + REGISTER_TEST(otbGenericRSResampleImageFilterNew); REGISTER_TEST(otbGenericRSResampleImageFilter); + REGISTER_TEST(otbGenericRSResampleImageFilterFromMap); } diff --git a/Testing/Code/Radiometry/CMakeLists.txt b/Testing/Code/Radiometry/CMakeLists.txt index dd12f31b52487d7757c2ed62e101019261ae99d1..ca69e7980dd84c11e907b4a1c089d48c781dc511 100644 --- a/Testing/Code/Radiometry/CMakeLists.txt +++ b/Testing/Code/Radiometry/CMakeLists.txt @@ -528,6 +528,12 @@ ADD_TEST(raTuAtmosphericRadiativeTermsSingleChannelNew ${RADIOMETRY_TESTS3} otbAtmosphericRadiativeTermsSingleChannelNew ) +ADD_TEST(raTvAtmosphericRadiativeTermsTest ${RADIOMETRY_TESTS3} + --compare-ascii ${NOTOL} ${BASELINE_FILES}/raTvAtmosphericRadiativeTermsTest.txt + ${TEMP}/raTvAtmosphericRadiativeTermsTest.txt + otbAtmosphericRadiativeTermsTest + ${TEMP}/raTvAtmosphericRadiativeTermsTest.txt +) # ------- otb::ReflectanceToSurfaceReflectanceImageFilter ------------------------------ ADD_TEST(raTuReflectanceToSurfaceReflectanceImageFilterNew ${RADIOMETRY_TESTS3} diff --git a/Testing/Code/Radiometry/otbAtmosphericRadiativeTermsTest.cxx b/Testing/Code/Radiometry/otbAtmosphericRadiativeTermsTest.cxx index 9d25f71b71c4b2ace43ec82344e0c026ad8db4ea..05ffbda62571dba8f4acf29ad9a7c4fee84b4ea6 100644 --- a/Testing/Code/Radiometry/otbAtmosphericRadiativeTermsTest.cxx +++ b/Testing/Code/Radiometry/otbAtmosphericRadiativeTermsTest.cxx @@ -19,6 +19,8 @@ #pragma warning ( disable : 4786 ) #endif +#include <fstream> + #include "itkExceptionObject.h" #include "otbAtmosphericRadiativeTerms.h" #include <cstdlib> @@ -40,6 +42,98 @@ int otbAtmosphericRadiativeTermsSingleChannelNew(int argc, char * argv[]) // Instantiating object AtmosphericRadiativeTermsType::Pointer object = AtmosphericRadiativeTermsType::New(); + std::cout << object << std::endl; return EXIT_SUCCESS; } +std::ostream& operator<<(std::ostream& os, const otb::AtmosphericRadiativeTerms::DataVectorType& values) +{ + os << "["; + if (values.size() > 0) + { + os << values[0]; + } + for (unsigned int i = 1; i < values.size(); ++i) + { + os << ", "; + os << values[i]; + } + os << "]\n"; + return os; +} + +int otbAtmosphericRadiativeTermsTest(int argc, char * argv[]) +{ + char * filename = argv[1]; + std::ofstream file; + file.open(filename); + + typedef otb::AtmosphericRadiativeTerms AtmosphericRadiativeTermsType; + + // Instantiating object + AtmosphericRadiativeTermsType::Pointer object = AtmosphericRadiativeTermsType::New(); + object->ValuesInitialization(3); + + // Set the values + AtmosphericRadiativeTermsType::DataVectorType values; + values.push_back(1.0); + values.push_back(2.0); + values.push_back(3.0); + + object->SetIntrinsicAtmosphericReflectances(values); + object->SetSphericalAlbedos(values); + object->SetTotalGaseousTransmissions(values); + object->SetDownwardTransmittances(values); + object->SetUpwardTransmittances(values); + object->SetUpwardDiffuseTransmittances(values); + object->SetUpwardDirectTransmittances(values); + object->SetUpwardDiffuseTransmittancesForRayleigh(values); + object->SetUpwardDiffuseTransmittancesForAerosol(values); + object->SetWavelengthSpectralBand(values); + + file << object << std::endl; + + file << "\n\n TESTING ACCESSOR OUT OF RANGE \n\n"; + object->SetSphericalAlbedo(3, 4.0); + object->SetTotalGaseousTransmission(5, 5.0); + object->SetDownwardTransmittance(6, 6.0); + object->SetUpwardTransmittance(7, 7.0); + object->SetUpwardDiffuseTransmittance(8, 8.0); + object->SetUpwardDirectTransmittance(9, 9.0); + object->SetUpwardDiffuseTransmittanceForRayleigh(10, 10.0); + object->SetUpwardDiffuseTransmittanceForAerosol(11, 11.0); + object->SetWavelengthSpectralBand(12, 12.0); + + file << object << std::endl; + + file << "\n\n TESTING ACCESSOR \n\n"; + file << object->GetIntrinsicAtmosphericReflectances() << std::endl; + file << object->GetSphericalAlbedos() << std::endl; + file << object->GetTotalGaseousTransmissions() << std::endl; + file << object->GetDownwardTransmittances() << std::endl; + file << object->GetUpwardTransmittances() << std::endl; + file << object->GetUpwardDiffuseTransmittances() << std::endl; + file << object->GetUpwardDirectTransmittances() << std::endl; + file << object->GetUpwardDiffuseTransmittancesForRayleigh() << std::endl; + file << object->GetUpwardDiffuseTransmittancesForAerosol() << std::endl; + file << object->GetWavelengthSpectralBand() << std::endl; + + file << "\n\n TESTING ACCESSOR WITH INDEX\n\n"; + file << object->GetIntrinsicAtmosphericReflectance(0) << std::endl; + file << object->GetSphericalAlbedo(5) << std::endl; + file << object->GetTotalGaseousTransmission(5) << std::endl; + file << object->GetDownwardTransmittance(5) << std::endl; + file << object->GetUpwardTransmittance(5) << std::endl; + file << object->GetUpwardDiffuseTransmittance(5) << std::endl; + file << object->GetUpwardDirectTransmittance(5) << std::endl; + file << object->GetUpwardDiffuseTransmittanceForRayleigh(5) << std::endl; + file << object->GetUpwardDiffuseTransmittanceForAerosol(5) << std::endl; + file << object->GetWavelengthSpectralBand(12) << std::endl; + file << std::endl; + file << object->GetValueByIndex(5) << std::endl; + + + file.close(); + + return EXIT_SUCCESS; +} diff --git a/Testing/Code/Radiometry/otbRadiometryTests3.cxx b/Testing/Code/Radiometry/otbRadiometryTests3.cxx index 38563b860149c002ff08dee367cf1f5e2d1e4bc4..7ca32e0a7483e259939a633155f891e98b444064 100644 --- a/Testing/Code/Radiometry/otbRadiometryTests3.cxx +++ b/Testing/Code/Radiometry/otbRadiometryTests3.cxx @@ -34,6 +34,7 @@ void RegisterTests() REGISTER_TEST(otbSIXSTraitsComputeAtmosphericParametersTest); REGISTER_TEST(otbAtmosphericRadiativeTermsNew); REGISTER_TEST(otbAtmosphericRadiativeTermsSingleChannelNew); + REGISTER_TEST(otbAtmosphericRadiativeTermsTest); REGISTER_TEST(otbReflectanceToSurfaceReflectanceImageFilterNew); REGISTER_TEST(otbReflectanceToSurfaceReflectanceImageFilterTest); REGISTER_TEST(otbReflectanceToSurfaceReflectanceImageFilterTest2); diff --git a/Testing/Utilities/CMakeLists.txt b/Testing/Utilities/CMakeLists.txt index dd6ddce38a17602a484c0ce23456d3cf2ba37403..94a4d72111e90803687c9057d3ac5ea552307b12 100644 --- a/Testing/Utilities/CMakeLists.txt +++ b/Testing/Utilities/CMakeLists.txt @@ -72,6 +72,14 @@ ADD_TEST(utTvOssimTileMapModelTestToulouse ${UTILITIES_TESTS} ADD_TEST(utTvOssimpluginsHermiteInterpolationTest ${UTILITIES_TESTS} ossimpluginsHermiteInterpolationTest) +IF(OTB_DATA_USE_LARGEINPUT) +ADD_TEST(utTvOssimpluginsHermiteInterpolationPlateformPositionRadarSat2Test ${UTILITIES_TESTS} + ossimpluginsHermiteInterpolationPlateformPositionTest + ${IMAGEDATA}/RADARSAT2/ALTONA/Fine_Quad-Pol_Dataset/PK6621_DK406_FQ9_20080405_124900_HH_VV_HV_VH_SLC_Altona/product.xml + ) +ENDIF(OTB_DATA_USE_LARGEINPUT) + + # ------- lib otbsvm ------------------------------ ADD_TEST(utTuSvmKernelFunctorTest ${UTILITIES_TESTS} @@ -479,6 +487,7 @@ ossimElevManagerTest.cxx ossimXmlDocumentTest.cxx ossimTileMapModelTest.cxx ossimpluginsHermiteInterpolation.cxx +ossimpluginsHermiteInterpolationPlateformPosition.cxx svmGenericKernelFunctor.cxx svmTest.cxx svmGenericKernelTest.cxx diff --git a/Testing/Utilities/ossimpluginsHermiteInterpolationPlateformPosition.cxx b/Testing/Utilities/ossimpluginsHermiteInterpolationPlateformPosition.cxx new file mode 100644 index 0000000000000000000000000000000000000000..731635f38190d8c8334478c4f0255ff21289c64e --- /dev/null +++ b/Testing/Utilities/ossimpluginsHermiteInterpolationPlateformPosition.cxx @@ -0,0 +1,124 @@ +/*========================================================================= + + Program: ORFEO Toolbox + Language: C++ + Date: $Date$ + Version: $Revision$ + + + Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. + See OTBCopyright.txt for details. + + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#include <cstdlib> + +#include <iostream> +#include <iomanip> +#include <cmath> + + +#include "ossim/base/ossimCommon.h" +#include "ossim/init/ossimInit.h" +#include "otb/HermiteInterpolator.h" +#include "otb/PlatformPosition.h" +#include "otb/Ephemeris.h" +#include "otb/JSDDateTime.h" + +#include "itkTimeProbe.h" +#include "projection/ossimProjection.h" +#include "projection/ossimProjectionFactoryRegistry.h" +#include "ossim/ossimPluginProjectionFactory.h" +#include "ossim/base/ossimKeywordlist.h" + + +int ossimpluginsHermiteInterpolationPlateformPositionTest(int argc, char * argv[]) +{ + ossimInit::instance()->initialize(argc, argv); + + if(argc!=2) + { + std::cout << "<input filename>" << std::endl; + return EXIT_FAILURE; + } + + char * filename = argv[1]; + + /** Don't use FactoryRegistry because of its default factory that can conflict + * with plugins factor (cf. TSX .tif image read as QB)*/ + // test ossim plugin factory + ossimProjection * projection = ossimplugins::ossimPluginProjectionFactory::instance()->createProjection( + ossimFilename(filename), 0); + + // if ossim plugins factory failed, then test ossim factory + if (!projection) + { + projection = ossimProjectionFactoryRegistry::instance()->createProjection(ossimFilename(filename), 0); + if (!projection) + { + std::cout<<"OSSIM Instanciate projection FAILED ! "; + return EXIT_FAILURE; + } + } + + + ossimKeywordlist geom; + std::cout << "Read ossim Keywordlist..."; + + bool hasMetaData = false; + + hasMetaData = projection->saveState(geom); + + if (!hasMetaData) + { + std::cout << "Bad metadata parsing " << std::endl; + return EXIT_FAILURE; + } + + + // Get plateform position count : + const char* platform_positions_count_str = geom.find("platform_positions_count"); + unsigned int platform_positions_count = atoi(platform_positions_count_str); + std::cout << "plateform_positions_count :" << platform_positions_count << std::endl; + + ossimplugins::PlatformPosition * platform_position; + hasMetaData = platform_position->loadState(geom); + + if (!hasMetaData) + { + std::cout << "Bad metadata parsing " << std::endl; + return EXIT_FAILURE; + } + + for(unsigned int i = 0 ; i < platform_position->getNbrData() ; ++i) + { + ossimplugins::Ephemeris * ephemeris = platform_position->getData(i); + double * position = ephemeris->get_position(); + double * velocity = ephemeris->get_vitesse(); + ossimplugins::JSDDateTime date = ephemeris->get_date(); + + ossimplugins::Ephemeris * interpolateEphemeris = platform_position->Interpolate(date); + + double * interpolatePosition = interpolateEphemeris->get_position(); + double * interpolateVelocity = interpolateEphemeris->get_vitesse(); + ossimplugins::JSDDateTime interpolateDate = interpolateEphemeris->get_date(); + + double diffPosition = 0.0; + double diffVelocity = 0.0; + + for(unsigned int j = 0 ; j <3 ; ++j) + { + diffPosition += (interpolatePosition[j]-position[j]) * (interpolatePosition[j]-position[j]); + diffVelocity += (interpolateVelocity[j]-velocity[j]) * (interpolateVelocity[j]-velocity[j]); + } + std::cout << "Diff position ["<< i<<"] =" << diffPosition << std::endl; + std::cout << "Diff velocity ["<< i<<"] =" << diffVelocity << std::endl; + } + + return EXIT_SUCCESS; +} diff --git a/Testing/Utilities/otbUtilitiesTests.cxx b/Testing/Utilities/otbUtilitiesTests.cxx index 091db3b089736ba0fb02ebd900f3dc9089e07426..d6abf071d14f06891c80228462f0f36713d7d0d5 100644 --- a/Testing/Utilities/otbUtilitiesTests.cxx +++ b/Testing/Utilities/otbUtilitiesTests.cxx @@ -32,6 +32,7 @@ REGISTER_TEST(ossimElevManagerTest); REGISTER_TEST(ossimXmlDocumentTest); REGISTER_TEST(ossimTileMapModelTest); REGISTER_TEST(ossimpluginsHermiteInterpolationTest); +REGISTER_TEST(ossimpluginsHermiteInterpolationPlateformPositionTest); REGISTER_TEST(svmGenericKernelFunctor); REGISTER_TEST(svmTest); REGISTER_TEST(svmGenericKernelTest); diff --git a/Utilities/otbossimplugins/ossim/otb/PlatformPosition.cpp b/Utilities/otbossimplugins/ossim/otb/PlatformPosition.cpp index 22fa9c7e3c58848db739013ec6d77ac53f5982af..3baf9eff91013bea1f236392840a1d783d0d54b8 100644 --- a/Utilities/otbossimplugins/ossim/otb/PlatformPosition.cpp +++ b/Utilities/otbossimplugins/ossim/otb/PlatformPosition.cpp @@ -105,7 +105,6 @@ Ephemeris* PlatformPosition::Interpolate(JSDDateTime date) double * y = new double[_nbrData]; double * yd = new double[_nbrData]; double dt = 0.0; - bool echIrreg = false; double d; x[0] = 0.0 ; @@ -115,24 +114,6 @@ Ephemeris* PlatformPosition::Interpolate(JSDDateTime date) * JOURCIVIL_LENGTH + _data[i]->get_date().get_second() - _data[0]->get_date().get_second() + _data[i]->get_date().get_decimal() - _data[0]->get_date().get_decimal(); - d = x[i] - x[i-1] ; - - /* - * Non increasing time - */ - if (d <= 0.0)/* Non increasing time */ - { - delete ephem; - ephem = NULL; - } - else if (i == 1) - { - dt = d ; - } - else if (fabs (d-dt) >= 1.0e-4) /* Irregular sampling */ - { - echIrreg = true; - } } if (ephem != NULL) @@ -143,10 +124,6 @@ Ephemeris* PlatformPosition::Interpolate(JSDDateTime date) + date.get_second() - _data[0]->get_date().get_second() + date.get_decimal() - _data[0]->get_date().get_decimal(); - /* If nPts odd or if the searched date is not situated in the middle of the ephemeris list -> Lagrange */ - d = (dt - x[_nbrData/2-1]) / (x[_nbrData/2] - x[_nbrData/2-1]) ; - - /* Computation by Everett */ /*---------------------*/ double pos[3]; @@ -160,7 +137,6 @@ Ephemeris* PlatformPosition::Interpolate(JSDDateTime date) } HermiteInterpolator interpolator(_nbrData,x,y,yd); interpolator.Interpolate(dt, pos[j], vit[j]); - } ephem->set_position(pos); ephem->set_vitesse(vit); @@ -182,6 +158,21 @@ void PlatformPosition::setData(Ephemeris** data, int nbrData) _nbrData = nbrData; } +Ephemeris* PlatformPosition::getData(int noData) const +{ + if(noData >=0 && noData < _nbrData) + { + return _data[noData]; + } + return NULL; +} + +int PlatformPosition::getNbrData() const +{ + return _nbrData; +} + + bool PlatformPosition::saveState(ossimKeywordlist& kwl, const char* prefix) const { diff --git a/Utilities/otbossimplugins/ossim/otb/PlatformPosition.h b/Utilities/otbossimplugins/ossim/otb/PlatformPosition.h index a557c050790bd09cf8ef9e206e3e59c138a2ce5e..61c4ff285566f9936240f587530a52dfb0edaca8 100644 --- a/Utilities/otbossimplugins/ossim/otb/PlatformPosition.h +++ b/Utilities/otbossimplugins/ossim/otb/PlatformPosition.h @@ -71,7 +71,9 @@ public: }; void setData(Ephemeris** data, int nbrData); + Ephemeris* getData(int noData) const; + int getNbrData() const; /** * @brief Method to save object state to a keyword list. * @param kwl Keyword list to save to.