Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Matrix
  • Practice Matrix
  • MCQs on Matrix
  • Tutorial on Matrix
  • Matrix Traversal
  • Sorting in Matrix
  • Matrix Rotation
  • Transpose of Matrix
  • Inverse of Matrix
  • Determinant of Matrix
  • Matrix Application
  • Adjoint & Inverse Matrix
  • Sparse Matrix
  • Matrix Exponentiation
Open In App
Next Article:
Rotate a Matrix by 180 degree
Next article icon

Cpp14 Program to Turn an image by 90 degree

Last Updated : 24 May, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an image, how will you turn it by 90 degrees? A vague question. Minimize the browser and try your solution before going further. An image can be treated as 2D matrix which can be stored in a buffer. We are provided with matrix dimensions and it’s base address. How can we turn it? For example see the below picture,

* * * ^ * * * * * * | * * * * * * | * * * * * * | * * *

After rotating right, it appears (observe arrow direction)

* * * * * * * * * * * * -- - - > * * * * * * * * * * * *

The idea is simple. Transform each row of source matrix into required column of final image. We will use an auxiliary buffer to transform the image. From the above picture, we can observe that

first row of source ------> last column of destination second row of source ------> last but-one column of destination so ... on last row of source ------> first column of destination

In pictorial form, we can represent the above transformations of an (m x n) matrix into (n x m) matrix,

 

If you have not attempted, atleast try your pseudo code now. It will be easy to write our pseudo code. In C/C++ we will usually traverse matrix on row major order. Each row is transformed into different column of final image. We need to construct columns of final image. See the following algorithm (transformation)

for (r = 0; r < m; r++) {    for (c = 0; c < n; c++)    {       // Hint: Map each source element indices into       // indices of destination matrix element.        dest_buffer [ c ] [ m - r - 1 ] = source_buffer [ r ] [ c ];    } }

Note that there are various ways to implement the algorithm based on traversal of matrix, row major or column major order. We have two matrices and two ways (row and column major) to traverse each matrix. Hence, there can atleast be 4 different ways of transformation of source matrix into final matrix.

C++




// C++ program to turn an
// image by 90 Degree
#include <bits/stdc++.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);
             
void displayMatrix(unsigned int const *p,
                   unsigned int r,
                   unsigned int c)
{
    unsigned int row, col;
    cout << "
 
";
 
    for (row = 0; row < r; row++)
    {
        for (col = 0; col < c; col++)
            cout << * (p + row * c + col) << "    ";
        cout << "
";
    }
 
    cout << "
 
";
}
 
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);
        }
    }
}
 
// Driver Code
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);
 
    return 0;
}
 
// This code is contributed by rathbhupendra
 
 

Output :

 1    2    3    4     5    6    7    8     9    10    11    12         9    5    1     10    6    2     11    7    3     12    8    4    

Time Complexity: O(n*m) where n and m are matrix dimensions

Auxiliary Space: O(1)

Please refer complete article on Turn an image by 90 degree for more details!



Next Article
Rotate a Matrix by 180 degree
author
kartik
Improve
Article Tags :
  • C++
  • DSA
  • Matrix
  • rotation
Practice Tags :
  • CPP
  • Matrix

Similar Reads

  • Rotate a Rectangular Image by 90 Degree Clockwise
    Given an image represented by m x n matrix, rotate the image by 90 degrees in clockwise direction. Please note the dimensions of the result matrix are going to n x m for an m x n input matrix. Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16Output: 13 9 5 1 14 10 6 2 15 11 7 3 16 12 8 4 Another Example
    9 min read
  • OpenCV C++ Program to blur an image
    The following is the explanation to the C++ code to blur an Image in C++ using the tool OpenCV. Things to know: (1) The code will only compile in Linux environment. (2) Compile command: g++ -w article.cpp -o article `pkg-config --libs opencv` (3) Run command: ./article (4) The image bat.jpg has to b
    5 min read
  • Rotate an Image 90 Degree Counterclockwise
    Given an image represented by m x n matrix, rotate the image by 90 degrees in counterclockwise direction. Please note the dimensions of the result matrix are going to n x m for an m x n input matrix. Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output: 4 8 12 16 3 7 11 15 2 6 10 14 1 5 9 13 Input:
    6 min read
  • Javascript Program for Rotate a Matrix by 180 degree
    Given a square matrix, the task is that we turn it by 180 degrees in an anti-clockwise direction without using any extra space. Examples : Input : 1 2 3 4 5 6 7 8 9Output : 9 8 7 6 5 4 3 2 1Input : 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 Output : 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1Method: 1 (Only prints rotated
    6 min read
  • Rotate a Matrix by 180 degree
    Given a square matrix, the task is to turn it by 180 degrees. Note that when we rotate a matrix by 180 degree, clockwise and anticlockwise both give same results. Examples: Input: mat[][] = [[1, 2, 3] [4, 5, 6] [7, 8, 9]]Output: [9, 8, 7] [6, 5, 4] [3, 2, 1] Input: mat[][] = [[1, 2, 3, 4], [5, 6, 7,
    13 min read
  • OpenCV C++ Program to create a single colored blank image
    The following is the explanation to the C++ code to create a single colored blank image in C++ using the tool OpenCV. Things to know:  (1) The code will only compile in Linux environment. (2) To run in windows, please use the file: 'blank.o' and run it in cmd. However if it does not run (problem in
    3 min read
  • Program to Convert Radian to Degree
    Before moving to the actual solution, let's try to find out what is a degree, a radian, and their relations. Radian: The radian is the standard unit of angular measure, used in many areas of mathematics. The length of an arc of a unit circle is numerically equal to the measurement in radians of the
    5 min read
  • Program to convert Degree to Radian
    Given the angle in degree, the task is to convert this into radians.Examples: Input: degree = 45 Output: radian = 0.785398Input: degree = 58Output: radian = 1.01229 Approach: Radian: The Radian is the SI unit for measuring angles, used mainly in trigonometry. A radian is defined by an arc of a circl
    3 min read
  • Javascript Program to Inplace rotate square matrix by 90 degrees | Set 1
    Given a square matrix, turn it by 90 degrees in anti-clockwise direction without using any extra space. Examples : Input:Matrix: 1 2 3 4 5 6 7 8 9Output: 3 6 9 2 5 8 1 4 7 The given matrix is rotated by 90 degree in anti-clockwise direction.Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output: 4 8 1
    5 min read
  • Rotate Square Matrix by 90 Degrees Counterclockwise
    Given a n*n square matrix mat[][], rotate it by 90 degrees in counterclockwise direction without using any extra space. Examples: Input: mat[][] = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]Output: [[3, 6, 9], [2, 5, 8], [1, 4, 7]] Input: mat[][] = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences