简单地说,使用所需的通道值创建类型的rgb8_pixel_t
值并将其分配给迭代器指向的像素。
举个简单的例子,这将用纯橙色填充您的图像:
#include <boost/gil.hpp>
#include <boost/gil/extension/io/png.hpp>
namespace gil = boost::gil;
int main()
{
gil::rgb8_image_t img(100, 100);
auto v = gil::view(img);
auto b = v.begin();
while (b != v.end())
{
*b = gil::rgb8_pixel_t{255, 128, 0};
b++;
}
gil::write_view("image.png", gil::view(img), gil::png_tag());
}
对于更复杂的示例,以下是如何使用像素通道值的自定义生成器:
#include <boost/gil.hpp>
#include <boost/gil/extension/io/png.hpp>
#include <random>
namespace gil = boost::gil;
template <typename T>
struct random_value
{
static_assert(std::is_integral<T>::value, "T must be integral type");
static constexpr auto range_min = std::numeric_limits<T>::min();
static constexpr auto range_max = std::numeric_limits<T>::max();
random_value() : rng_(rd_()), uid_(range_min, range_max) {}
T operator()()
{
auto value = uid_(rng_);
return static_cast<T>(value);
}
std::random_device rd_;
std::mt19937 rng_;
std::uniform_int_distribution<typename gil::promote_integral<T>::type> uid_;
};
int main()
{
random_value<channel_type<gil::rgb8_pixel_t>::type> make_channel_value;
gil::rgb8_image_t img(100, 100);
auto v = gil::view(img);
auto b = v.begin();
while (b != v.end())
{
// generate random value for each channel of RGB image separately
gil::static_generate(*b, [&make_channel_value]() { return make_channel_value(); });
b++;
}
gil::write_view("image.png", gil::view(img), gil::png_tag());
}
更新:这static_generate
是对颜色基础(例如像素)进行操作的 GIL 算法之一。这struct random_value
是一个仿函数类,因为它封装了随机数生成器的数据元素。我只是从 GIL 的test/core/image/test_fixture.hpp中复制了它,但它不必是一个类。它可以是任何可调用的、可用作函子的东西。我已经更新了带有命名空间限定的代码片段,gil::
以便更清楚地了解事物的来源。