ITK 全稱爲 Insight Toolkit ,是一款開源、跨平臺、用於圖像分析工具包,開發遵循極限編程,主流使用語言爲 C++,但目前開發團隊已經提供了面向 Python 的接口。
ITK 內部封裝了許多優秀算法。ITK 可用於圖像處理、配準、分割等領域,處理維度面向二維、三維或者更高維度
原理講解
本文爲 ITK 系列教程的第一篇文章,主要介紹該工具包中二值化分割功能的實現;圖像分割的目的通過改變圖像像素值,來提取我們想要的區域,一般是圖像處理的大前提;
ITK 中的二值化分割主要用到 itk::BinaryThresholdImageFilter 過濾器,其分割原理圖如下:
二值化分割是分割方法中最基礎的,通過定義 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 圖片,最終的分割結果如下