使用 Boost.GIL 将图像转换为“原始”字节

2023-12-14

Goal

我正在尝试转向 Boost GIL 来取代我已经实现的一些类似功能,这些功能即将达到其可维护生命周期。

我现有的代码可以使用 24 BPP、8 位 RGB 图像uint8_t*。我无法更改这一点,因为使用相同的接口来公开来自不同位置的图像(例如 OpenGL 缓冲区)并且已经有相当多的代码。

因此,我尝试小步使用 GIL,首先读取文件并将像素逐字节复制到std::vector<uint8_t>我可以用它来管理存储,但仍然得到一个uint8_t*通过使用&vector[0].

这可以透明地放在现有接口后面,直到达到重构有意义的程度为止。

我尝试过的

我认为这应该是一个简单的使用案例copy_pixels()有两个适当构造的视图。

我整理了一个最小、完整的示例,说明了我通过查看文档和尝试所实现的目标的总和:

#include <boost/gil/rgb.hpp>
#include <boost/gil/extension/io/png_dynamic_io.hpp>
#include <stdint.h>
#include <vector>

int main() {
  std::vector<uint8_t> storage;
  {
    using namespace boost::gil;
    rgb8_image_t img;
    png_read_image("test.png", img);

    // what should replace 3 here to be more "generic"?
    storage.resize(img.width()*img.height()*3);

    // doesn't work, the type of the images aren't compatible.
    copy_pixels(const_view(img), 
                interleaved_view(img.width(), img.height(), &storage[0], 3*img.width()));
  }
}

我被困住的地方

这不能编译:

error: cannot convert ‘const boost::gil::pixel<unsigned char, boost::gil::layout<boost::mpl::vector3<boost::gil::red_t, boost::gil::green_t, boost::gil::blue_t> > >’ to ‘unsigned char’ in assignment

这是相当不言自明的 - RGB 像素不能转换为单个像素unsigned char自动地。我想我会尝试使用copy_and_convert_pixels()来解决这个问题,但我看不到 3:1 的方法(即我有 3unsigned chars 在源图像中每个像素的输出中)这些转换的问题。转换似乎更针对色彩空间转换(例如 RGB->HSV)或包装更改。


我将分别推回 rgb8_pixel_t 的每种颜色:

struct PixelInserter{
        std::vector<uint8_t>* storage;
        PixelInserter(std::vector<uint8_t>* s) : storage(s) {}
        void operator()(boost::gil::rgb8_pixel_t p) const {
                storage->push_back(boost::gil::at_c<0>(p));
                storage->push_back(boost::gil::at_c<1>(p));
                storage->push_back(boost::gil::at_c<2>(p));
        }
};

int main() {
  std::vector<uint8_t> storage;
  {
    using namespace boost::gil;
    rgb8_image_t img;
    png_read_image("test.png", img);
    storage.reserve(img.width() * img.height() * num_channels<rgb8_image_t>());
    for_each_pixel(const_view(img), PixelInserter(&storage));
  }
...
}

...但我也不是 GIL 方面的专家。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Boost.GIL 将图像转换为“原始”字节 的相关文章

随机推荐