Reputation: 1674
I have a list of PIL images: p0, p1, ..., p85999 (a total of 86000 of them). They are all RGB, of size 30x30px.
I need to convert them to normalized numpy arrays, I did the following:
[np.asarray(r).astype('float32') / 255.0) for r in images]
where r
is a PIL image.
This gives an array of numpy arrays.
However, these arrays are sometimes of shape (30,30,3)
and sometimes of shape (30,30)
.
I want them always to be of shape (30,30,3)
.
I'm guessing numpy does this for performance reasons (when RGB is not needed, eg. white images?).
Anyway, how to get the desired result - get all numpy arrays to be of size (30,30,3)
?
Also, ideally I would want my final numpy array to be of size (30, 30, 3, 86000)
. Is there a shortcut to create such an array straight from PIL images?
Upvotes: 0
Views: 819
Reputation: 19153
I'm guessing numpy does this for performance reasons
Numpy has nothing to do with it, this is your PIL Image having one channel only.
The simplest solution is to just convert
everything to RGB:
ims = [np.asarray(r.convert('RGB')).astype('float32') / 255.0) for r in images]
If you then call np.asarray(ims)
, you'll obtain an array of shape [N,30,30,3]
where N is the number of images, which you can then transpose
to your desired ordering.
Upvotes: 1