Rotate Image by 90 degree in C++

Here I’ve discussed a very simple way to Rotate Image by 90 degree in C++ Programming.

Consider an image as a 2-Dimensional Array or 2-D matrix which can be stored in a Buffer.

We are given “base address” and dimension of Matrix.

Suppose we have an Image like this:

* * * | * * *
* * * | * * *
* * * | * * *
* * * | * * *

 

So after turning it by 90 degree we will have it like this:

* * * *
* * * *
* * * *
- - - -
* * * *
* * * *
* * * *

 

Now here is the Program to Rotate Image by 90 Degree in C++:

#include <iostream>
#include <stdlib.h>
using namespace std;

void displayMatrix(unsigned int const *p, unsigned int row, unsigned int col);
void rotate(unsigned int *pS, unsigned int *pD, unsigned int row, unsigned int col);

int main()
{
    // declarations
    unsigned int image[][4] = {{1,2,3,4}, {5,6,7,8}, {9,10,11,12}};
    unsigned int *pSource;
    unsigned int *pDestination;
    unsigned int m, n;

    // setting initial values and memory allocation
    m = 3, n = 4, pSource = (unsigned int *)image;
    pDestination = (unsigned int *)malloc(sizeof(int)*m*n);

    // process each buffer
    displayMatrix(pSource, m, n);

    rotate(pSource, pDestination, m, n);

    displayMatrix(pDestination, n, m);

    free(pDestination);

    getchar();
    return 0;
}

void displayMatrix(unsigned int const *p, unsigned int r, unsigned int c)
{
    unsigned int row, col;
    cout<<"nn";

    for(row = 0; row < r; row++)
    {
        for(col = 0; col < c; col++)
        {
            cout<<"t"<<*(p + row * c + col);
        }
        cout<<"n";
    }

    cout<<"nn";
}

void rotate(unsigned int *pS, unsigned int *pD, unsigned int row, unsigned int col)
{
    unsigned int r, c;
    for(r = 0; r < row; r++)
    {
        for(c = 0; c < col; c++)
        {
            *(pD + c * row + (row - r - 1)) = *(pS + r * col + c);
        }
    }
}

 

OUTPUT:

Rotate image by 90 degree

1 thought on “Rotate Image by 90 degree in C++”

  1. Here’s an easier to understand version…

    void rotate(size_t y, size_t x, char src[y][x], char dst[x][y]) {
    int i, j;
    for (i = 0;i < x;i++) {
    for (j = 0;j < y;j++) {
    dst[i][j] = src[y-j-1][i];
    }
    }
    }

    Reply

Leave a Reply to Bob Cancel reply