How to make getdata() from Pillow to return an array of tuples of RGB colors of the pixel, if the picture is black and white?

I convert the array of piskula obtained by using a PIllow in a three-dimensional NumPy 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 it is black-and-white image, you receive the following error:
ValueError: cannot reshape array of size 784 into shape (28,28,3)

The problem is that the Pillow instead of three colors of a pixel produces a single. Get all arrays must be of the same dimension. How can I make it so that you can get three colors for each pixel in case of black-and-white image?
March 25th 20 at 13:45
2 answers
March 25th 20 at 13:47
But if konvertnut in RGB before?
And how it can be done by means of Pillow? - eunice commented on March 25th 20 at 13:50
@eunice, the answer to this question is in the first position in Google, don't be lazy, please. - Ova_Fay commented on March 25th 20 at 13:53
@Ova_Fay, sorry, thanks for the reply, I'll leave the final code here:
def PIL2array(img):
 if type(img.getdata()[1]) == int:
 img = img.convert('RGB')
 return np.array(img.getdata(),
 np.uint8).reshape(img.size[0], img.size[1], 3)
- eunice commented on March 25th 20 at 13:56
@eunice, use the normal method:
if img.mode != 'RGB':
 img = img.convert('RGB')

And again the question, why convert the picture np.array in such a curved way, if you can call np.array(img), without any getdata and reshape? - velva commented on March 25th 20 at 13:59
@velva, thank you corrected, I copied this code from some website, because reshape does not work for black and white photos, I only then realized that the problem is that they are black and white. - eunice commented on March 25th 20 at 14:02
March 25th 20 at 13:49
Everything is much simpler:
You can even put -1 instead of 3:
np.array(img.getdata(), np.uint8).reshape(img.size[0], img.size[1], -1)
I needed arrays of all of the pictures were of the same dimension (28, 28, 3) - eunice commented on March 25th 20 at 13:52
@eunice, open the documentation for the Pillow, it says how to translate b/W image to RGB. Can also use the cv2.cvtColor() or np.repeat(). - velva commented on March 25th 20 at 13:55

Find more questions by tags NumPyPython