Last modified: Nov 11, 2023 By Alexander Williams
Python: Resize Image While Keeping Aspect Ratio
Example 1: Resize Image Using OpenCV
import cv2
# Read the image
image = cv2.imread('path/to/your/image.jpg')
# Specify the target width (e.g., 300 pixels)
target_width = 300
# Calculate the aspect ratio
aspect_ratio = image.shape[1] / image.shape[0]
# Calculate the target height to maintain the aspect ratio
target_height = int(target_width / aspect_ratio)
# Resize the image
resized_image = cv2.resize(image, (target_width, target_height))
Output:
# Display the resized image
Example 2: Resize Image Using PIL (Pillow)
from PIL import Image
# Open the image
image = Image.open('path/to/your/image.jpg')
# Specify the target width (e.g., 300 pixels)
target_width = 300
# Calculate the aspect ratio
aspect_ratio = image.width / image.height
# Calculate the target height to maintain the aspect ratio
target_height = int(target_width / aspect_ratio)
# Resize the image
resized_image = image.resize((target_width, target_height))
Output:
# Display the resized image (if needed)
Example 3: Resize Image Using scikit-image
from skimage import io, transform
# Read the image
image = io.imread('path/to/your/image.jpg')
# Specify the target width (e.g., 300 pixels)
target_width = 300
# Calculate the aspect ratio
aspect_ratio = image.shape[1] / image.shape[0]
# Calculate the target height to maintain the aspect ratio
target_height = int(target_width / aspect_ratio)
# Resize the image
resized_image = transform.resize(image, (target_height, target_width))
Output:
# Display the resized image (if needed)