PIL: Image.fromarray(img.astype('uint8'), mode='RGB') returns grayscale image
我已经将大小为
PIL版本1.1.7
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | # This code implements the __getitem__ function for a child class of datasets.MNIST in pytorch # https://pytorch.org/docs/stable/_modules/torchvision/datasets/mnist.html#MNIST img, label = self.data[index], self.targets[index] assert img.shape == (3, 28, 28), \\ (f'[Before PIL] Incorrect image shape: expecting (3, 28, 28),' f'received {img.shape}') print('Before reshape:', img.shape) # torch.Size([3, 28, 28]) img = img.numpy().reshape(3, 28, 28) img = np.stack([img[0,:,:], img[1,:,:], img[2,:,:]], axis=2) print('After reshape:', img.shape) # (28, 28, 3) # doing this so that it is consistent with all other datasets # to return a PIL Image img = Image.fromarray(img.astype('uint8'), mode='RGB') # Returns 28 x 28 image assert img.size == (3, 28, 28), \\ (f'[Before Transform] Incorrect image shape: expecting (3, 28, 28), ' f'received {img.size}') |
编辑:这是一个最小的示例。如果有任何帮助,我将保留上述内容。
1 2 3 4 5 6 7 8 9 | from PIL import Image import numpy as np img = np.random.randn(28, 28, 3) img = Image.fromarray(img.astype('uint8'), mode='RGB') # Returns 28 x 28 image assert img.size == (28, 28, 3), \\ (f'[Before Transform] Incorrect image shape: expecting (3, 28, 28), ' f'received {img.size}') |
我想您想要这样,其中RGB值的范围是0..255:
范围内的整数
1 2 3 4 5 6 7 8 | import numpy as np from PIL import Image # Make random 28x28 RGB image img =np.random.randint(0,256,(28,28,3), dtype=np.uint8) # Convert to PIL Image pImg=Image.fromarray(img, mode='RGB') |
现在检查我们拥有什么:
1 2 | In [19]: pImg Out[19]: <PIL.Image.Image image mode=RGB size=28x28 at 0x120CE9CF8> |
并保存:
1 | pImg.save('result.png') |