6 template <
class DataType,
unsigned int Po
intDimension>
7 KMeansFilter <DataType,PointDimension>::
10 m_ClassesMembership.clear();
13 m_NumberPerClass.clear();
17 m_MaxIterations = 100;
22 template <
class DataType,
unsigned int Po
intDimension>
28 template <
class DataType,
unsigned int Po
intDimension>
37 m_NbInputs = m_InputData.size();
40 template <
class DataType,
unsigned int Po
intDimension>
45 if (m_NbClass > m_NbInputs)
46 throw itk::ExceptionObject(__FILE__, __LINE__,
"More classes than inputs...",ITK_LOCATION);
48 this->InitializeKMeansFromData();
50 unsigned int itncount = 0;
51 bool continueLoop =
true;
53 while ((itncount < m_MaxIterations)&&(continueLoop))
58 std::cout <<
"Iteration " << itncount <<
"..." << std::endl;
60 this->ComputeCentroids();
61 this->UpdateMemberships();
63 continueLoop = !this->endConditionReached(oldMemberships);
64 oldMemberships = m_ClassesMembership;
68 template <
class DataType,
unsigned int Po
intDimension>
73 for (
unsigned int i = 0;i < m_NbClass;++i)
74 m_Centroids[i].Fill(0);
76 for (
unsigned int j = 0;j < m_NbInputs;++j)
78 for (
unsigned int k = 0;k < PointDimension;++k)
79 m_Centroids[m_ClassesMembership[j]][k] += m_InputData[j][k];
82 for (
unsigned int j = 0;j < m_NbClass;++j)
84 if (m_NumberPerClass[j] != 0)
86 for (
unsigned int k = 0;k < PointDimension;++k)
87 m_Centroids[j][k] /= m_NumberPerClass[j];
92 template <
class DataType,
unsigned int Po
intDimension>
97 std::fill(m_NumberPerClass.begin(),m_NumberPerClass.end(),0);
98 for (
unsigned int i = 0;i < m_NbInputs;++i)
100 unsigned int bestClass = 0;
101 double bestDistance = this->computeDistance(m_InputData[i],m_Centroids[0]);
103 for (
unsigned int j = 1;j < m_NbClass;++j)
105 double tmpDist = this->computeDistance(m_InputData[i],m_Centroids[j]);
106 if (tmpDist < bestDistance)
108 bestDistance = tmpDist;
113 m_ClassesMembership[i] = bestClass;
114 ++m_NumberPerClass[bestClass];
118 template <
class DataType,
unsigned int Po
intDimension>
123 for (
unsigned int i = 0;i < m_NbInputs;++i)
125 if (oldMemberships[i] != m_ClassesMembership[i])
132 template <
class DataType,
unsigned int Po
intDimension>
135 InitializeKMeansFromData()
139 for (
unsigned int i = 0;i < m_NbClass;++i)
140 m_Centroids.push_back(m_InputData[i]);
143 if (m_ClassesMembership.size() != m_NbInputs)
145 m_ClassesMembership.resize(m_NbInputs);
146 std::fill(m_ClassesMembership.begin(),m_ClassesMembership.end(),0);
148 this->UpdateMemberships();
152 template <
class DataType,
unsigned int Po
intDimension>
157 if (classM.size() == m_NbInputs)
158 m_ClassesMembership = classM;
160 for (
unsigned int i = 0;i < m_NbInputs;++i)
161 m_NumberPerClass[m_ClassesMembership[i]]++;
164 template <
class DataType,
unsigned int Po
intDimension>
171 for (
unsigned int i = 0;i < PointDimension;++i)
172 resVal += (vec1[i] - vec2[i])*(vec1[i] - vec2[i]);
std::vector< VectorType > DataHolderType
std::vector< unsigned int > MembershipType