Question

I've written the next function to rotate an unsigned char pixel array which holds a RGB image by 90 degrees. The problem I'm facing is that the rotated output is all completely garbled.

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;
}
Was it helpful?

Solution

Replace the line in the inner-most loop with:

for (int i = 0; i < 3; i++)
    tempBuffer[(x * height + destinationColumn) * 3 + i] = buffer[(offset + x) * 3 + i];

OTHER TIPS

this is merely C, add a cast to a temporary rgb type to let the compiler deal with pixel copy and offset computation :

#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 );
}

You should also look here for ideas on how to rotate by 90 degrees without a temporary storage and copy of the image size : http://en.wikipedia.org/wiki/In-place_matrix_transposition

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top