Guides
Last updated
August 2, 2023

Python Resize Image Numpy

Elizabeth (Lizzie) Shipton

Table of Contents:

Get your free
API key now
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required

Learning how to resize images is a frequent question for people learning Python, particularly for people who want to use Python for machine learning. One common use case for resizing images in Python is downsampling a large set of images for use in training an AI.

Image resizing in Python can be done in a few ways, but typically, for use cases such as the one mentioned above, people use the Numpy library. Numpy is a fundamental Python library that facilitates scientific computing. It exposes a multidimensional array object (a matrix), and a handful of methods that allow you to operate on arrays.

In this article, we'll explore the Numpy library as it relates to image manipulation and learn how to get a resized image using the Numpy array.

What Is Numpy?

The primary feature of Numpy is the ndarray. The Numpy array is an n-dimensional array that contains homogenous data types. Unlike a Python list or other standard Python sequence, an ndarray has a fixed size, is required to be of all one data type, and facilitates advanced mathematical operations.

There are an increasing number of Python-based packages being built using Numpy arrays. Many of them convert input into Numpy arrays before processing and output Numpy arrays.

How Does Image Resizing Work in Numpy?

If you're not familiar with Numpy, you're probably thinking, "Hang on. Numpy lets me work with arrays. What does that have to do with images?"

Put simply: an image is essentially a 2D array (matrix) of pixels. Therefore, it can be represented as a Numpy array. At a very basic level, you can imagine an image as a grid of squares W units wide and H units high. Once an image is represented as a Numpy array, we can work with in using Numpy functions.

Image processing packages built on Numpy (and Numpy itself) convert an original image into an ndarray object so that mathematical operations can be performed on it. By multiplying, dividing, and otherwise manipulating the array, we can perform image manipulation.

Let’s send your first free
call
See why the best developers build on Abstract
Get your free api

How to Resize an Image in Numpy

The Numpy library contains a resize function that changes the size of a Numpy array. Unfortunately, this function does not take into consideration an interpolation parameter or extrapolation.

Interpolation and Extrapolation

Interpolation and extrapolation both refer to ways of inferring new data based on existing data. Interpolation refers to the process of predicting values that fall within a range of points. Extrapolation refers to the process of predicting values that fall outside a range of points.

What does this have to do with image processing? When an image is resized, the resized image will contain data that was not in the original image. Interpolation and extrapolation occur when you increase or decrease the total number of pixels and map your image from one pixel grid to another.

Because Numpy alone does not account for interpolation or extrapolation, it is necessary to use a specialized image manipulation library like OpenCV or SciKit Image to work with image data.

Both of these libraries are built on Numpy and operate on the Numpy array.

Resize Images With OpenCV

OpenCV is the most widely used open-source Python library for image processing, manipulation, and computer vision. It exposes a function that reads an image into a Numpy array and provides further methods to work with the image as an ndarray.

Here is a basic method to scale images in OpenCV:



import cv2
import numpy as np

img = cv2.imread('original-image'.jpeg')
res = cv2.resize(img, dsize=(54, 140), interpolation=cv2.INTER_LINEAR)
cv2.imwrite('new-image.jpeg', res)

The imread function reads a standard image file into memory and converts it to a Numpy array. Next, the resize function accepts the image, the desired size, and an interpolation parameter. It adjusts the size of the Numpy array based on these parameters.

Finally, the imwrite function takes the resulting Numpy array, converts it back into a regular image, and writes the output image to a file with a typical image file extension. The dimensions you provide to the dsize parameter directly translate to the new image width and height in pixels.

The interpolation parameter can be any of the following:

  • INTER_NEAREST - interpolation using the nearest neighboring pixels
  • INTER_LINEAR - bilinear interpolation (default)
  • INTER_AREA - resampling using pixel area relation.
  • INTER_CUBIC - bicubic interpolation over 4x4 pixel neighborhood
  • INTER_LANCZOS4 - Lanczos interpolation over 8x8 pixel neighborhood

For more information on the different types of interpolation, read the docs.

Resize Images Using SciKit-Image

SciKit Image is another Python library based on Numpy that does image resizing with interpolation and extrapolation.

Here is the basic code for resizing an image with SciKit Image:



from skimage.transform import resize
from skimage.io import imsave, imread

img = imread('original-image.jpeg')
res = resize(img, (140, 54))
imsave('new-image.jpeg', res)

Similarly to OpenCV, SciKit Image exposes imread and imsave functions for converting image data to and from an ndarray. The resize function accepts the ndarray and a new width ratio and height for the output image.

Resize Images Using Pillow (PIL)

It's not necessary to use OpenCV or SciKit Image to resize images in Python code. It is possible to write your own function to resize an image, or to use a different library that isn't based on Numpy.

One such library is Pillow (Python Image Library fork since PIL was deprecated.) The code for resizing images using Pillow) is similar to the code for doing it in OpenCV or SciKit Image although the underlying method is different.

PIL Image Object

PIL does not convert an image into an ndarray. Rather, it converts images into PIL Image objects. The PIL Image object provides methods for opening and reading image data, for saving image data to a file, and for manipulating image data. It is possible to convert Numpy arrays to PIL Image objects and vice versa.

Here is the basic method for resizing an image in PIL.



from PIL import Image
from IPython.display import display

img = Image.open("original-image.jpg")
res = img.resize(250, 250)
resized_img.save('new-image.jpg')

As you can see, the process for working with images in PIL is much the same as for the other libraries from the outside.

Resize Images Using AbstractAPI

Let's quickly look at an alternative method to Numpy: the AbstractAPI Image Processing API. This API allows you to send an HTTP request to resize an image at a hosted URL.

Acquire an API Key

Navigate to the Images API home page and click “Get Started." You may need to sign up with your email and a password. The API is free.

Once you’ve signed up and logged in, you’ll land on the API dashboard.

Make a Request to the API

Use the requests module to send a POST request to the endpoint with your API key and the URL of the image you want to resize included in the parameters object.



api_url = "https: // images.abstractapi.com/v1/"
api_key = YOUR_API_KEY

def send_compress_image_request():
params = {
'api_key': api_key,
'url': 'https://s3.amazonaws.com/static.abstractapi.com/test-images/dog.jpg',
'resize': {
'width': 100,
'height': 75,
}
}
try:
response = requests.post(api_url, params=params)
print(response.content)
except requests.exceptions.RequestException as api_error:
print(f"There was an error contacting the Images API: {api_error}")
raise SystemExit(api_error)

This request will return a JSON object like the following:



{
"original_size":205559,
"original_height":430,
"original_width":1142,
"final_size":75101,
"bytes_saved":130458,
"final_height":75,
"final_width":100,
"url":"https://abstractapi-images.s3.amazonaws.com/8f2dd6392c524bc98313a89a24012b1f_dog.jpg"
}

The API returns a URL to a new file, hosted at one of AbstractAPI's AWS S3 buckets, along with some information about the original image and the new image. To use the resized image, simply access the URL of the new image via dot notation.

Conclusion

In this article, we looked at three different methods for resizing images in Python. Two of these methods relied upon the Numpy library, which provides a set of tools for performing mathematical operations on multidimensional arrays (called ndarrays.)

Working with Numpy to resize images is a common use case for people who want to use large image datasets to train AIs.

FAQs

How Do I Rescale an Image in Numpy?

To resize an image using Numpy, you can simply call the resize function on a Numpy array that has been derived from image data. However, Numpy alone will not account for interpolation and extrapolation. To rescale an image with these parameters in mind, use a library built on Numpy like OpenCV or SciKit Image.

How Do You Resize an Image in Python?

There are many ways to resize an image in Python. The easiest way is to use the PIL library, which turns an image file into a PIL Image object and exposes methods for image manipulation. You could use a Numpy-based library like OpenCV or SciKit Image to first convert the image to a Numpy array and then perform a resize operation.

What Is the Difference Between Reshape and Resize?

The primary difference between reshape and resize in Numpy is that resize modifies the original array, while reshape does not.

Elizabeth (Lizzie) Shipton

Lizzie Shipton is an adept Full Stack Developer, skilled in JavaScript, React, Node.js, and GraphQL, with a talent for creating scalable, seamless web applications. Her expertise spans both frontend and backend development, ensuring innovative and efficient solutions.

Get your free
key now
See why the best developers build on Abstract
get started for free

Related Articles

Get your free
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required