c++ - 将图像顺时针旋转 90 度

标签 c++

<分区>

我正在尝试将图像逐个像素地旋转 90 度,似乎有一个我无法解决的数学问题...和数组越界异常 这是我的尝试

const unsigned char *srcData = source.getData();
unsigned char *dstData = new unsigned char[width * height * bpp];


 size_t srcPitch = source.getRowSpan();
    size_t dstPitch = width * bpp;

     for(int i=0; i<height; i++)
    {
        for(int j=0; j<width * bpp; j++)
        {
            rotatedData[(i * dstPitch) + j]= dstData[(height-i) * dstPitch + j];
        }
    }

最佳答案

首先,让我们构建一个图像描述符来跟踪尺寸。

struct ImageDescriptor {
  std::size_t width;
  std::size_t height;
  std::size_t channels;

  std::size_t stride() const { return width * channels; }
  std::size_t offset(std::size_t row, std::size_t col, std::size_t chan) {
    assert(0 <= row && row < height);
    assert(0 <= col && col < width);
    assert(0 <= chan && chan < channels);
    return row*stride() + col*channels + chan;
    // or, depending on your coordinate system ...
    // return (height - row - 1)*stride() + col*channels + chan;
  }
  std::size_t size() const { return height * stride(); }
};

现在我们需要两个 ImageDescriptor 来跟踪我们的两个图像的尺寸。请注意,除非原始图像是方形的,否则旋转后的图像将具有不同的宽度和高度(因此跨度)。具体来说,旋转图像的宽度将是源图像的高度(反之亦然)。

const ImageDescriptor source(width, height, bpp);
ImageDescriptor target(height, width, bpp);  // note width/height swap

进行转换的一种常见方法是遍历目标像素并查找源像素。

unsigned char *rotated = new[target.size()];

for (std::size_t row = 0; row < target.height; ++row) {
  for (std::size_t col = 0; col < target.width; ++col) {
    for (std::size_t chan = 0; chan < target.channels; ++chan) {
       rotated[target.offset(row, col, chan)] =
           original[source.offset(col, row, chan)];
    }
  }
}

一旦你做对了,你就可以努力消除不必要的计算。第一个机会是逐步浏览目标图像,因为所有这些都是按内存顺序排列的。第二个机会是,将源偏移计算提升到 channel 循环之外。最后,如果 bpp 是常量,则可以展开最内层的循环。

unsigned char *p = rotated;
for (std::size_t row = 0; row < target.height; ++row) {
  for (std::size_t col = 0; col < target.width; ++col) {
    const std::size_t base = source.offset(col, row, 0);
    for (std::size_t chan = 0; chan < target.channels; ++chan) {
       *p++ = original[base + chan];
    }
  }
}

关于c++ - 将图像顺时针旋转 90 度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47870494/

相关文章:

c++ - 训练 sapi : Creating transcripted wav files and adding file paths to registry

c++ - 如何在 C++ 中获取类型的大小?

python - 编译多个模块时 import_array() 出现 Numpy/CAPI 错误

c++ - 之前编译报错unqualified-id

c++ - 指向成员类型和模板的指针

c++ - 在eclipse中运行C代码时出错

c++ - 英特尔 TSX 硬件事务内存 非事务线程看到什么?

c++ - strlen有副作用吗?

c++ - 为什么 C++ 显式实例化的模板方法不能覆盖虚拟方法?

c++ - 如何声明模板常量类型?