1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
|
/*=========================================================================
*
* Copyright NumFOCUS
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef itkImageKmeansModelEstimator_hxx
#define itkImageKmeansModelEstimator_hxx
#include "itkMakeUniqueForOverwrite.h"
namespace itk
{
template <typename TInputImage, typename TMembershipFunction>
ImageKmeansModelEstimator<TInputImage, TMembershipFunction>::ImageKmeansModelEstimator()
{
m_ValidInCodebook = false;
m_DoubleMaximum = NumericTraits<double>::max();
m_Threshold = 0.01;
m_OffsetAdd = 0.01;
m_OffsetMultiply = 0.01;
m_MaxSplitAttempts = 10;
m_OutputDistortion = 0.0;
m_OutputNumberOfEmptyCells = 0;
m_VectorDimension = 1;
m_NumberOfCodewords = 1;
m_CurrentNumberOfCodewords = 1;
}
template <typename TInputImage, typename TMembershipFunction>
void
ImageKmeansModelEstimator<TInputImage, TMembershipFunction>::PrintSelf(std::ostream & os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
os << indent << "Centroid: " << m_Centroid << std::endl;
os << indent << "Threshold: " << m_Threshold << std::endl;
os << indent << "OffsetAdd: " << m_OffsetAdd << std::endl;
os << indent << "OffsetMultiply: " << m_OffsetMultiply << std::endl;
os << indent << "MaxSplitAttempts: " << m_MaxSplitAttempts << std::endl;
os << indent << "ValidInCodebook: " << m_ValidInCodebook << std::endl;
os << indent << "DoubleMaximum: " << m_DoubleMaximum << std::endl;
os << indent << "OutputDistortion: " << m_OutputDistortion << std::endl;
os << indent << "OutputNumberOfEmptyCells: " << m_OutputNumberOfEmptyCells << std::endl;
os << indent
<< "VectorDimension: " << static_cast<typename NumericTraits<SizeValueType>::PrintType>(m_VectorDimension)
<< std::endl;
os << indent
<< "NumberOfCodewords: " << static_cast<typename NumericTraits<SizeValueType>::PrintType>(m_NumberOfCodewords)
<< std::endl;
os << indent << "CurrentNumberOfCodewords: "
<< static_cast<typename NumericTraits<SizeValueType>::PrintType>(m_CurrentNumberOfCodewords) << std::endl;
os << indent << "CodewordHistogram: " << m_CodewordHistogram << std::endl;
os << indent << "CodewordDistortion: " << m_CodewordDistortion << std::endl;
}
template <typename TInputImage, typename TMembershipFunction>
void
ImageKmeansModelEstimator<TInputImage, TMembershipFunction>::PrintKmeansAlgorithmResults()
{
itkDebugMacro(" ");
itkDebugMacro("Results of the clustering algorithms");
itkDebugMacro("====================================");
itkDebugMacro(" ");
itkDebugMacro("Means of the clustered vector ");
itkDebugMacro("++++++++++++++++++++++++++++++++++++");
itkDebugMacro(<< m_Centroid);
itkDebugMacro(" ");
itkDebugMacro("Distortion measures ");
itkDebugMacro("+++++++++++++++++++++++++++++++++++ ");
itkDebugMacro(<< m_CodewordDistortion);
itkDebugMacro(" ");
itkDebugMacro("Histogram of the vector ");
itkDebugMacro("+++++++++++++++++++++++++++++++++++ ");
itkDebugMacro(<< m_CodewordHistogram);
}
template <typename TInputImage, typename TMembershipFunction>
void
ImageKmeansModelEstimator<TInputImage, TMembershipFunction>::GenerateData()
{
this->EstimateModels();
}
template <typename TInputImage, typename TMembershipFunction>
void
ImageKmeansModelEstimator<TInputImage, TMembershipFunction>::SetCodebook(CodebookMatrixOfDoubleType inCodebook)
{
// Set the input codebook and allocate memory for the output codebook and
// other scratch memory
m_Codebook = inCodebook;
// Check if the input codebook is a valid
if (InputImagePixelType::GetVectorDimension() == m_Codebook.cols())
{
m_ValidInCodebook = true;
this->Allocate();
}
}
template <typename TInputImage, typename TMembershipFunction>
void
ImageKmeansModelEstimator<TInputImage, TMembershipFunction>::Allocate()
{
SizeValueType initCodebookSize, finalCodebookSize;
m_VectorDimension = InputImagePixelType::GetVectorDimension();
if (m_ValidInCodebook)
{
m_NumberOfCodewords = m_Codebook.rows();
m_VectorDimension = m_Codebook.cols();
// Set the initial and final codebook size
finalCodebookSize = m_NumberOfCodewords;
}
else
{
m_ValidInCodebook = true;
// Check the validity of the n
if (this->GetNumberOfModels() <= 0)
{
itkExceptionMacro("Number of models is less than 0.");
}
m_NumberOfCodewords = this->GetNumberOfModels();
m_VectorDimension = InputImagePixelType::GetVectorDimension();
// Set the initial and final codebook size
initCodebookSize = (SizeValueType)1;
finalCodebookSize = (SizeValueType)m_NumberOfCodewords;
m_Codebook.set_size(initCodebookSize, m_VectorDimension);
// Initialize m_Codebook to 0 (it now has only one row)
m_Codebook.fill(0);
}
// Allocate scratch memory for the centroid, codebook histogram
// and the codebook distortion
m_Centroid.set_size(finalCodebookSize, m_VectorDimension);
m_Centroid.fill(0);
m_CodewordHistogram.set_size(m_NumberOfCodewords, 1);
m_CodewordHistogram.fill(0);
m_CodewordDistortion.set_size(m_NumberOfCodewords, 1);
m_CodewordDistortion.fill(0);
}
template <typename TInputImage, typename TMembershipFunction>
void
ImageKmeansModelEstimator<TInputImage, TMembershipFunction>::Reallocate(int oldSize, int newSize)
{
// Set up a temporary codebook
CodebookMatrixOfDoubleType tmpCodebook(oldSize, m_VectorDimension);
// Save the contents of m_Codebook in the tmpCodebook
tmpCodebook = m_Codebook;
m_Codebook.set_size(newSize, m_VectorDimension);
// Copy back the saved data into the codebook
if (oldSize < newSize)
{
for (int r = 0; r < oldSize; ++r)
{
for (unsigned int c = 0; c < m_VectorDimension; ++c)
{
m_Codebook[r][c] = tmpCodebook[r][c];
}
}
for (int r = oldSize; r < newSize; ++r)
{
for (unsigned int c = 0; c < m_VectorDimension; ++c)
{
m_Codebook[r][c] = 0;
}
}
} // If oldSize is smaller than the new size
else
{
for (int r = 0; r < newSize; ++r)
{
for (unsigned int c = 0; c < m_VectorDimension; ++c)
{
m_Codebook[r][c] = tmpCodebook[r][c];
}
}
}
}
template <typename TInputImage, typename TMembershipFunction>
void
ImageKmeansModelEstimator<TInputImage, TMembershipFunction>::EstimateModels()
{
this->EstimateKmeansModelParameters();
// Set up the membership calculators
unsigned int numberOfModels = this->GetNumberOfModels();
// Call local function to estimate mean variances of the various
// class labels in the training set
// The statistics class functions have not been used since all the
// class statistics are calculated simultaneously here.
// Populate the membership functions for all the classes
MembershipFunctionPointer membershipFunction;
if (this->GetNumberOfMembershipFunctions() > 0)
{
this->DeleteAllMembershipFunctions();
}
for (unsigned int classIndex = 0; classIndex < numberOfModels; ++classIndex)
{
membershipFunction = TMembershipFunction::New();
typename TMembershipFunction::CentroidType centroid;
centroid = m_Centroid.get_row(classIndex);
membershipFunction->SetCentroid(centroid);
this->AddMembershipFunction(membershipFunction);
}
}
template <typename TInputImage, typename TMembershipFunction>
void
ImageKmeansModelEstimator<TInputImage, TMembershipFunction>::EstimateKmeansModelParameters()
{
// If a codebook is provided by the user then call the
// Kmeans algorithm directly that is based on the
// Generalized Lloyd algorithm (GLA) if a valid codebook
// is provided or m_NumberOfModels is set to 0, else
// Linde-Buzo-Gray algorithm is used for clustering
if (m_ValidInCodebook)
{
WithCodebookUseGLA();
}
else
{
// Assign memory for the initial codebook since no input codebook is
// provided for this function
Allocate();
m_CurrentNumberOfCodewords = m_Codebook.rows();
WithoutCodebookUseLBG();
}
m_ValidInCodebook = false;
}
template <typename TInputImage, typename TMembershipFunction>
int
ImageKmeansModelEstimator<TInputImage, TMembershipFunction>::WithCodebookUseGLA()
{
// Do the Lloyd iteration. Use the nearest neighbor condition to
// find the cells. Then find the centroid of each cell.
// First pass requires very large distortion
double olddistortion = m_DoubleMaximum;
double distortion, tempdistortion;
int pass = 0; // no empty cells have been found yet
int emptycells;
int bestcodeword;
m_CurrentNumberOfCodewords = m_Codebook.rows();
do
{
// Encode all of the input vectors using the given codebook
NearestNeighborSearchBasic(&distortion);
// Check for lack of convergence
if (olddistortion < distortion)
{
itkExceptionMacro("Distortion is increasing, not decreasing");
}
// Find number of empty cells
emptycells = 0;
for (unsigned int i = 0; i < m_CurrentNumberOfCodewords; ++i)
{
if (m_CodewordHistogram[i][0] == 0)
{
emptycells += 1;
m_CodewordDistortion[i][0] = 0.0;
}
}
// If distortion = 0.0, or if change in distortion < threshold AND there
// aren't any empty cells, exit
if ((distortion == 0.0) || ((emptycells == 0) && (olddistortion - distortion) / distortion < m_Threshold))
{
m_OutputNumberOfEmptyCells = emptycells;
m_OutputDistortion = distortion;
return GLA_CONVERGED;
}
// No empty cells, find new centroids and reinitialize for next pass
if (emptycells == 0)
{
for (unsigned int i = 0; i < m_CurrentNumberOfCodewords; ++i)
{
for (unsigned int j = 0; j < m_VectorDimension; ++j)
{
m_Codebook[i][j] = m_Centroid[i][j];
}
}
olddistortion = distortion;
pass = 0;
}
// There are empty cells, split the highest distortion codewords.
// try again
else
{
// If there have been too many attempts to fill cells, stop iterations
if (pass == m_MaxSplitAttempts)
{
itkWarningMacro("Unable to fill all empty cells");
m_OutputNumberOfEmptyCells = emptycells;
m_OutputDistortion = distortion;
return GLA_CONVERGED;
}
// Try getting new codewords, send a warning to user
itkDebugMacro("Attempting to fill empty cells in the codebook");
// Consolidate the highest distortion codewords into the beginning
// of the array. Take care to protect zero distortion codewords
// which have a positive m_CodewordHistogram. note: there must be a
// faster sort algorithm, but this event should be very unlikely
for (unsigned int n = 0; n < m_CurrentNumberOfCodewords - emptycells; ++n)
{
tempdistortion = 0.0;
bestcodeword = 0;
for (unsigned int i = 0; i < m_NumberOfCodewords; ++i)
{
if ((m_CodewordDistortion[i][0] >= tempdistortion) && (m_CodewordHistogram[i][0] > 0))
{
tempdistortion = m_CodewordDistortion[i][0];
bestcodeword = i;
}
}
// Put highest distortion centroid into nth codebook row,
// and erase the set of highest centroid stats to 0 so
// it will not be used again.
// Find centroid, reinitialize
for (unsigned int j = 0; j < m_VectorDimension; ++j)
{
m_Codebook[n][j] = m_Centroid[bestcodeword][j];
}
m_CodewordHistogram[bestcodeword][0] = 0;
m_CodewordDistortion[bestcodeword][0] = 0.0;
}
// Split the required number of codewords
SplitCodewords(m_CurrentNumberOfCodewords - emptycells, emptycells, pass);
olddistortion = distortion;
++pass;
}
} while (pass <= m_MaxSplitAttempts);
itkExceptionMacro("Lack of convergence");
}
template <typename TInputImage, typename TMembershipFunction>
void
ImageKmeansModelEstimator<TInputImage, TMembershipFunction>::NearestNeighborSearchBasic(double * distortion)
{
// itkDebugMacro(<<"Start nearest_neighbor_search_basic()");
double bestdistortion, tempdistortion, diff;
int bestcodeword;
// unused: double *centroidVecTemp = ( double * ) new double[m_VectorDimension];
// Initialize codeword histogram and distortion
for (unsigned int i = 0; i < m_CurrentNumberOfCodewords; ++i)
{
m_CodewordHistogram[i][0] = 0;
m_CodewordDistortion[i][0] = 0.0;
}
// Initialize centroid if it exists
m_Centroid.fill(0);
// Perform encoding using partial distortion method
*distortion = 0.0;
// Declare the iterators for the image and the codebook
InputImageConstPointer inputImage = this->GetInputImage();
InputImageConstIterator inputImageIt(inputImage, inputImage->GetBufferedRegion());
inputImageIt.GoToBegin();
// Calculate the number of vectors in the input data set
ImageSizeType size = inputImage->GetBufferedRegion().GetSize();
unsigned int totalNumVecsInInput = 1;
for (unsigned int i = 0; i < TInputImage::ImageDimension; ++i)
{
totalNumVecsInInput *= (SizeValueType)size[i];
}
// Loop through the input image vectors
InputPixelVectorType inputImagePixelVector;
for (unsigned int n = 0; n < totalNumVecsInInput; ++n)
{
// Keep convention that ties go to lower index
bestdistortion = m_DoubleMaximum;
bestcodeword = 0;
for (unsigned int i = 0; i < m_CurrentNumberOfCodewords; ++i)
{
// Find the best codeword
tempdistortion = 0.0;
inputImagePixelVector = inputImageIt.Get();
for (unsigned int j = 0; j < m_VectorDimension; ++j)
{
diff = static_cast<double>(inputImagePixelVector[j] - m_Codebook[i][j]);
tempdistortion += diff * diff;
if (tempdistortion > bestdistortion)
{
break;
}
}
if (tempdistortion < bestdistortion)
{
bestdistortion = tempdistortion;
bestcodeword = i;
}
// If the bestdistortion is 0.0, the best codeword is found
if (bestdistortion == 0.0)
{
break;
}
}
m_CodewordHistogram[bestcodeword][0] += 1;
m_CodewordDistortion[bestcodeword][0] += bestdistortion;
*distortion += bestdistortion;
// inputImagePixelVector = *tempImgIt;
inputImagePixelVector = inputImageIt.Get();
for (unsigned int j = 0; j < m_VectorDimension; ++j)
{
m_Centroid[bestcodeword][j] += inputImagePixelVector[j];
}
++inputImageIt;
} // all training vectors have been encoded
// Compute table frequency and distortion
for (unsigned int i = 0; i < m_CurrentNumberOfCodewords; ++i)
{
if (m_CodewordHistogram[i][0] > 0)
{
m_CodewordDistortion[i][0] /= static_cast<double>(m_CodewordHistogram[i][0]);
}
}
// Compute centroid
for (unsigned int i = 0; i < m_CurrentNumberOfCodewords; ++i)
{
if (m_CodewordHistogram[i][0] > 0)
{
for (unsigned int j = 0; j < m_VectorDimension; ++j)
{
m_Centroid[i][j] /= static_cast<double>(m_CodewordHistogram[i][0]);
}
}
}
// Normalize the distortions
*distortion /= static_cast<double>(totalNumVecsInInput);
// Check for bizarre errors
if (*distortion < 0.0)
{
itkExceptionMacro("Computational overflow");
}
}
template <typename TInputImage, typename TMembershipFunction>
void
ImageKmeansModelEstimator<TInputImage, TMembershipFunction>::SplitCodewords(int currentSize, int numDesired, int scale)
{
const auto newCodebookData = make_unique_for_overwrite<double[]>(m_VectorDimension);
const auto inCodebookData = make_unique_for_overwrite<double[]>(m_VectorDimension);
for (int i = 0; i < numDesired; ++i)
{
for (unsigned int j = 0; j < m_VectorDimension; ++j)
{
inCodebookData[j] = m_Codebook[i][j];
}
Perturb(inCodebookData.get(), scale, newCodebookData.get());
for (unsigned int j = 0; j < m_VectorDimension; ++j)
{
m_Codebook[i + currentSize][j] = newCodebookData[j];
}
}
}
template <typename TInputImage, typename TMembershipFunction>
void
ImageKmeansModelEstimator<TInputImage, TMembershipFunction>::Perturb(double * oldCodeword,
int scale,
double * newCodeword)
{
unsigned int i;
double addoffset;
double muloffset;
double rand_num;
addoffset = m_OffsetAdd / std::pow(2.0, static_cast<double>(scale));
muloffset = m_OffsetMultiply / std::pow(2.0, static_cast<double>(scale));
for (i = 0; i < m_VectorDimension; ++i)
{
srand(static_cast<unsigned int>(time(nullptr)));
rand_num = (rand()) / (static_cast<double>(RAND_MAX));
if (oldCodeword[i] == 0.0)
{
newCodeword[i] = addoffset * rand_num;
}
else if (itk::Math::abs(oldCodeword[i]) < 0.9 * addoffset)
{
newCodeword[i] = oldCodeword[i];
if (oldCodeword[i] < 0)
{
newCodeword[i] -= addoffset * rand_num;
}
else
{
newCodeword[i] += addoffset * rand_num;
}
}
else
{
newCodeword[i] = oldCodeword[i] + muloffset * oldCodeword[i] * rand_num;
}
}
}
template <typename TInputImage, typename TMembershipFunction>
int
ImageKmeansModelEstimator<TInputImage, TMembershipFunction>::WithoutCodebookUseLBG()
{
// itkDebugMacro(<<"Start local function lbg design()");
unsigned int tmp_ncodewords, j;
// Do the LBG algorithm
// Iteration begins here
// Start with one word codebook
// Set initial distortion
m_OutputDistortion = m_DoubleMaximum;
// Apply the generalized Lloyd algorithm on all codebook sizes
for (tmp_ncodewords = 1; tmp_ncodewords < m_NumberOfCodewords;)
{
// Run the GLA for codebook of size i
// Run GLA
WithCodebookUseGLA();
// If empty cells, do not continue
// If distortion is zero, no need to continue.
if (m_OutputNumberOfEmptyCells > 0 || m_OutputDistortion == 0.0)
{
break;
}
// Find the number of new codewords to be made (j-tmp_ncodewords)
j = 2 * tmp_ncodewords;
if (j > m_NumberOfCodewords)
{
j = m_NumberOfCodewords;
}
// Split the codewords
// Increase size of codebook
const SizeValueType oldSize = m_Codebook.rows();
Reallocate(oldSize, j);
// Initialize the new codewords
SplitCodewords(tmp_ncodewords, (j - tmp_ncodewords), 0);
// If error, do not continue
// Increment the codebook size
tmp_ncodewords = j;
}
// If there are no errors, no empty cells and the distortion is positive,
// create the final codebook
if (m_OutputNumberOfEmptyCells == 0 && m_OutputDistortion > 0.0)
{
// Run GLA
WithCodebookUseGLA();
}
// Done with all iterations
const SizeValueType codebookSize = m_Codebook.rows();
if (m_NumberOfCodewords != codebookSize)
{
itkDebugMacro("Returning fewer codewords than requested");
}
// itkDebugMacro(<<"Done with local function LBG ()");
return LBG_COMPLETED;
}
} // namespace itk
#endif
|