How to Resize an Image Array in Python?

Estimated read time 2 min read

To resize an image array in Python, you can use the resize function from the NumPy library. NumPy provides a powerful set of functions for working with multi-dimensional arrays. Here’s an example code snippet that demonstrates how to resize an image array:

import numpy as np
from PIL import Image

def resize_image_array(image_array, new_size):
    Resize an image array using NumPy.

    :param image_array: The input image array.
    :param new_size: The desired size of the resized image as a tuple (new_width, new_height).
    :return: The resized image array.
    image = Image.fromarray(image_array)
    resized_image = image.resize(new_size)
    resized_array = np.array(resized_image)
    return resized_array

# Example usage:
image_array = np.array('image.jpg'))
new_size = (800, 600)  # New size of the image

resized_array = resize_image_array(image_array, new_size)

In this code, we define the resize_image_array function that takes two parameters: image_array (the input image array) and new_size (the desired size of the resized image as a tuple of new_width and new_height).

Inside the function, we create a PIL Image object from the input image array using Image.fromarray. Then, we call the resize method on the image object, passing the new size. Next, we convert the resized image back to a NumPy array using np.array. Finally, we return the resized image array.

In the example usage section, we first load the input image as an array using np.array('image.jpg')). Then, we specify the desired new size as (800, 600). We call the resize_image_array function with the input image array and the new size, and store the resulting resized image array in the resized_array variable.

Make sure you have the NumPy and PIL libraries installed, and the input image file exists in the specified location. The code will resize the image array and return the resized version as a NumPy array.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply