Rotating an Image Using cv2.warpAffine() in Python OpenCV

In python opencv, we can use cv2.warpAffine() and cv2.getRotationMatrix2D() function to rotate an image easily. In this tutorial, we will introduce you how to do.

Rotating an Image Using cv2.warpAffine() in Python OpenCV Tutorial

cv2.getRotationMatrix2D(center, angle, scale)

1.Open an image using cv2.imread()

import cv2
img = cv2.imread("pyimg.jpg")

Here img is <class ‘numpy.ndarray’>

2.Get the image width and height

height, width = img.shape[0:2]

Here is an tutorial:

Understanding Read an Image to Numpy Array with Python cv2.imread()

3.Set rotated angle using cv2.getRotationMatrix2D()

rotationMatrix = cv2.getRotationMatrix2D((width/2, height/2), 90, .5)

4.Rotate an image using cv2.warpAffine()

rotatedImage = cv2.warpAffine(img, rotationMatrix, (width, height))

5.Show the rotated image

cv2.imshow('Rotated Image', rotatedImage)

cv2.waitKey(0)

You also can write the rotated image to an file.

Save an Image in Python OpenCV

Rotating an Image Using cv2.warpAffine() in Python OpenCV