如何使用boost::gil处理数字像素操作中的溢出

How to handle overflow in numeric pixel operations with boost::gil?

本文关键字:操作 溢出 像素 处理 何使用 boost gil 数字      更新时间:2023-10-16

boost::gil的数字扩展包含如下算法:

template <typename Channel1,typename Channel2,typename ChannelR>
struct channel_plus_t : public std::binary_function<Channel1,Channel2,ChannelR> {
   ChannelR operator()(typename channel_traits<Channel1>::const_reference ch1,
                       typename channel_traits<Channel2>::const_reference ch2) const {
      return ChannelR(ch1)+ChannelR(ch2);
   }
};

当用两个uint8通道值填充时,如果通道r也是uint8,则会发生溢出。

我认为计算应该

  • 使用不同的类型进行处理(如何从模板通道类型派生此类型?)
  • 将结果剪辑到ChannelR类型的范围以获得饱和结果(使用boost::gil::channel_traits<ChannelR>::min_value()/…max_value() ?)

如何以一种允许性能优化结果的方式做到这一点?

  • 转换为最大可能的类型?听起来适得其反…
  • 提供模板专门化库?有更好的主意吗?

我不知道这里有什么问题…我的反应是"所以不要将ChannelR设置为uint8,否则会中断"

你似乎是在争辩像

这样的代码
  uint8 a=128;
  uint8 b=128;
  uint8 c=a+b;  // Uh-Oh...

应该做一些聪明的事情(例如饱和算术)。

我建议的解决方案是使用更精确,或定义自己的channel_saturating_plus_t与您需要的行为,就像我建议的解决方案是

uint16 c=uint16(a)+uint16(b)

uint8 c=saturating_add(a,b);

并且感谢GIL的创建者甚至考虑将结果类型作为单独的类型参数公开;外面有很多不喜欢的东西!