Rotate Image by Specified Angle using PIL

  • Share this:

Code introduction


This function reads an image file, rotates it by a specified angle using the PIL library, and returns the rotated image.


Technology Stack : OpenCV, PIL, NumPy

Code Type : Image processing

Code Difficulty : Intermediate


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

    # Load the image using OpenCV
    image = cv2.imread(image_path)
    
    # Convert the image to RGB (OpenCV uses BGR by default)
    rgb_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    
    # Convert the RGB image to a PIL Image object
    pil_image = Image.fromarray(rgb_image)
    
    # Rotate the image using PIL's rotate function
    rotated_image = pil_image.rotate(angle, expand=True)
    
    # Convert the rotated PIL Image back to a numpy array
    rotated_image_np = np.array(rotated_image)
    
    # Convert the numpy array back to BGR for OpenCV
    rotated_image_cv = cv2.cvtColor(rotated_image_np, cv2.COLOR_RGB2BGR)
    
    return rotated_image_cv                
              
Tags: