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)
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)
2. Using Image.fromarray() (PIL 1.1.6 or higher):
Simply assign the modified array to the image:
pic = Image.fromarray(pix)
Additional Notes:
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!