为什么 pillow 和 numpy 有时会错误地转换我的图像(但并非总是如此)?
Why are pillow and numpy incorrectly converting my image sometimes (but not all of the time)?
我正在制作一个程序,涉及将枕头 (PIL) 图像转换为 numpy 数组并将 numpy 数组转换回图像。但是,它正在将一些(但不是全部)图像转换回之前的颗粒状灰度版本。
代码的相关部分是:
from PIL import Image, fromarray
from numpy import asarray
im = Image.open("C:\path\to\image")
pixels = asarray(im)
Image.fromarray(pixels).show()
此代码应该显示与最初打开的相同的图像。它适用于某些图像。例如下图的安道尔国旗: . However, it doesn't work for other images, such as this image of the flag of Albania: . Instead, it becomes a grainy black and white image:。查看了它生成的 numpy 数组后,它似乎正在为图像中的每个像素生成一个数字而不是一个 RGB 元组,但我不知道为什么。我该怎么做才能使标志正确地来回转换?
安道尔国旗是 RGB 图像,阿尔巴尼亚国旗是彩色图图像。 PIL 可以将颜色图转换为 RGB:
im = Image.open("C:\path\to\image").convert('RGB')
print(im.mode) # => now it prints always RGB, without convert it would print P for colormap images
您可能会找到一些文档 here。
我正在制作一个程序,涉及将枕头 (PIL) 图像转换为 numpy 数组并将 numpy 数组转换回图像。但是,它正在将一些(但不是全部)图像转换回之前的颗粒状灰度版本。
代码的相关部分是:
from PIL import Image, fromarray
from numpy import asarray
im = Image.open("C:\path\to\image")
pixels = asarray(im)
Image.fromarray(pixels).show()
此代码应该显示与最初打开的相同的图像。它适用于某些图像。例如下图的安道尔国旗:
安道尔国旗是 RGB 图像,阿尔巴尼亚国旗是彩色图图像。 PIL 可以将颜色图转换为 RGB:
im = Image.open("C:\path\to\image").convert('RGB')
print(im.mode) # => now it prints always RGB, without convert it would print P for colormap images
您可能会找到一些文档 here。