Alright, I\'m toying around with converting a PIL image object back and forth to a numpy array so I can do some faster pixel by pixel transformations than PIL\'s Pixel
I am using Pillow 4.1.1 (the successor of PIL) in Python 3.5. The conversion between Pillow and numpy is straightforward.
from PIL import Image
import numpy as np
im = Image.open('1.jpg')
im2arr = np.array(im) # im2arr.shape: height x width x channel
arr2im = Image.fromarray(im2arr)
One thing that needs noticing is that Pillow-style im
is column-major while numpy-style im2arr
is row-major. However, the function Image.fromarray
already takes this into consideration. That is, arr2im.size == im.size
and arr2im.mode == im.mode
in the above example.
We should take care of the HxWxC data format when processing the transformed numpy arrays, e.g. do the transform im2arr = np.rollaxis(im2arr, 2, 0)
or im2arr = np.transpose(im2arr, (2, 0, 1))
into CxHxW format.