我编写了下一个函数来旋转一个无符号的char像素数组,该数组将RGB图像保持90度。我面临的问题是旋转的输出完全是乱码。
void rotate90(unsigned char *buffer, const unsigned int width, const unsigned int height)
{
const unsigned int sizeBuffer = width * height * 3;
unsigned char *tempBuffer = new unsigned char[sizeBuffer];
for (int y = 0, destinationColumn = height - 1; y < height; ++y, --destinationColumn)
{
int offset = y * width;
for (int x = 0; x < width; x++)
{
tempBuffer[(x * height) + destinationColumn] = buffer[offset + x];
}
}
// Copy rotated pixels
memcpy(buffer, tempBuffer, sizeBuffer);
delete[] tempBuffer;
}
答案 0 :(得分:5)
将最内层循环中的行替换为:
for (int i = 0; i < 3; i++)
tempBuffer[(x * height + destinationColumn) * 3 + i] = buffer[(offset + x) * 3 + i];
答案 1 :(得分:1)
这只是C,将一个强制转换为临时rgb类型,让编译器处理像素复制和偏移量计算:
#include <algorithm>
#include <memory>
// buffer is interleaved RGB
void rotate90( unsigned char *buffer, const unsigned int width, const unsigned int height ) {
struct rgb { unsigned char r_, g_, b_; };
static_assert( sizeof( rgb ) == 3, "?" );
size_t const count { width * height };
auto source = reinterpret_cast<rgb*>( buffer );
auto dest = std::unique_ptr<rgb[]>( new rgb[ count ] );
for ( size_t y {}, destinationColumn = height - 1; y < height; ++y, --destinationColumn ) {
size_t offset = y * width;
for ( size_t x {}; x < width; x++ )
dest[ ( x * height ) + destinationColumn ] = source[ offset + x ];
}
// Copy rotated pixels
std::copy_n( dest.get(), count, source );
}
您还应该在这里查看如何在没有临时存储和图像大小复制的情况下旋转90度的想法:http://en.wikipedia.org/wiki/In-place_matrix_transposition