ITK版本:4.13
#include <itkImage.h>
#include <itkRGBPixel.h>
// PNG对应
#include <itkPNGImageIOFactory.h>
// BMP对应
#include <itkBMPImageIOFactory.h>
// JPG对应
#include <itkJPEGImageIOFactory.h>
#include <itkImageFileReader.h>
#include "demo_ImportLib.h"
#include <iostream>
using namespace std;
const char *filename = "F:\\img_02_00.jpg";
int main(int, char * argv[])
{
typedef itk::RGBPixel<unsigned char> PixelType; // bmp,jpg,png使用unsigned char
typedef itk::Image<PixelType, 2> ImageType;
typedef itk::ImageFileReader<ImageType> ReaderType;
//创建图像读取器
ReaderType::Pointer reader = ReaderType::New();
itk::JPEGImageIOFactory::RegisterOneFactory();
itk::BMPImageIOFactory::RegisterOneFactory();
itk::PNGImageIOFactory::RegisterOneFactory();
reader->SetFileName(filename);
try {
reader->Update();
} catch (itk::ExceptionObject &e) {
cerr << e.what() << endl;
}
ImageType::Pointer image = ImageType::New();
image = reader->GetOutput();
const auto ®ion = image->GetLargestPossibleRegion();
int image_width = region.GetSize()[0];
int image_height = region.GetSize()[1];
//itk中访问图像数据需要通过Index,Index在这里理解成一个数组
//维数与图像维数对应
ImageType::IndexType pixcelIndex;
pixcelIndex[0] = 0;//列数
pixcelIndex[1] = 0;//行数
//获取图像的像素数据
PixelType pixel1 = image->GetPixel(pixcelIndex);
PixelType::ValueType red = pixel1.GetRed();
PixelType::ValueType green = pixel1.GetGreen();
PixelType::ValueType blue = pixel1.GetBlue();
//输出数据,注意,itk中的像素数据需要由专门的模块来处理
cout << "get pixel at [0,0]:" << endl;
cout << "R:" << itk::NumericTraits<PixelType::ValueType>::PrintType(red) << endl;
cout << "G:" << itk::NumericTraits<PixelType::ValueType>::PrintType(green) << endl;
cout << "B:" << itk::NumericTraits<PixelType::ValueType>::PrintType(blue) << endl;
// 遍历像素
for (int i = 0; i < image_width; ++i)
{
for (int j = 0; j < image_height; ++j)
{
ImageType::IndexType pixelIndex;
pixelIndex[0] = i;
pixelIndex[1] = j;
PixelType pixel1 = image->GetPixel(pixcelIndex);
PixelType::ValueType red = pixel1.GetRed();
PixelType::ValueType green = pixel1.GetGreen();
PixelType::ValueType blue = pixel1.GetBlue();
cout << "get pixel at [" << i << ", " << j << "]" << endl;
cout << "R:" << itk::NumericTraits<PixelType::ValueType>::PrintType(red) << endl;
cout << "G:" << itk::NumericTraits<PixelType::ValueType>::PrintType(green) << endl;
cout << "B:" << itk::NumericTraits<PixelType::ValueType>::PrintType(blue) << endl;
}
}
system("pause");
return 0;
}