首页 > 解决方案 > 如何迭代行对齐像素的子集

问题描述

我有一个来自行对齐的 PNG 的 BGRA 数据缓冲区。

unsigned int *data_; // bgra buffer described by 
                     // image_.ximage_->width and 
                     // image_.ximage_->height

我有兴趣对图像中的子图像进行采样。子图像由原点和高度和宽度定义:

struct Box {
        unsigned int x_;
        unsigned int y_;
        unsigned int width_;
        unsigned int height_;
};

我正在像这样走子图像::

unsigned int *origin, p;
origin = data_ + ((image_.ximage_->width * box.y_) + box.x_);
for( unsigned int j = 0 ; j < box.height_; ++j )
{
    p = origin + (image_.ximage_->width * j);
    for( unsigned int i = 0 ; i < box.width_; ++i )
    {
        p++;
    }
}

但是,我想做的不是遍历子图像中的每个像素,而是遍历每 n 个像素。例如,在查看源自此 5x5 图像的 0,0 的 3x3 子图像时,我想遍历每个第二个像素:

X _ X _ _
_ X _ _ _
X _ X _ _
_ _ _ _ _
_ _ _ _ _

但我想不出一个好的方法来做到这一点。有什么想法吗?重要的是我尽可能快地做到这一点。

标签: c++pngx11

解决方案


很难说没有测试什么是更快或更慢,但是一个平坦的索引可以解决问题:

for (uint idx = 0; idx<reg.height*reg.width; idx+=step) {
    uint i = idx%reg.height + reg.x, j = idx/reg.width + reg.y;
    img(i,j) = 'X';
}

可在此处测试:https ://godbolt.org/z/7jjGWj8rn


推荐阅读