You mentioned numpy
. If you want a numpy array of the image, don't iterate through it, just do data = np.array(im)
.
E.g.
from PIL import Image
import numpy as np
im = Image.open("/Users/Hugo/green_leaves.jpg")
p = np.array(im)
Building up a numpy array by repeatedly appending to it is very inefficient. Numpy arrays aren't like python lists (python lists serve that purpose very well!!). They're fixed-size, homogenous, memory-efficient arrays.
If you did want to build up a numpy array through appending, use a list (which can be efficiently appended to) and then convert that list to a numpy array.
However, in this case, PIL images support being converted to numpy arrays directly.
On one more note, the example I gave above isn't 100% equivalent to your code. p
will be a height by width by numbands (3 or 4) array, instead of a numpixels by numbands array as it was in your original example.
If you want to reshape the array into numpixels by numbands, just do:
p = p.reshape(-1, p.shape[2])
(Or equivalently, p.shape = -1, p.shape[2]
)
This will reshape the array into width*height
by numbands (either 3 or 4, depending on whether or not there's an alpha channel) array. In other words a sequence of the red,green,blue,alpha pixel values in the image. The -1
is a placeholder that tells numpy to calculate the appropriate shape for the first axes based on the other sizes that are specified.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…