F
F
FoxBoost2019-08-07 12:47:00
Python
FoxBoost, 2019-08-07 12:47:00

How to make Pillow's getdata() return an array of RGB tuples for a pixel if the photo is black and white?

I'm converting the PIllow pixel array to a NumPy 3D array, and this code works fine with color images:

def PIL2array(img):
    np.array(img.getdata(), np.uint8).reshape(img.size[0], img.size[1], 3)

But when a black and white image is served, the following error is thrown:
ValueError: cannot reshape array of size 784 into shape (28,28,3)

The problem is that instead of three pixel colors, Pillow returns one. All resulting arrays must be of the same dimension. How can you make it so that you can get three colors for each pixel in the case of a black and white image?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
alternativshik, 2019-08-07
@FoxBoost

And if you convert to RGB before that?

A
Andrey Dugin, 2019-08-19
@adugin

Everything is much simpler:
You can also put -1 instead of 3:

np.array(img.getdata(), np.uint8).reshape(img.size[0], img.size[1], -1)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question