All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
ClassifierKMeansStrategy.cpp
Go to the documentation of this file.
1 /* Copyright (C) 2008 National Institute For Space Research (INPE) - Brazil.
2 
3  This file is part of the TerraLib - a Framework for building GIS enabled applications.
4 
5  TerraLib is free software: you can redistribute it and/or modify
6  it under the terms of the GNU Lesser General Public License as published by
7  the Free Software Foundation, either version 3 of the License,
8  or (at your option) any later version.
9 
10  TerraLib is distributed in the hope that it will be useful,
11  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  GNU Lesser General Public License for more details.
14 
15  You should have received a copy of the GNU Lesser General Public License
16  along with TerraLib. See COPYING. If not, write to
17  TerraLib Team at <terralib-team@terralib.org>.
18  */
19 
20 /*!
21  \file terralib/rp/ClassifierKMeansStrategy.cpp
22 
23  \brief KMeans strategy for image classification.
24 */
25 
26 // TerraLib
27 #include "../classification/KMeans.h"
28 #include "../common/progress/TaskProgress.h"
29 #include "../geometry/Envelope.h"
30 #include "../raster/Grid.h"
31 #include "../raster/PositionIterator.h"
32 #include "../raster/RasterIterator.h"
33 #include "../raster/Utils.h"
35 #include "Macros.h"
36 #include "Functions.h"
37 
38 // STL
39 #include <iostream>
40 #include <stdlib.h>
41 
42 namespace
43 {
44  static te::rp::ClassifierKMeansStrategyFactory classifierKMeansStrategyFactoryInstance;
45 }
46 
48 {
49  reset();
50 }
51 
53 {
54 }
55 
57 {
58  reset();
59 
60  m_K = rhs.m_K;
61  m_maxIterations = rhs.m_maxIterations;
62  m_maxInputPoints = rhs.m_maxInputPoints;
63  m_epsilon = rhs.m_epsilon;
64 
65  return *this;
66 }
67 
69 {
70  m_K = 0;
71  m_maxIterations = 0;
72  m_maxInputPoints = 0;
73  m_epsilon = 0.0;
74 }
75 
77 {
79 }
80 
82 {
83  m_isInitialized = false;
84 }
85 
87 {
88 }
89 
90 bool te::rp::ClassifierKMeansStrategy::initialize(te::rp::StrategyParameters const* const strategyParams) throw(te::rp::Exception)
91 {
92  m_isInitialized = false;
93 
94  te::rp::ClassifierKMeansStrategy::Parameters const* paramsPtr = dynamic_cast<te::rp::ClassifierKMeansStrategy::Parameters const*>(strategyParams);
95 
96  if(!paramsPtr)
97  return false;
98 
99  m_parameters = *(paramsPtr);
100 
101  TERP_TRUE_OR_RETURN_FALSE(m_parameters.m_K > 1, TE_TR("The value of K (number of clusters) must be at least 2."))
102  TERP_TRUE_OR_RETURN_FALSE(m_parameters.m_maxIterations > 0, TE_TR("The number of iterations must be at least 1."))
103  TERP_TRUE_OR_RETURN_FALSE(m_parameters.m_epsilon > 0, TE_TR("The stop criteria must be higher than 0."))
104 
107 
108  m_isInitialized = true;
109 
110  return true;
111 }
112 
113 bool te::rp::ClassifierKMeansStrategy::execute(const te::rst::Raster& inputRaster, const std::vector<unsigned int>& inputRasterBands,
114  const std::vector<te::gm::Polygon*>& inputPolygons, te::rst::Raster& outputRaster,
115  const unsigned int outputRasterBand, const bool enableProgressInterface) throw(te::rp::Exception)
116 {
117  TERP_TRUE_OR_RETURN_FALSE(m_isInitialized, TE_TR("Instance not initialized"))
118 
119 // defining classification parameters
121  classifierParameters.m_K = m_parameters.m_K;
122  classifierParameters.m_maxIterations = m_parameters.m_maxIterations;
123  classifierParameters.m_epsilon = m_parameters.m_epsilon;
124  std::vector<unsigned int> classification;
125 
126 // define point set iterators for training
127  std::vector<te::gm::Point*> randomPoints = te::rst::GetRandomPointsInRaster(inputRaster, m_parameters.m_maxInputPoints);
130 
131 // define raster iterators for classification
134 
135 // execute the algorithm
137 
138  if(!classifier.initialize(classifierParameters))
139  throw;
140  if(!classifier.train(pit, pitend, inputRasterBands, std::vector<unsigned int>(), true))
141  throw;
142  if(!classifier.classify(rit, ritend, inputRasterBands, classification, true))
143  throw;
144 
145 // classifying image
147  task.setTotalSteps(inputRaster.getNumberOfColumns() * inputRaster.getNumberOfRows());
148  task.setMessage(TE_TR("KMeans algorithm - classifying image"));
149  task.setCurrentStep(0);
150  unsigned int i = 0;
151  while (rit != ritend)
152  {
153  outputRaster.setValue(rit.getColumn(), rit.getRow(), classification[i], outputRasterBand);
154  ++i;
155  ++rit;
156  task.pulse();
157  }
158 
159  return true;
160 }
161 
163  : te::rp::ClassifierStrategyFactory("kmeans")
164 {
165 }
166 
168 {
169 }
170 
172 {
174 }
bool execute(const te::rst::Raster &inputRaster, const std::vector< unsigned int > &inputRasterBands, const std::vector< te::gm::Polygon * > &inputPolygons, te::rst::Raster &outputRaster, const unsigned int outputRasterBand, const bool enableProgressInterface)
Executes the classification strategy.
ClassifierKMeansStrategy::Parameters m_parameters
Internal execution parameters.
Raster KMeans Classifier strategy factory.
void setMessage(const std::string &message)
Set the task message.
bool initialize(const Parameters &params)
Definition: KMeans.h:175
unsigned int getRow() const
Returns the current row in iterator.
KMeans strategy for image classification.
void reset()
Clear all internal allocated resources and reset the parameters instance to its initial state...
This class implements and iterator to "navigate" over a raster, with a predefined number of bands...
This class can be used to inform the progress of a task.
Definition: TaskProgress.h:53
bool classify(TCLASSIFY &itBegin, TCLASSIFY &itEnd, const std::vector< unsigned int > &attributesIndices, std::vector< unsigned int > &classification, const bool enableProgressInterface)
Definition: KMeans.h:304
static PointSetIterator end(const te::rst::Raster *r, const std::vector< te::gm::Point * > p)
Returns an iterator referring to after the end of the iterator.
unsigned int m_maxInputPoints
The maximum number of points used to estimate the clusters (default = 1000).
#define TE_TR(message)
It marks a string in order to get translated.
Definition: Translator.h:347
This class implements the strategy to iterate with spatial restriction, the iteration occurs inside a...
Raster Processing functions.
void setTotalSteps(int value)
Set the task total stepes.
#define TERP_TRUE_OR_RETURN_FALSE(value, message)
Checks if value is true. For false values a warning message will be logged and a return of context wi...
Definition: Macros.h:183
te::rp::ClassifierStrategy * build()
Concrete factories (derived from this one) must implement this method in order to create objects...
Raster classifier strategy factory base class.
unsigned int m_K
The number of clusters (means) to detect in image.
const Parameters & operator=(const Parameters &params)
An abstract class for raster data strucutures.
Definition: Raster.h:71
static RasterIterator begin(Raster *r, const std::vector< unsigned int > &bands)
Returns an iterator referring to the first value.
Raster strategy parameters base class.
bool initialize(StrategyParameters const *const strategyParams)
Initialize the classification strategy.
void pulse()
Calls setCurrentStep() function using getCurrentStep() + 1.
double m_epsilon
The stop criteria. When the clusters change in a value smaller then epsilon, the convergence is achie...
bool m_isInitialized
True if this instance is initialized.
KMeans strategy for classification. Step-by-step:
Definition: KMeans.h:62
Abstract parameters base interface.
void setCurrentStep(int value)
Set the task current step.
Raster classifier strategy base class.
TERASTEREXPORT std::vector< te::gm::Point * > GetRandomPointsInRaster(const te::rst::Raster &inputRaster, unsigned int numberOfPoints=1000)
Creates a vector of random positions (points) inside the raster.
Definition: Utils.cpp:485
unsigned int m_maxIterations
The maximum of iterations to perform if convergence is not achieved.
static RasterIterator end(Raster *r, const std::vector< unsigned int > &bands)
Returns an iterator referring to after the end of the iterator.
unsigned int getColumn() const
Returns the current column in iterator.
AbstractParameters * clone() const
Create a clone copy of this instance.
static PointSetIterator begin(const te::rst::Raster *r, const std::vector< te::gm::Point * > p)
Returns an iterator referring to the first value of the band.
KMeans strategy for image classification. Step-by-step:
bool train(TTRAIN &itBegin, TTRAIN &itEnd, const std::vector< unsigned int > &attributesIndices, const std::vector< unsigned int > &labels, const bool enableProgressInterface)
Definition: KMeans.h:198