How to Resize Images Perfectly Without Losing Quality in Python

How to Resize Images Perfectly Without Losing Quality in Python

Resizing Images using Python

Image resizing with Python, a high-level interpreted programming language with dynamic typing, has become increasingly popular. Renowned for its clear syntax that emphasizes code readability, it's widely used in web development, data analysis, and machine learning. Python stands out for its extensive standard library and a robust ecosystem of packages, streamlining rapid prototyping and collaboration.

2 Tools to Resize Images in Python

  1. Pillow

  2. OpenCV

In image resizing, OpenCV excels in real-time processing and advanced manipulation, whereas Pillow is ideal for simple tasks. The choice hinges on the project's complexity and requirements.

By understanding the strengths and applications of each, developers can make informed decisions on the best approach for their specific image resizing needs.

OpenCVPillow
Strengths
PerformanceOptimized for real-time operations.Suited for straightforward image tasks.
Functionality RangeExtensive tools for image processing and computer vision.Simplified and user-friendly interface.
FlexibilitySupports various programming languages and platforms.Works well with other Python libraries.
Applications
Face detection, object recognition.Image cropping, rotation, resizing, filters.
Overlaying virtual images on real-time camera feeds.Format conversion: switching image formats.
Machines interpreting their surroundings.Web Development: optimizing images for websites.

For an informed decision, it's advisable to test both OpenCV and Pillow in the context of your specific tasks. Performance can vary based on the nature of the operation, and direct comparison will provide clarity on which library best suits your needs.

Resizing images using Pillow

Pillow is a fork of the Python Imaging Library (PIL) and has established itself as the premier solution for image resizing in Python. It offers a suite of robust tools made for diverse imaging operations The library ensures efficient Python image resize operations.

Its intuitive methods, especially resize() and thumbnail(), have set industry standards, making Pillow image resize practices an indispensable asset in the modern digital imaging toolkit.

Pillow accommodates a wide array of formats including but not limited to PNG, JPEG, TIFF, BMP, and GIF, ensuring flexibility and versatility in handling diverse image types.

In this article, we'll explore the two primary image resizing methods in the Pillow library: resize() and thumbnail(). We'll outline their functionalities and highlight the key differences, providing a clear guide for developers to choose the appropriate method for their image processing needs in Python.

Resize vs Thumbnail Methods

Featurethumbnail()resize()
PurposeResize an imageResize an image
Preserves original ratioYes. Maintains the image's aspect ratio.No, unless the provided dimensions are proportional to the original.
Returns a new instanceNo. Modifies the current instance.Yes, returns a new image instance.
Enlarges the imageDoesn't enlarge the image. If the provided dimensions are larger than the original, it retains the original size.Can enlarge the image, which might lead to quality loss.
Typical useUseful for generating thumbnails or reducing image size while maintaining the proportion.Useful when a specific size is needed without concern for the aspect ratio.

How to Install Pillow

Ensure PIL is uninstalled to avoid conflicts, as Pillow serves as its modern replacement.

Then, run the following commands:


python3 -m pip install --upgrade pip
python3 -m pip install --upgrade Pillow

How to Resize an Image using Pillow

pip install Pillow
from PIL import Image

The Image object in Pillow represents a loaded image, allowing for various manipulations like resizing, cropping, and rotating. It's the central interface for interacting with image data in the Pillow library.

How to Resize Images Using Pillow’s Thumbnail Method

  1. Load the image:
image_path = 'example.jpg'
image = Image.open(image_path)
print(image.size)
  1. Use the thumbnail method:
# Desired dimensions:
width, height = 800, 1000

# Resizing:
image.thumbnail((width, height))
image.save('resized_img.jpg')

When it comes to image resizing in Python, the thumbnail() method of the renowned Pillow library emerges as an indispensable tool. This method stands out particularly for those delving into Pillow image resize tasks, as it adjusts an image's dimensions without compromising its original aspect ratio. This intrinsic feature ensures images remain proportionate and free from distortions.

The thumbnail() function in Pillow preserves the original aspect ratio when resizing an image. When given dimensions, these act as maximum width and height values. For instance, with an original image of 800x600 pixels and resizing to 400x400 pixels using the thumbnail() function, the result will be 400x300 pixels, maintaining the 4:3 aspect ratio. The function ensures the image fits within the specified dimensions without distortion.

How to Resize Images using Pillow’s Resize Method

In step one, nothing changes. Just replace thumbnail() with resize() in step 2.

# Desired dimensions:
width, height = 800, 200

# Resizing:
resized_img = image.resize((width, height))
resized_img.save('imagem_resized.jpg')

Using the resize() method in Pillow with a different aspect ratio than the original image can result in distortion. This distortion stretches or compresses the image either horizontally or vertically, altering the original proportions and potentially misrepresenting the image content as you can see in the example below.

Here's an example: resizing a 1024x1024 image using the resize() method to produce an output of 800x200.

resized_img = image.resize((800, 200))

Original:

Resized Image:

It may be useful to print the dimensions of an Image when using Pillow. You can just:

print(image.size)

Syntax of Image.resize() and Image.thumbnail()

The Syntax of both methods are the same:

Image.resize(size, resample=0)
Image.thumbnail(size, resample=0)

There are only two parameters and they are simple to understand.

ParameterDescription
sizeA tuple representing the desired dimensions in pixels: (width, height).
resampleOptional. Specifies the resampling technique.

Resample methods:

ValueDescription
PIL.Image.BILINEARLinear interpolation.
PIL.Image.NEARESTUses nearest neighbor.
PIL.Image.LANCZOSA high-quality downsampling filter.
PIL.Image.BICUBICCubic spline interpolation.

The resample methods for the resize and thumbnail in Pillow determine the technique used to estimate pixel values when resizing, ranging from simple nearest-neighbor approaches to more advanced bicubic and Lanczos interpolations for higher-quality results.

For more information about each of the methods, you can refer to the section below titled "OpenCV Interpolation Methods Explained: Guide to Image Resizing" where we explain all these interpolation methods and an additional one.

Resize Images in Python With OpenCV

OpenCV, a leading library in computer vision, offers the resize() method as a straightforward solution for adjusting image dimensions in Python. This function is integral for professionals working with image processing, ensuring precision and efficiency in resizing tasks.

When using resize(), you have the flexibility to upscale or downscale images. You can maintain the original aspect ratio, ensuring consistent proportions, or choose to disregard it, which may lead to potential distortions.

How to Install and Resize Images Using OpenCV cv2

  1. Install OpenCV

     pip install opencv-python
    
  2. Load the original image

     import cv2
     original_img = cv2.imread('example.png')
    
  3. Resize the image and save

     resized_img = cv2.resize(original_img, (300,300), interpolation = cv2.INTER_AREA)
     cv2.imwrite('resized_opencv.png', resized_img)
    

    Understanding the cv2.resize() Syntax:

    When working with image processing in Python using OpenCV, the cv2.resize() function is essential for adjusting image dimensions. Understanding its syntax and parameters ensures optimal image resizing. Here's a detailed breakdown:

    cv2.resize(src, dsize, dst, fx, fy, interpolation)

    | Parameter | Description | | --- | --- | | src | [required] path of source/input image | | dsize | [required] tuple of integers of the desired size for the output image | | fx | [optional] scale factor along the horizontal axis | | fy | [optional] scale factor along the vertical axis | | interpolation | [optional] flag that takes one of the specified methods (see below) |

    OpenCV Interpolation Methods Explained: Guide to Image Resizing

    When resizing images using OpenCV, it's essential to understand the various interpolation methods and their applications. Interpolation techniques determine pixel values at new positions, critical for producing high-quality resized images.

    1. INTER_NEAREST: Fastest Interpolation Technique

    • Application: Quick image resizing.

    • Description: Uses the nearest pixel's value. While it's the fastest, it might not always offer the best visual output, especially during image enlargement.

2. INTER_LINEAR: Bilinear Interpolation for Balanced Results

  • Application: Common image resizing tasks.

  • Description: Incorporates values from the four closest pixels. This method strikes a balance between speed and visual quality, making it a popular choice in many applications.

3. INTER_AREA: Ideal for Image Downsizing

  • Application: Reducing image size.

  • Description: Uses pixel area relation, providing sharp, artifact-free reductions. It's especially effective in preventing the moiré effect when downsizing.

4. INTER_CUBIC: High-Quality Bicubic Interpolation

  • Application: Quality-centric image enlargement.

  • Description: Employs bicubic interpolation over a 4x4 pixel grid. While slower than INTER_LINEAR, it's favored for its smoother enlargements.

5. INTER_LANCZOS4: Top-Tier Interpolation for Enlargement

  • Application: Professional-grade image resizing.

  • Description: Leverages Lanczos interpolation across an 8x8 pixel neighborhood. For those prioritizing image quality, this method is a top pick.

The right interpolation method depends on your project's requirements. Prioritize speed with INTER_NEAREST, balance with INTER_LINEAR, and opt for quality with INTER_CUBIC or INTER_LANCZOS4. Always consider your image's purpose when choosing an interpolation method in OpenCV.

You can also explore more methods in the official documentation.

How can you maintain the aspect ratio by resizing images with fx and fy parameters?

To maintain the aspect ratio, you can pass None for 'dsize' parameter and fill fx and fy using only the percent scale of the desired output image as the following example shows:

    resized_img = cv2.resize(original_img, None, fx = 0.25, fy = 0.25)
    cv2.imwrite('resized_opencv2.png', resized_img)

Conclusion

Image resizing is an essential task in many development and design projects. Python, with its robust libraries like Pillow and OpenCV, simplifies this process, offering a range of methods and tools to cater to different needs.

  • Pillow: It's excellent for straightforward and quick tasks, with an intuitive interface and a broad range of supported formats.

  • OpenCV: It's a potent solution for those seeking more advanced tools and resizing options with greater flexibility.

When choosing a tool for image resizing in Python, always keep your project's purpose in mind. Whether for web optimization, data analysis, or real-time image processing, Python surely has the right tools to assist you.

If you're interested in delving deeper into the capabilities of these libraries, we recommend exploring advanced tutorials or the official documentation of each library. And remember, practice makes perfect. So start experimenting, test different methods in Python for image resizing, and discover what works best for you!

Official Documentation and Related Sites: