当我尝试调整 ImageView 大小时,我遇到了一些与使用 boost::gil 库相关的问题。我想在调整大小后访问 ImageView 的像素内容。但是,这样做时我总是会遇到段错误。这是我的代码:
boost::gil::rgb8_image_t rgb_image;
//Try to convert image file to raw binary data
try {
boost::gil::read_and_convert_image("/tmp/image.jpg", rgb_image, boost::gil::jpeg_tag());
} catch (...) {
return;
}
boost::gil::rgb8_view_t rgb_view;
boost::gil::rgb8_image_t rgb_image_resize(150, 200);
boost::gil::resize_view(boost::gil::const_view(rgb_image), boost::gil::view(rgb_image_resize), boost::gil::bilinear_sampler());
rgb_view = boost::gil::view(rgb_image_resize);
for (std::uint32_t i = 0; i < 150; i++) {
boost::gil::rgb8_view_t::x_iterator it_image = rgb_view.row_begin(i);
for (size_t width = 0; width < 200; width++) {
if (it_image->at_c_dynamic(0) * 0.299 + it_image->at_c_dynamic(1) * 0.114 + it_image->at_c_dynamic(2) * 0.587 < 80) {//color filter. Trying to execute this line gives me a seg fault
//do something
} else { //white pixel
//do something
}
it_image++;
}
}
你能告诉我我的问题是什么吗?如果我删除 resize_view 函数并直接从 rgb_image 创建 View ,它会完美运行。
rgb_view.row_begin(i);
行为您提供了 i-th
行的 X 导航迭代器,您可以使用它来迭代 i-第
行像素。但是,您在嵌套循环中递增此迭代器 it_image++;
,即 150 * 200
次,这使得它远远超出了 的最后一个像素的末尾>第 i
行。
下面的示例显示了实现正确迭代的一种可能方法:
#include <boost/gil.hpp>
#include <boost/gil/extension/io/jpeg.hpp>
#include <boost/gil/extension/numeric/resample.hpp>
#include <boost/gil/extension/numeric/sampler.hpp>
int main()
{
namespace bg = boost::gil;
bg::rgb8_image_t rgb_image;
bg::read_and_convert_image("/tmp/example/test.jpg", rgb_image, bg::jpeg_tag());
bg::rgb8_image_t rgb_image_resize(68, 49); // rgb_image is 136x98
bg::resize_view(bg::const_view(rgb_image), bg::view(rgb_image_resize), bg::bilinear_sampler());
auto rgb_view = bg::view(rgb_image_resize);
for (int y = 0; y < rgb_view.height(); ++y)
{
bg::rgb8_view_t::x_iterator it_row = rgb_view.row_begin(y);
for (int x = 0; x < rgb_view.width(); ++x)
{
auto p = it_row[x];
if (p.at_c_dynamic(0) * 0.299 + p.at_c_dynamic(1) * 0.114 + p.at_c_dynamic(2) * 0.587 < 80)
; //do something
else
; //do something
}
}
}
有关更多选项,请查看 Boost.GIL 教程 example computing the image gradient .
注意:I/O 扩展已在 Boost 1.68 发布的 Boost.GIL 中完全重写 .上面的示例基于来自 Boost 1.68 的 GIL。
我是一名优秀的程序员,十分优秀!