All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
ClassifierKMeansStrategy.cpp
Go to the documentation of this file.
1 /* Copyright (C) 2001-2009 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"
34 #include "Macros.h"
35 #include "Functions.h"
36 
37 // STL
38 #include <iostream>
39 #include <stdlib.h>
40 
41 namespace
42 {
43  static te::rp::ClassifierKMeansStrategyFactory classifierKMeansStrategyFactoryInstance;
44 }
45 
47 {
48  reset();
49 }
50 
52 {
53 }
54 
56 {
57  reset();
58 
59  m_K = rhs.m_K;
60  m_maxIterations = rhs.m_maxIterations;
61  m_maxInputPoints = rhs.m_maxInputPoints;
62  m_epsilon = rhs.m_epsilon;
63 
64  return *this;
65 }
66 
68 {
69  m_K = 0;
70  m_maxIterations = 0;
71  m_maxInputPoints = 0;
72  m_epsilon = 0.0;
73 }
74 
76 {
78 }
79 
81 {
82  m_isInitialized = false;
83 }
84 
86 {
87 }
88 
89 bool te::rp::ClassifierKMeansStrategy::initialize(te::rp::StrategyParameters const* const strategyParams) throw(te::rp::Exception)
90 {
91  m_isInitialized = false;
92 
93  te::rp::ClassifierKMeansStrategy::Parameters const* paramsPtr = dynamic_cast<te::rp::ClassifierKMeansStrategy::Parameters const*>(strategyParams);
94 
95  if(!paramsPtr)
96  return false;
97 
98  m_parameters = *(paramsPtr);
99 
100  TERP_TRUE_OR_RETURN_FALSE(m_parameters.m_K > 1, TR_RP("The value of K (number of clusters) must be at least 2."))
101  TERP_TRUE_OR_RETURN_FALSE(m_parameters.m_maxIterations > 0, TR_RP("The number of iterations must be at least 1."))
102  TERP_TRUE_OR_RETURN_FALSE(m_parameters.m_epsilon > 0, TR_RP("The stop criteria must be higher than 0."))
103 
106 
107  m_isInitialized = true;
108 
109  return true;
110 }
111 
112 bool te::rp::ClassifierKMeansStrategy::execute(const te::rst::Raster& inputRaster, const std::vector<unsigned int>& inputRasterBands,
113  const std::vector<te::gm::Polygon*>& inputPolygons, te::rst::Raster& outputRaster,
114  const unsigned int outputRasterBand, const bool enableProgressInterface) throw(te::rp::Exception)
115 {
116  TERP_TRUE_OR_RETURN_FALSE(m_isInitialized, TR_RP("Instance not initialized"))
117 
118 // defining classification parameters
120  classifierParameters.m_K = m_parameters.m_K;
121  classifierParameters.m_maxIterations = m_parameters.m_maxIterations;
122  classifierParameters.m_epsilon = m_parameters.m_epsilon;
123  std::vector<unsigned int> classification;
124 
125 // define point set iterators for training
126  std::vector<te::gm::Point*> randomPoints = te::rp::GetRandomPointsInRaster(inputRaster, m_parameters.m_maxInputPoints);
129 
130 // define raster iterators for classification
133 
134 // execute the algorithm
136 
137  if(!classifier.initialize(classifierParameters))
138  throw;
139  if(!classifier.train(pit, pitend, inputRasterBands, std::vector<unsigned int>(), true))
140  throw;
141  if(!classifier.classify(rit, ritend, inputRasterBands, classification, true))
142  throw;
143 
144 // classifying image
146  task.setTotalSteps(inputRaster.getNumberOfColumns() * inputRaster.getNumberOfRows());
147  task.setMessage(TR_RP("KMeans algorithm - classifying image"));
148  task.setCurrentStep(0);
149  unsigned int i = 0;
150  while (rit != ritend)
151  {
152  outputRaster.setValue(rit.getColumn(), rit.getRow(), classification[i], outputRasterBand);
153  ++i;
154  ++rit;
155  task.pulse();
156  }
157 
158  return true;
159 }
160 
162  : te::rp::ClassifierStrategyFactory("kmeans")
163 {
164 }
165 
167 {
168 }
169 
171 {
173 }
unsigned int m_maxInputPoints
The maximum number of points used to estimate the clusters (default = 1000).
double m_epsilon
The stop criteria. When the clusters change in a value smaller then epsilon, the convergence is achie...
Raster KMeans Classifier strategy factory.
const Parameters & operator=(const Parameters &params)
Raster strategy parameters base class.
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.
std::vector< te::gm::Point * > GetRandomPointsInRaster(const te::rst::Raster &inputRaster, unsigned int numberOfPoints)
Creates a vector of random positions (points) inside the raster.
Definition: Functions.cpp:700
Raster Processing functions.
void setTotalSteps(int value)
Set the task total stepes.
KMeans strategy for classification. Step-by-step:
Definition: KMeans.h:62
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
This class implements and iterator to &quot;navigate&quot; over a raster, with a predefined number of bands...
#define TR_RP(message)
It marks a string in order to get translated. This is a special mark used in the Raster Processing mo...
Definition: Config.h:58
bool initialize(const Parameters &params)
Definition: KMeans.h:175
void setCurrentStep(int value)
Set the task current step.
unsigned int getRow() const
Returns the current row in iterator.
#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
KMeans strategy for image classification.
Abstract parameters base interface.
KMeans strategy for image classification. Step-by-step:
te::rp::ClassifierStrategy * build()
Concrete factories (derived from this one) must implement this method in order to create objects...
unsigned int m_maxIterations
The maximum of iterations to perform if convergence is not achieved.
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.
unsigned int m_K
The number of clusters (means) to detect in image.
void pulse()
Calls setCurrentStep() function using getCurrentStep() + 1.
Raster classifier strategy factory base class.
This class implements the strategy to iterate with spatial restriction, the iteration occurs inside a...
bool initialize(StrategyParameters const *const strategyParams)
Initialize the classification strategy.
static RasterIterator end(Raster *r, const std::vector< unsigned int > &bands)
Returns an iterator referring to after the end of the iterator.
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.
void setMessage(const std::string &message)
Set the task message.
An abstract class for raster data strucutures.
Definition: Raster.h:70
This class can be used to inform the progress of a task.
Definition: TaskProgress.h:53
unsigned int getColumn() const
Returns the current column in iterator.
void reset()
Clear all internal allocated resources and reset the parameters instance to its initial state...
ClassifierKMeansStrategy::Parameters m_parameters
Internal execution parameters.
Raster classifier strategy base class.
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 RasterIterator begin(Raster *r, const std::vector< unsigned int > &bands)
Returns an iterator referring to the first value.
bool m_isInitialized
True if this instance is initialized.
AbstractParameters * clone() const
Create a clone copy of this instance.