将图片buffer写入到image

Import Pixel Buffer into an Image
官方demo:https://itk.org/ITKExamples/src/Core/Common/ImportPixelBufferIntoAnImage/Documentation.html

效果图:
将图片buffer写入到image_第1张图片

源码整理:

    //输出文件名称
    const char* outputFileName = "../Data/imagedata/imagetest.jpg";
   //图片buffer类型
    using PixelType = unsigned char;
    constexpr unsigned int Dimension = 2;

    using ImageType = itk::Image< PixelType, Dimension >;
    using ImportFilterType = itk::ImportImageFilter< PixelType, Dimension >;
    //将图片buffer写入到ImportFilterType
    ImportFilterType::Pointer importFilter = ImportFilterType::New();
    //指定图片的长宽
    ImportFilterType::SizeType  size;
    size[0]  = 200;  // size along X
    size[1]  = 200;  // size along Y

    ImportFilterType::IndexType start;
    start.Fill( 0 );
    ImportFilterType::RegionType region;
    region.SetIndex( start );
    region.SetSize(  size  );
    //图片区域
    importFilter->SetRegion( region );
    //图片原点
    const itk::SpacePrecisionType origin[ Dimension ] = { 0.0, 0.0};
    importFilter->SetOrigin( origin );
    //图片间距
    const itk::SpacePrecisionType  spacing[ Dimension ] =  { 1.0, 1.0};
    importFilter->SetSpacing( spacing );
    //像素数量
    const unsigned int numberOfPixels =  size[0] * size[1];

    //生成图片buffer区域
    auto * localBuffer = new PixelType[ numberOfPixels ];
    constexpr double radius = 80.0;
    const double radius2 = radius * radius;
    PixelType * it = localBuffer;
    for(unsigned int y=0; y < size[1]; y++)
      {
      const double dy = static_cast<double>( y )
        - static_cast<double>(size[1])/2.0;
      for(unsigned int x=0; x < size[0]; x++)
        {
        const double dx = static_cast<double>( x )
          - static_cast<double>(size[0])/2.0;
        const double d2 = dx*dx + dy*dy;
        *it++ = ( d2 < radius2 ) ? 255 : 0;
        }
      }
    //是否为importFilter所拥有,跟随importFilter释放
    const bool importImageFilterWillOwnTheBuffer = true;
    //将图片buffer设置到importFilter
    importFilter->SetImportPointer( localBuffer, numberOfPixels,
                                    importImageFilterWillOwnTheBuffer );

    //保存图片
    using WriterType = itk::ImageFileWriter< ImageType >;
    WriterType::Pointer writer = WriterType::New();
    writer->SetFileName( outputFileName );
    writer->SetInput(  importFilter->GetOutput()  );
    typedef itk::JPEGImageIO ImageIOType;
    ImageIOType::Pointer jpegImageIO = ImageIOType::New();
    writer->SetImageIO(jpegImageIO);
    try
      {
      writer->Update();
      }
    catch( itk::ExceptionObject & exp )
      {
      std::cerr << "Exception caught !" << std::endl;
      std::cerr << exp << std::endl;
      return EXIT_FAILURE;
      }

你可能感兴趣的:(ITK,PixelBuffer,image)