Rotate Image Using OpenCV

  • Share this:

Code introduction


This function takes an image path and an angle as input, uses the OpenCV library to read the image, calculates the rotation matrix, and then rotates the image.


Technology Stack : OpenCV library, image processing, rotation matrix calculation, warpAffine

Code Type : The type of code

Code Difficulty : Advanced


                
                    
def rotate_image(image_path, angle):
    import cv2
    import numpy as np

    # Load the image
    image = cv2.imread(image_path)
    
    # Get the height and width of the image
    height, width = image.shape[:2]
    
    # Calculate the center of the image
    center = (width // 2, height // 2)
    
    # Get the rotation matrix
    M = cv2.getRotationMatrix2D(center, angle, 1.0)
    
    # Perform the rotation
    rotated = cv2.warpAffine(image, M, (width, height))
    
    return rotated