General Threshold 介紹
上篇文章介紹了 ITK 中的二值化分割,最終得到的是 二值圖像(圖像中只有兩種像素值),
但有時我們會遇到另外一種需求,只改變某一閾值範圍的像素值,其他部分保留;這時二值化分割已經滿足不了我們的基本需求了,需要尋求另外一種方法。
本篇教程介紹 ITK 中的 General Threshold ,是二值化的改進版,可以只改變某一範圍內的像素值,並且其它範圍內像素值得到保留。
原理講解
General Threshold 中用到了三種分割方式:
第一種,原理圖如下,該方法需要設置一個低臨界閾值 Lower Threshold,圖像中像素值若低於這個值,其值變爲 Outsidevalue,否則像素值不變;
該方法中需要設置二個參數,低像素值設定用到的是 ThresholdBelow() 函數;用戶指定 Outsidevalue;
第二種,方法中需要設置一個高臨界閾值 Upper Threshold,圖像中像素值若高於這個值,像素值將變成 Outsidevalue,否則像素值不變;
該方法中也需要設置二個參數,高閾值設定用到 ThresholdAbove() 函數,用戶指定 Outsidevalue;
第三種,結合了前兩種,該方法需要設置兩個閾值臨界 Lower Threshold 和 Upper Threshold 兩個值,若像素值介於兩者之間則不變,否則設爲 Outsidevalue;
方法中需要設置三個參數,低閾值設定用到 ThresholdBelow() 函數,高閾值設定用到 ThresholdAbove() 函數,用戶指定 Outsidevalue;
代碼實現
General Threshold 分割方法用到主要頭文件爲 itk::ThresholdImageFilter ;該 Filter 中閾值的設置用到兩個函數:
- ThresholdAbove() ;
- ThresholdBelow() ;
#include<itkThresholdImageFilter.h>
#include<itkImage.h>
#include<itkImageFileReader.h>
#include<itkImageFileWriter.h>
#include<itkPNGImageIOFactory.h>
#include<string.h>
using namespace std;
int main()
{
itk::PNGImageIOFactory::RegisterOneFactory();
string input_name = "D:/ceshi1/ITK/Filter/General_Seg/input.png";
string output_name1 = "D:/ceshi1/ITK/Filter/General_Seg/output1.png";
string output_name2 = "D:/ceshi1/ITK/Filter/General_Seg/output2.png";
string output_name3 = "D:/ceshi1/ITK/Filter/General_Seg/output3.png";
using PixelType = unsigned char;
using ImageType = itk::Image<PixelType, 2>;
using FilterType = itk::ThresholdImageFilter<ImageType>;
using ReaderType = itk::ImageFileReader<ImageType>;
using WriterType = itk::ImageFileWriter<ImageType>;
ReaderType::Pointer reader = ReaderType::New();
WriterType::Pointer writer = WriterType::New();
FilterType::Pointer filter = FilterType::New();
reader->SetFileName(input_name);
writer->SetFileName(output_name1);
writer->SetInput(filter->GetOutput());
filter->SetInput(reader->GetOutput());
//first Threshold method;
filter->SetOutsideValue(0);
filter->ThresholdBelow(170);
try
{
filter->Update();
writer->Update();
}
catch (exception & e)
{
cout << "Caught Error" << endl;
cout << e.what() << endl;
return EXIT_FAILURE;
}
filter->ThresholdAbove(190);
writer->SetFileName(output_name2);
try
{
filter->Update();
writer->Update();
}
catch (exception & e)
{
cout << "Caught Error" << endl;
cout << e.what() << endl;
return EXIT_FAILURE;
}
//Third Threshold Seg;
filter->ThresholdOutside(170, 190);
writer->SetFileName(output_name3);
try
{
filter->Update();
writer->Update();
}
catch (exception & e)
{
cout << "Caught Error" << endl;
cout << e.what() << endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
該例子中,用到的輸入圖像爲 ITK 官網提供的大腦切片 PNG 圖像,參數設定情況如下:Lower Threshold 設爲170,Upper Threshold 設爲190,Outsidevalue 設爲 0,
最後生成的結果圖如下,第 2-4 張圖片分別爲 第一至第三種方法生成得到的結果。