My Coding > Programming language > Python > Python libraries and packages > Python NumPy > How to turn image 90 degree with NumPy

How to turn image 90 degree with NumPy

Pretty common task is to rotate image 90 degree. If the image already loaded into NumPy it is very easy to do with rot90() function. Actually this can be used to matrix rotation as well if you need it!

As usual, start with proper libraries. You need to have NumPy for manipulations with data and PIL for reading image.

import numpy as np 
from PIL import Image

Then load image and convert it to NumPy array

imP ='image_name.jpg')
imgN = np.array(imP)

Next step is rotate the matrix, which corresponds to the image

imgR = np.rot90(imgN, k = rotate, axes = (0, 1))

Where rotate is a number of 90 degree turns you need to perform. The rotation will be done in the plane specified by axes in the direction from the first towards the second axis.

So, to rotate image anticlockwise use by 90 degree, use:

imgR = np.rot90(imgN, k = 1, axes = (0, 1))

It is necessary to remember, that after rotation, Numpy Array will be allocated in the memory a bit messy, and some function will not work properly, giving an error:

cv2.error: OpenCV(4.5.5) :-1: error: (-5:Bad argument) in function 'putText'
> Overload resolution failed:
>  - Layout of the output array img is incompatible with cv::Mat
>  - Expected Ptr for argument 'img'

to avoid this error, you need to make this array continuous again

imgR = np.ascontiguousarray(imgR, dtype=np.uint8)

Published: 2022-07-22 21:24:32

Last 10 artitles

9 popular artitles

© 2020 -My blog about coding and further learning. This blog was writen with pure Perl and front-end output was performed with TemplateToolkit.