ITK  6.0.0
Insight Toolkit
SphinxExamples/src/Segmentation/Classifiers/KMeansClusterOfPixelsInImage/Code.cxx
/*=========================================================================
*
* 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.
*
*=========================================================================*/
#include "itkImage.h"
#include "itkListSample.h"
#include "itkVector.h"
using MeasurementVectorType = itk::Vector<unsigned char, 3>;
using ColorImageType = itk::Image<MeasurementVectorType, 2>;
using ScalarImageType = itk::Image<unsigned char, 2>;
static void
CreateImage(ColorImageType::Pointer image);
int
main()
{
// Create a demo image
auto image = ColorImageType::New();
CreateImage(image);
// Compute pixel clusters using KMeans
using MembershipFunctionPointer = MembershipFunctionType::Pointer;
using MembershipFunctionPointerVector = std::vector<MembershipFunctionPointer>;
auto kmeansEstimator = ImageKmeansModelEstimatorType::New();
kmeansEstimator->SetInputImage(image);
kmeansEstimator->SetNumberOfModels(3);
kmeansEstimator->SetThreshold(0.01);
kmeansEstimator->SetOffsetAdd(0.01);
kmeansEstimator->SetOffsetMultiply(0.01);
kmeansEstimator->SetMaxSplitAttempts(10);
kmeansEstimator->Update();
// Classify each pixel
auto classifier = ClassifierType::New();
using DecisionRuleType = itk::Statistics::MinimumDecisionRule;
auto decisionRule = DecisionRuleType::New();
classifier->SetDecisionRule(decisionRule);
classifier->SetNumberOfClasses(3);
using ClassLabelVectorObjectType = ClassifierType::ClassLabelVectorObjectType;
using ClassLabelVectorType = ClassifierType::ClassLabelVectorType;
using MembershipFunctionVectorObjectType = ClassifierType::MembershipFunctionVectorObjectType;
using MembershipFunctionVectorType = ClassifierType::MembershipFunctionVectorType;
// Setup membership functions
MembershipFunctionPointerVector kmeansMembershipFunctions = kmeansEstimator->GetMembershipFunctions();
MembershipFunctionVectorObjectType::Pointer membershipFunctionsVectorObject =
classifier->SetMembershipFunctions(membershipFunctionsVectorObject);
MembershipFunctionVectorType & membershipFunctionsVector = membershipFunctionsVectorObject->Get();
for (auto & kmeansMembershipFunction : kmeansMembershipFunctions)
{
membershipFunctionsVector.push_back(kmeansMembershipFunction.GetPointer());
}
// Setup class labels
auto classLabelsObject = ClassLabelVectorObjectType::New();
classifier->SetClassLabels(classLabelsObject);
ClassLabelVectorType & classLabelsVector = classLabelsObject->Get();
classLabelsVector.push_back(50);
classLabelsVector.push_back(150);
classLabelsVector.push_back(250);
// Perform the classification
auto sample = SampleAdaptorType::New();
sample->SetImage(image);
classifier->SetInput(sample);
classifier->Update();
// Prepare the output image
auto outputImage = ScalarImageType::New();
outputImage->SetRegions(image->GetLargestPossibleRegion());
outputImage->Allocate();
outputImage->FillBuffer(0);
// Setup the membership iterator
const ClassifierType::MembershipSampleType * membershipSample = classifier->GetOutput();
ClassifierType::MembershipSampleType::ConstIterator membershipIterator = membershipSample->Begin();
// Setup the output image iterator - this is automatically synchronized with the membership iterator since the sample
// is an adaptor
outputImage->GetLargestPossibleRegion());
outputIterator.GoToBegin();
while (membershipIterator != membershipSample->End())
{
int classLabel = membershipIterator.GetClassLabel();
// std::cout << "Class label: " << classLabel << std::endl;
outputIterator.Set(classLabel);
++membershipIterator;
++outputIterator;
}
itk::WriteImage(image, "input.mha");
itk::WriteImage(outputImage, "output.mha");
return EXIT_SUCCESS;
}
void
CreateImage(ColorImageType::Pointer image)
{
// Create a black image with a red square and a green square
start[0] = 0;
start[1] = 0;
size[0] = 200;
size[1] = 300;
region.SetSize(size);
region.SetIndex(start);
image->SetRegions(region);
image->Allocate();
itk::ImageRegionIterator<ColorImageType> imageIterator(image, region);
redPixel[0] = 255;
redPixel[1] = 0;
redPixel[2] = 0;
greenPixel[0] = 0;
greenPixel[1] = 255;
greenPixel[2] = 0;
blackPixel[0] = 0;
blackPixel[1] = 0;
blackPixel[2] = 0;
while (!imageIterator.IsAtEnd())
{
if (imageIterator.GetIndex()[0] > 100 && imageIterator.GetIndex()[0] < 150 && imageIterator.GetIndex()[1] > 100 &&
imageIterator.GetIndex()[1] < 150)
{
imageIterator.Set(redPixel);
}
else if (imageIterator.GetIndex()[0] > 50 && imageIterator.GetIndex()[0] < 70 && imageIterator.GetIndex()[1] > 50 &&
imageIterator.GetIndex()[1] < 70)
{
imageIterator.Set(greenPixel);
}
else
{
imageIterator.Set(blackPixel);
}
++imageIterator;
}
}
itk::Statistics::DistanceToCentroidMembershipFunction
DistanceToCentroidMembershipFunction models class membership using a distance metric.
Definition: itkDistanceToCentroidMembershipFunction.h:45
Pointer
SmartPointer< Self > Pointer
Definition: itkAddImageFilter.h:93
itkSampleClassifierFilter.h
itk::ImageKmeansModelEstimator
Base class for ImageKmeansModelEstimator object.
Definition: itkImageKmeansModelEstimator.h:131
itk::Statistics::ImageToListSampleAdaptor
This class provides ListSample interface to ITK Image.
Definition: itkImageToListSampleAdaptor.h:54
itkDistanceToCentroidMembershipFunction.h
itk::Vector
A templated class holding a n-Dimensional vector.
Definition: itkVector.h:62
itk::GTest::TypedefsAndConstructors::Dimension2::SizeType
ImageBaseType::SizeType SizeType
Definition: itkGTestTypedefsAndConstructors.h:49
itk::Statistics::ListSample
This class is the native implementation of the a Sample with an STL container.
Definition: itkListSample.h:51
itkImage.h
itkImageRegionIteratorWithIndex.h
itk::ImageRegionIterator
A multi-dimensional iterator templated over image type that walks a region of pixels.
Definition: itkImageRegionIterator.h:80
itk::GTest::TypedefsAndConstructors::Dimension2::IndexType
ImageBaseType::IndexType IndexType
Definition: itkGTestTypedefsAndConstructors.h:50
itkMinimumDecisionRule.h
itk::GTest::TypedefsAndConstructors::Dimension2::RegionType
ImageBaseType::RegionType RegionType
Definition: itkGTestTypedefsAndConstructors.h:54
itkListSample.h
itk::ImageRegionIteratorWithIndex
A multi-dimensional iterator templated over image type that walks pixels within a region and is speci...
Definition: itkImageRegionIteratorWithIndex.h:73
itkImageFileWriter.h
itk::Size::SetSize
void SetSize(const SizeValueType val[VDimension])
Definition: itkSize.h:180
itk::ImageConstIteratorWithIndex::GoToBegin
void GoToBegin()
itkVector.h
itkImageKmeansModelEstimator.h
itk::Image
Templated n-dimensional image class.
Definition: itkImage.h:88
New
static Pointer New()
itk::Statistics::SampleClassifierFilter
Sample classification class.
Definition: itkSampleClassifierFilter.h:45
itk::Statistics::MinimumDecisionRule
A decision rule that returns the class label with the smallest discriminant score.
Definition: itkMinimumDecisionRule.h:38
itkImageToListSampleAdaptor.h
itk::WriteImage
ITK_TEMPLATE_EXPORT void WriteImage(TImagePointer &&image, const std::string &filename, bool compress=false)
Definition: itkImageFileWriter.h:256