Image Rotation Function

  • Share this:

Code introduction


This function reads an image file and rotates it by a given angle, returning the rotated image.


Technology Stack : OpenCV, NumPy

Code Type : Image processing

Code Difficulty : Intermediate


                
                    
import cv2
import numpy as np

def rotate_image(image_path, angle):
    # Read the image
    image = cv2.imread(image_path)
    
    # Get the height and width of the image
    (h, w) = image.shape[:2]
    
    # Calculate the center of the image
    center = (w // 2, h // 2)
    
    # Generate rotation matrix
    M = cv2.getRotationMatrix2D(center, angle, 1.0)
    
    # Perform the actual rotation and crop
    rotated = cv2.warpAffine(image, M, (w, h))
    
    return rotated                
              
Tags: