Home >Backend Development >Python Tutorial >How to Efficiently Convert PIL Images to NumPy Arrays and Back?

How to Efficiently Convert PIL Images to NumPy Arrays and Back?

Linda Hamilton
Linda HamiltonOriginal
2024-11-13 13:18:02449browse

How to Efficiently Convert PIL Images to NumPy Arrays and Back?

Converting PIL Images to NumPy Arrays and Back

When working with pixel-based transformations, the speed and flexibility of NumPy arrays can often be advantageous over PIL's PixelAccess. This article demonstrates how to efficiently convert PIL Images to NumPy arrays and back, enabling you to leverage the capabilities of both frameworks.

Converting PIL Image to NumPy Array

import PIL.Image
import numpy as np

pic = PIL.Image.open("foo.jpg")
pix = np.array(pic.getdata()).reshape(pic.size[0], pic.size[1], 3)

This code converts the PIL Image into a NumPy array with dimensions (height, width, channels).

Converting NumPy Array to PIL Image

Two approaches are available:

Method 1: Using pic.putdata()

data = list(tuple(pixel) for pixel in pix)
pic.putdata(data)

Note that this method can be slow for large arrays.

Method 2: Using Image.fromarray() (as of PIL 1.1.6)

pix = np.array(pic) # Converts PIL Image to NumPy array
# Make changes to the array
pic = PIL.Image.fromarray(pix)

This method generally performs faster and is the recommended approach for converting NumPy arrays back to PIL Images.

The above is the detailed content of How to Efficiently Convert PIL Images to NumPy Arrays and Back?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn