Rotate Image by 90 degrees

Rotate the given image by 90 degrees

Image : An image can be represented as a 2D matrix which can be stored in a buffer. So, the matrix contains it's base address.

Example

First row of given matrix will be last column and of a rotated matrix, second row will be last but one and so on.

Algorithm

Time Complexity: O(m*n) for matrix (mxn)
Basic idea: In rotated_image [i] [m-j-1] = given_image [j] [i] for all i, j

Step 1 : Store the image in a 2D vector.

a)    In the form of vector
b)    Initialize with given values.

Step 2 : Just run two loops such that we push back the rows. Traverse the array column wise and push the element.

a)    We create arbitrary variable vector Rotate_image.(nxm)
b)    We just use the above idea:
Rotate_image[i].push_back(Image[M-j-1][i])
we are pushing the last row of Image into first column and so on.

Step 3: we print both the original image and rotated image

Algorithm Working example

C++ Program

#include <bits/stdc++.h>
#include <iostream>
#include <vector>

using namespace std;

int main()
{
	int M = 3 , N = 4;
	// vector <vector <int> > Image {{1,2,3,4}, {5,6,7,8}, {9,10,11,12}};
	
	vector< vector<int> > Image(3, vector<int>(4));
	Image[0][0] = 1;
	Image[0][1] = 2;
	Image[0][2] = 3;
	Image[0][3] = 4;	 
	Image[1][0] = 5;
	Image[1][1] = 6;
	Image[1][2] = 7;
	Image[1][3] = 8;	 
	Image[2][0] = 9;
	Image[2][1] = 10;
	Image[2][2] = 11;
	Image[2][3] = 12;	 

	vector< vector <int> > Rotate_image(N);
	
	for(int i = 0 ;  i < N; i++)
		for(int j = 0 ; j < M; j++)
		{
			Rotate_image[i].push_back(Image[M-j-1][i]); //Traverse the array column wise in a right rotated manner and push the elements 
		}
	cout<<"Original image \n";
	for(int i = 0 ; i < M; i ++)	
	{
	 for(int j = 0 ; j < N; j++)
			cout<< Image[i][j] << " ";
		cout<<endl;
	}
	
	cout<<"\nRotated image is "<<endl;
	for(int i = 0 ; i < N; i ++)	
	{
	 for(int j = 0 ; j < M; j++)
			cout<< Rotate_image[i][j] <<" ";
		cout<<endl;
	}
	return 0;
}
Try It


Next > < Prev
Scroll to Top