Rotating an image is a common operation in image processing, and OpenCV provides simple methods to achieve this. This guide will walk you through the basic steps to rotate an image using OpenCV.
Installation
First, ensure you have OpenCV installed. You can install it using pip:
pip install opencv-python
Loading an Image
To rotate an image, you first need to load it. Use the cv2.imread function to read the image from a file.
import cv2
# Load the image
image = cv2.imread('path_to_your_image.jpg')
Rotating the Image
OpenCV allows you to rotate an image by creating a rotation matrix and applying it using cv2.warpAffine.
Get the Image Dimensions:
(height, width) = image.shape[:2]
Set the Rotation Angle and Center:
- Choose the angle for rotation and the center point around which to rotate.
angle = 45 # Rotation angle in degrees center = (width // 2, height // 2) # Center of the image
Create the Rotation Matrix:
- Use
cv2.getRotationMatrix2Dto create the rotation matrix.
rotation_matrix = cv2.getRotationMatrix2D(center, angle, 1.0)
Apply the Rotation:
- Use
cv2.warpAffineto apply the rotation to the image.
rotated_image = cv2.warpAffine(image, rotation_matrix, (width, height))
Displaying the Images
You can display the original and rotated images using cv2.imshow. This helps you see the result.
# Display the original image
cv2.imshow('Original Image', image)
# Display the rotated image
cv2.imshow('Rotated Image', rotated_image)
# Wait for a key press and close the windows
cv2.waitKey(0)
cv2.destroyAllWindows()
Complete Code Example
Here’s the complete code to rotate an image using OpenCV:
import cv2
# Load the image
image = cv2.imread('path_to_your_image.jpg')
# Get the image dimensions
(height, width) = image.shape[:2]
# Set the rotation angle and center
angle = 45 # Rotation angle in degrees
center = (width // 2, height // 2) # Center of the image
# Create the rotation matrix
rotation_matrix = cv2.getRotationMatrix2D(center, angle, 1.0)
# Apply the rotation
rotated_image = cv2.warpAffine(image, rotation_matrix, (width, height))
# Display the original image
cv2.imshow('Original Image', image)
# Display the rotated image
cv2.imshow('Rotated Image', rotated_image)
# Wait for a key press and close the windows
cv2.waitKey(0)
cv2.destroyAllWindows()