首先,让我们构建一个图像描述符来跟踪尺寸。
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(); }
};
现在我们需要两个ImageDescriptors来跟踪我们两幅图像的尺寸。请注意,除非原始图像是正方形,否则旋转后的图像将具有不同的宽度和高度(从而步幅)。具体来说,旋转图像的宽度将是源图像的高度(反之亦然)。
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)];
}
}
}
一旦你做对了,你可以努力消除不必要的计算。第一个机会就是通过目标图像,因为所有内容都是按照内存顺序。第二个机会是,将通道回路中的源偏移计算提升出来。最后,如果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++相同)比'-'优先级数字 – user463035818
仍具有一定界限dstData [I + J *宽度* BPP] = srcData [(宽×BPP)* J + 1 - j]; –
你已经有了dstPitch,不知道你为什么没有在你的条件中使用它作为inner for循环。 – Eddge