我正在尝试将图像逐个像素地旋转 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];
}
}
}