How to Convert a PIL Image to a NumPy Array and Back?

DDD
Release: 2024-11-23 07:33:08
Original
382 people have browsed it

How to Convert a PIL Image to a NumPy Array and Back?

Converting PIL Image to NumPy Array

Problem:

How can you convert a PIL Image to a NumPy array to perform faster pixel-wise transformations, and then load it back into the PIL Image after modifying the array?

Answer:

Conversion to NumPy Array:

To convert a PIL Image into a NumPy array, use the following code:

import numpy as np
from PIL import Image

pic = Image.open("foo.jpg")
pix = np.array(pic)
Copy after login

This will create a 3D array of shape (height, width, channels) containing pixel values.

Conversion Back to PIL Image:

To load the modified array back into the PIL Image, there are multiple ways:

1. Using Image.putdata():

Convert the array back to a sequence of tuples:

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

2. Using Image.fromarray() (PIL 1.1.6 or higher):

Simply assign the modified array to the image:

pic = Image.fromarray(pix)
Copy after login

Additional Notes:

  • The PIL Image's getdata() method returns a flattened array, so you need to reshape it to obtain a 3D array.
  • The NumPy array from np.array(pic) has the channels axis as the last dimension, while the getdata() method assumes the channels axis as the first dimension.
  • The Image.fromarray() method provides a faster conversion, especially for large images.

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

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template