
Have you ever wondered how search engines gather all that information from the internet? Learn how to build your own web crawler in Python and
Learn how to resize images while maintaining the aspect ratio in Python using libraries like Pillow and OpenCV. Follow our step-by-step guide with code examples, best practices, and troubleshooting tips.
Resizing images while maintaining their aspect ratio is a crucial task in many applications, from web development to machine learning. Whether you’re building a website, processing images for a mobile app, or preparing datasets for artificial intelligence, it’s important to resize images in a way that preserves their original proportions. If you don’t maintain the aspect ratio, you risk distorting your images, leading to poor user experience and suboptimal results.
In this guide, we’ll walk you through how to resize images while keeping their aspect ratio intact using Python. We will cover the following topics:
|
Understanding Aspect Ratio |
The aspect ratio of an image is the ratio of its width to its height. It is commonly expressed as two numbers separated by a colon (e.g., 16:9, 4:3). When resizing an image, maintaining the aspect ratio ensures that the image’s proportions stay the same.
For example, if an image is 800px wide and 600px tall (aspect ratio 4:3), resizing it to a new width of 400px would require the height to change proportionally to 300px (to maintain the 4:3 ratio). If the aspect ratio is not preserved, the image could appear stretched or compressed.
Why Maintain the Aspect Ratio? |
Maintaining the aspect ratio ensures that images look natural and aren’t distorted. Whether you are designing a website or training a machine learning model, you want to avoid stretching or squishing images as it can negatively impact their visual quality. Here are a few key reasons for maintaining the aspect ratio:
|
There are several Python libraries available for image manipulation. The most commonly used ones for resizing images are Pillow (PIL) and OpenCV. Let’s explore both.
Pillow (PIL) |
Pillow is a Python Imaging Library (PIL) fork that provides extensive file format support and powerful image processing capabilities. It’s the go-to library for basic image manipulation, including resizing, cropping, and format conversion.
OpenCV |
OpenCV is a powerful library designed for computer vision tasks. It is widely used in machine learning, video analysis, and image processing applications. OpenCV also provides support for resizing images and maintaining aspect ratios, although it is a more comprehensive tool than Pillow.
Resizing Images in Python with Pillow |
Here’s how you can resize an image with Pillow, maintaining the aspect ratio.
Installation |
To install Pillow, run the following command:
pip install pillow
Defaulting to user installation because normal site-packages is not writeable
Requirement already satisfied: pillow in /home/admin/.local/lib/python3.9/site-packages (10.3.0)
Code Example:
from PIL import Image
def resize_image(input_path, output_path, base_width):
img = Image.open(input_path)
# Calculate the aspect ratio
aspect_ratio = img.height / img.width
new_height = int(base_width * aspect_ratio)
# Resize the image
img = img.resize((base_width, new_height), Image.ANTIALIAS)
img.save(output_path)
# Example usage
resize_image('input_image.jpg', 'output_image.jpg', 400)
In this example, we resize the image to a new width (base_width
), while maintaining the original aspect ratio. The new height is calculated based on the aspect ratio of the original image.
Resizing Images in Python with OpenCV |
OpenCV also provides a straightforward way to resize images while preserving their aspect ratio. Here’s how you can do it.
Installation |
To install OpenCV, run the following command:
pip install opencv-python
Defaulting to user installation because normal site-packages is not writeable
Collecting opencv-python
Downloading opencv_python-4.11.0.86-cp37-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (63.0 MB)
|████████████████████████████████| 63.0 MB 24.5 MB/s
Collecting numpy>=1.17.0
Downloading numpy-2.0.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (19.5 MB)
|████████████████████████████████| 19.5 MB 80.1 MB/s
Installing collected packages: numpy, opencv-python
Successfully installed numpy-2.0.2 opencv-python-4.11.0.86
Code Example:
import cv2
def resize_image(input_path, output_path, base_width):
# Load the image
img = cv2.imread(input_path)
# Calculate the aspect ratio
aspect_ratio = img.shape[0] / img.shape[1]
new_height = int(base_width * aspect_ratio)
# Resize the image
img_resized = cv2.resize(img, (base_width, new_height))
# Save the resized image
cv2.imwrite(output_path, img_resized)
# Example usage
resize_image('input_image.jpg', 'output_image.jpg', 400)
The process is similar to the one in Pillow: you calculate the new height based on the aspect ratio, resize the image, and save it.
Simple Resize Example (Fixed Width) |
Let’s say you want to resize an image to a fixed width, keeping the height proportional.
def resize_image(input_path, output_path, new_width):
img = Image.open(input_path)
aspect_ratio = img.height / img.width
new_height = int(new_width * aspect_ratio)
img = img.resize((new_width, new_height), Image.ANTIALIAS)
img.save(output_path)
Resize with Fixed Height |
If you want to resize an image to a fixed height and calculate the corresponding width:
def resize_image_by_height(input_path, output_path, new_height):
img = Image.open(input_path)
aspect_ratio = img.width / img.height
new_width = int(new_height * aspect_ratio)
img = img.resize((new_width, new_height), Image.ANTIALIAS)
img.save(output_path)
Resize Image to Fit Within a Max Width and Height |
If you need to resize an image to fit within specific max width and height constraints, you can adjust both dimensions accordingly:
def resize_image_max(input_path, output_path, max_width, max_height):
img = Image.open(input_path)
# Calculate the scaling factor
width_ratio = max_width / img.width
height_ratio = max_height / img.height
scaling_factor = min(width_ratio, height_ratio)
new_width = int(img.width * scaling_factor)
new_height = int(img.height * scaling_factor)
img = img.resize((new_width, new_height), Image.ANTIALIAS)
img.save(output_path)
|
Resizing images while maintaining their aspect ratio is a simple yet crucial task in various fields, including web development and machine learning. By using Python libraries like Pillow and OpenCV, you can resize images without distorting them, ensuring they retain their quality and proportions. In this guide, we’ve provided code examples, best practices, and troubleshooting tips to help you successfully resize images in Python.
By following the steps outlined in this blog post, you can handle image resizing with ease and ensure that your images look their best across all platforms. Did you find this article useful? Your feedback is invaluable to us! Please feel free to share this post!
Have you ever wondered how search engines gather all that information from the internet? Learn how to build your own web crawler in Python and
Learn how to batch resize images (PNG, JPEG, etc.) using a Python script. Optimize your website or project by automating image resizing with the Pillow
In this tutorial, we’ll explore how to leverage Python to convert PNG images to WebP format, empowering you to enhance your website’s performance and boost