Tuesday 23 January 2024

OpenCV: Rotate an image by an angle

Rotation transformation rotate an object or image by a fixed angle. The transformation matrix for 2D rotation is given below.


[cos(θ) -sin(θ)]
[sin(θ) cos(θ)]

Θ represents the angle of rotation. A positive angle represents a counterclockwise (anti-clockwise) rotation. Conversely, a negative angle represents a clockwise rotation.

 

Following snippet rotate the image by given angle.

def rotate(img, angle, rotation_point=None):
    width = img.shape[1]
    height = img.shape[0]

    if rotation_point == None:
        rotation_point = (width // 2, height // 2)

    rotation_matrix = cv.getRotationMatrix2D(rotation_point, angle, 1.0)
    dimensions = (width, height)
    return cv.warpAffine(img, rotation_matrix, dimensions)

 

rotation_matrix = cv.getRotationMatrix2D(rotation_point, angle, 1.0)

First argument ‘rotation_point’ specifies the rotation point, which is the point around which the rotation will be performed.

 

Second argument angle specifies the rotation angle in degrees.

 

Third argument 1.0, specifies the scaling factor that allows you to resize the image.

 

Find the below working application.

 

rotation.py

 

import cv2 as cv

# if angle is positive, then it rotate the image in anti clock wise direction
# If angle is negative, then it rotate the image in clock wise direction
def rotate(img, angle, rotation_point=None):
    width = img.shape[1]
    height = img.shape[0]

    if rotation_point == None:
        rotation_point = (width // 2, height // 2)

    rotation_matrix = cv.getRotationMatrix2D(rotation_point, angle, 1.0)
    dimensions = (width, height)
    return cv.warpAffine(img, rotation_matrix, dimensions)


# Read the image as matrix of pixels
image = cv.imread('nature.png')
image = cv.resize(image, (1000, 800))

# Display the image in new window
cv.imshow('Nature', image)
cv.imshow('Rotate image by 45 degrees', rotate(image, 45))
cv.imshow('Rotate image by -45 degrees', rotate(image, -45))

# Wait for Infinite amount of time for a keyboard key to be pressed
cv.waitKey(0)

# Close the OpenCV windows
cv.destroyAllWindows()

Output

Original image 

 


Rotate image by 45 degrees

 


 

Rotate image by -45 degrees





 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment