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) 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, TE_TR("The value of K (number of clusters) must be at least 2."))
101  TERP_TRUE_OR_RETURN_FALSE(m_parameters.m_maxIterations > 0, TE_TR("The number of iterations must be at least 1."))
102  TERP_TRUE_OR_RETURN_FALSE(m_parameters.m_epsilon > 0, TE_TR("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, TE_TR("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(TE_TR("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 }
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:345
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.
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:746
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.
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