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.
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).
Two approaches are available:
data = list(tuple(pixel) for pixel in pix) pic.putdata(data)
Note that this method can be slow for large arrays.
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!