Python Program to Rotate an ImageIn this tutorial, we will write the Python program to solve the rotation of an image (matrix). It is a problem related to the matrix. Let's understand the problem statement. Problem StatementAn nxn 2D matrix represents an image. We need to rotate the image 90 degrees clockwise. We need to perform this operation using in-place means we do not need another 2D matrix and do the rotation. After the rotation, the image will look as below. Example -![]() Example - 1 Example - 2 Example - 3 We should follow the following constraints - SolutionWe will implement the following solution.
Let's see the following code. Example - Output: The input matrix is: [[1, 2, 3], [4, 5, 6], [7, 8, 9]] The matrix after rotation: [[7, 4, 1], [8, 5, 2], [9, 6, 3]] Explanation - In the above code, we have created a method that takes a matrix to be rotated. We iterated the outer loop, which will iterate each row of the matrix, and the outer loop is iterated over the column of each row. We changed the matrix's rows to columns and columns to rows inside the inner loop. If we print the transposed matrix, it will look as below. It will give the following output - [[1, 4, 7], [2, 5, 8], [3, 6, 9]] If we look closely at the transposed matrix, we are just one step away from getting the desired output. We only need to reverse each row. Hence we reversed each row of the matrix with the help of enumerate() function. It will give the following output - 0 [1, 4, 7] 1 [2, 5, 8] 2 [3, 6, 9] In the next line, we revered the rows and returned the matrix. Let's understand another solution. Solution - 2:In this solution, we will
Let's understand the following example. Example - Output: The input matrix is: [[1, 2, 3], [4, 5, 6], [7, 8, 9]] [[7, 8, 9], [4, 5, 6], [1, 2, 3]] The matrix after rotation: [[7, 4, 1], [8, 5, 2], [9, 6, 3]] ConclusionIn this tutorial, we have solved one of the interesting Python matrix problems that are asked by the many big organizations. We have implemented the solution using the multiple codes with the explanation. One you get the solution approach, do it your own.
Next TopicValidate the IP Address in Python
|
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week