ITK 全称为 Insight Toolkit ,是一款开源、跨平台、用于图像分析工具包,开发遵循极限编程,主流使用语言为 C++,但目前开发团队已经提供了面向 Python 的接口。
ITK 内部封装了许多优秀算法。ITK 可用于图像处理、配准、分割等领域,处理图像维度面向二维、三维或者更高维度
原理讲解
本文为 ITK 系列教程的第一篇文章,主要介绍该工具包中二值化分割功能的实现;图像分割的目的通过改变图像像素值,来提取我们想要的区域,一般是图像处理的大前提;
ITK 中的二值化分割主要用到 itk::BinaryThresholdImageFilter 过滤器,其分割原理图如下:
Snipaste_2020-05-03_15-50-50.png二值化分割是分割方法中最基础的,通过定义 Lower 和 Upper 两个像素临界点
只要图像像素值在者之间,则该像素值将改编为 Insidevalue;否则将改为 Outsidevalue;最终图像的像素值只有两种:Insidevalue 或者是 Outsidevalue;
注:上面的 Insidevalue、Outsidevalue、Lowervalue、Uppervalue 四个参数是用户自己设定的。
代码实现
上文已经提到了,二值化分割主要用到的头文件为 itkBinaryThresholdImageFilter ,该过滤器主要通过设置四个参数来完成分割效果。
下面的代码部分就是关于二值分割的功能实现,代码中,依次进行图像读取、参数设定、二值化处理、图像写出等一系列步骤
#include<itkBinaryThresholdImageFilter.h>
#include<itkImage.h>
#include<itkImageFileReader.h>
#include<itkImageFileWriter.h>
#include<itkPNGImageIOFactory.h>
#include<string.h>
using namespace std;
int Binary_Threshold()
{
itk::PNGImageIOFactory::RegisterOneFactory();
string input_name = "D:/ceshi1/ITK/Filter/Threshold_Seg/input.png";
string output_name = "D:/ceshi1/ITK/Filter/Threshold_Seg/output.png";
using InputPixelType = unsigned char;
using OutputPixelType = unsigned char;
using InputImageType = itk::Image<InputPixelType, 2>;
using OutputImageType = itk::Image<OutputPixelType, 2>;
using FilterType = itk::BinaryThresholdImageFilter<InputImageType, OutputImageType>;
using ReaderType = itk::ImageFileReader<InputImageType>;
using WriterType = itk::ImageFileWriter<OutputImageType>;
ReaderType::Pointer reader = ReaderType::New();
WriterType::Pointer writer = WriterType::New();
FilterType::Pointer filter = FilterType::New();
reader->SetFileName(input_name);
filter->SetInput(reader->GetOutput());
writer->SetInput(filter->GetOutput());
writer->SetFileName(output_name);
const OutputPixelType outsidevalue = 0;
const InputPixelType insidevalue = 255;
filter->SetOutsideValue(outsidevalue);
filter->SetInsideValue(insidevalue);
const InputPixelType lowerThreshold = 150;
const OutputPixelType upperThreshold = 180;
filter->SetUpperThreshold(upperThreshold);
filter->SetLowerThreshold(lowerThreshold);
try
{
filter->Update();// Running Filter;
writer->Update();//Runing Writer;
}
catch(exception &e)
{
cout << "Caught Error!" << endl;
cout << e.what() << endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
这里 Insidevalue 设置为 0 (黑色),Outsidevalue 设置为 255(白色);阈值分割区间设为 (150,180 );选取的分割图像为 ITK 官方提供的脑部切片 PNG 图片,最终的分割结果如下
Snipaste_2020-05-03_16-29-53.png
网友评论