读取透明图像 boost.gil C++

问题描述

我有一个带有透明背景的图像,我想将它复制到另一个图像上,这两个图像都是 png 格式我已经尝试使用 boost::gil::rgba8_image_t 但它仍然复制带有灰色背景的透明图像。 这是我用过的

#include <boost/gil.hpp>
#include <boost/gil/extension/io/png.hpp>
#include <boost/gil/extension/numeric/resample.hpp>
#include <boost/gil/extension/numeric/sampler.hpp>
#include <string>

namespace bg = boost::gil;

int main() {
    std::string target{"./jail.png"};
    std::string picture("./example_in.png");
    bg::rgba8_image_t jail;
    bg::rgba8_image_t temp;
    bg::read_and_convert_image(target,jail,bg::png_tag{});
    bg::rgba8_image_t pic(jail.dimensions());
    bg::read_and_convert_image(picture,temp,bg::png_tag{});
    bg::resize_view(bg::view(temp),bg::view(pic),bg::bilinear_sampler{});
    bg::copy_pixels(bg::view(jail),bg::view(pic));
    bg::write_view("out.png",bg::png_tag{});
}

解决方法

嗯。阅读本文似乎完全符合您的要求:

bg::resize_view(bg::view(temp),bg::view(pic),bg::bilinear_sampler{});

这会用输入图像的调整大小视图填充像素。新的大小与您的监狱的大小完全匹配。现在:

bg::resize_view(bg::view(temp),bg::bilinear_sampler{});

jail 图像中的所有像素复制到其上。这将替换您刚刚从调整大小的输入图像中填充的任何像素。

你的输出看起来像

enter image description here

注意背景的方格。这是表示透明度的常规模式。那不是灰色。它只是具有完全透明度的空像素。

您大概想要的是保留背景像素。 Boost GIL¹ 中似乎没有高级像素操作,但您自己编写:

using Img = bg::rgba8_image_t;
using Pix = Img::value_type;

void overlay_combine(Img& pic,Img const& overlay) {
    assert(pic.dimensions() == overlay.dimensions());
    bg::transform_pixels(
        view(pic),const_view(overlay),view(pic),[](Pix const& a,Pix const& b) {
            return get_color(b,bg::alpha_t{})? b : a;
        });
}

现在你像这样写 main

int main() {
    Img jail,polar;
    bg::read_and_convert_image("./jail_PNG16.png",jail,bg::png_tag{});
    bg::read_and_convert_image("./polar.png",polar,bg::png_tag{});

    Img pic(jail.dimensions());
    bg::resize_view(bg::view(polar),bg::bilinear_sampler{});
    overlay_combine(pic,jail);

    bg::write_view("out.png",bg::png_tag{});
}

结果是:

enter image description here

你可以猜到我从哪里得到的 polar.png :)

¹ 参见例如How to combine images with boost gil?

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...