What Is Python Image-Resize?
Python is a popular object-oriented programming language for image-related tasks for webpages, visualizations, or when using Python for machine-learning operations through frameworks like OpenCV and Scikit Learn.
Reducing the size of an image means changing its dimensions by removing its pixels. Scaling up an image increases the number of its pixels but lowers quality. Either way, the image’s aspect ratio changes, which results in distortion.
This article describes how to resize images in bulk with the Pillow library, a popular fork of the Python Imaging Library (PIL); and, to maintain the quality and aspect ratio, in OpenCV, a robust library of programming functions for computer vision. Also explained is how to resize and crop Python images with Cloudinary through automation.
- Resize Images in Python With Pillow
- Resize Images in Python With OpenCV
- Resize and Crop Images in Python With Cloudinary Through Automation
Resize Images in Python With Pillow
Pillow is a fork of the Python Imaging Library (PIL) that supports Python 3 and numerous image formats, including PNG, JPEG, TIFF, and PPM. When you load an image from a file, create a new image, or generate separate instances for images, you create an instance of PIL’s Image class.
To resize an image with Pillow’s
- Import the PIL
from PIL import Image
- Load the image from a file with the
image = Image.open('myimage.jpg')
The above command returns an
Imageobject. In case of failure, the command returns an
- Call the
resize()method on the new image instance, passing a tuple argument with two integers to specify the width and height you desire:
image = Image.open('myimage.jpg')
new_image = image.resize((500, 500))
Note: Instead of modifying the image file, this function returns a separate
Imageinstance with the new dimensions.
resize() method has two drawbacks, however:
- Oftentimes, resizing to an exact width and height changes the image’s aspect ratio, leading to distortions.
- If you set the size of the new instance to be larger than that of the original,
resize()“blows up” the instance, reducing its quality.
As a solution, resize the image with the more advanced Pillow method,
- Perform steps 1 and 2 of the above procedure.
- Call the
thumbnail()method on the
Imageinstance, passing a tuple argument with two integers to specify the width and height you desire:
image = Image.open('demo_image.jpg')
print(image.size) # Output: (400, 350)
As shown under
thumbnail() returns an instance of the same size.
Resize Images in Python With OpenCV
OpenCV is an open-source computer-vision library with thousands of machine-learning and deep-learning algorithms for face detection, object recognition, and many other computer-vision tasks. Given that numerous computer-vision models require a certain size and quality level for their images, resizing is critical. To determine which image variation performs best, experiment with different sizes or resolutions.
Here is the full syntax for the
resize() method in OpenCV:
cv2.resize(src, dsize, fx, fy, interpolation)
The parameters are as follows:
|src||The file path in which the input image resides.|
|dsize||The size of the output image, which adheres to the syntax
|fx||The scale factor for the X axis.|
|fy||The scale factor for the Y axis.|
|interpolation||The technique for adding or removing pixels during the resizing process. The default is
Note: Apply either
fy, or all three.
To perform a simple resizing task with OpenCV:
- Import the OpenCV library:
import matplotlib.pyplot as plt
- Acquire a sample image and specify its current size:
print('Image Width is',img.shape)
print('Image Height is',img.shape)
- Resize the image of, say, a size of 800×600 pixels, to 300×300 pixels:
As in the previous example on resizing images with Pillow’s resize() method, this procedure changes the aspect ratio, causing distortions. To maintain that ratio, run the following command to resize the image to 75% of its width and height:
img_75 = cv2.resize(img, None, fx = 0.75, fy = 0.75)
In addition, for a resized instance that is larger than the original, you can customize the interpolation of the resize operation. Even though doing that causes quality loss, it might be the right choice for certain computer-vision applications.
Here are the values for the
||The standard bilinear interpolation, ideal for enlarged images.|
||The nearest neighbor interpolation, which, though fast to run, creates blocky images.|
||The interpolation for the pixel area, which scales down images.|
||The bicubic interpolation with 4×4-pixel neighborhoods, which, though slow to run, generates high-quality instances.|
||The Lanczos interpolation with an 8×8-pixel neighborhood, which generates images of the highest quality but is the slowest to run.|
Resize and Crop Python Images With Cloudinary Through Automation
A cloud-based service for managing images and videos, Cloudinary offers a generous free-forever subscription plan. While on that platform, you can upload images and apply built-in effects, filters, and modifications.
You can also resize images through automation, focusing on the most important elements with AI, or adapt them to your website design by, for example, specifying the width, height, and aspect ratio as qualifiers for the new image instances. Cloudinary then automatically performs the resizing and cropping tasks to meet the criteria. No manual efforts are required.
Take this 1,200×1,200-pixel image:
Resizing it to 200×200 pixels with crop, scale, fill, and pad results in the following images:
To automate image resizing and cropping on Cloudinary:
- Sign up for a free Cloudinary account.
- Install the Python SDK.
- Set the transformation criteria for the above examples:
# Focus on the model in a portrait crop. CloudinaryImage("docs/model.jpg").image(gravity="person", height=600, width=450, crop="fill") # Detect the face for a thumbnail crop. CloudinaryImage("docs/model.jpg").image(gravity="face", height=250, width=250, crop="thumb") # Crop to a banner, automatically focusing on a region of interest. CloudinaryImage("docs/model.jpg").image(gravity="auto", height=150, width=600, crop="fill")