使用 PIL 打开带有调色板的图像并使用相同的调色板保存该图像
Using PIL to open an image with a palette and save that image with the same palette
所以我正在尝试将 bmp 转换为 NumPy 数组,将数组存储在某处,然后稍后再将其转换回 bmp 图像。
bmp = Image.open(fn_bmp)
data = np.array(bmp.convert('P', palette=Image.WEB))
这些数据暂时保存在另一个文件中,稍后我会去取回它。
bmp = Image.fromarray(np.array(dataset).convert('P', palette=Image.WEB))
bmp.save(fn)
请注意,数据集是一个转换回 NumPy 数组的对象,并且 np.array(dataset) == 所有索引中的数据。
出于某种原因,当我显示或保存此结果图像时,与某些调色板颜色对应的“14”被解释为灰度值并保存了一个这样的值。如何将图像保存为彩色调色板位图图像?我曾尝试在保存中添加选项(例如模式='P'、调色板=Image.WEB)但无济于事。谢谢你的帮助。
编辑:
在 PIL 文档的教程部分,它指定了转换的限制。
The library supports transformations between each supported mode and the “L” and “RGB” modes. To convert between other modes, you may have to use an intermediate image (typically an “RGB” image).
所以,为了完成我正在做的事情,我必须在第一个数组中将图像转换为 RGB,然后在第二个数组中转换回 P。
但是,图像(只有4种颜色)在从RGB转回P时出现变形,请问这是什么原因?
在这种情况下 Image.fromarray(data)
returns 灰度图像。当您将此图像转换为不同的图像模式时,它将保持灰度!
相反,您必须以调色板的形式提供颜色信息:
# first part
bmp = Image.open(fn_bmp)
bmp_P_web = bmp.convert('P', palette=Image.WEB)
web_palette = bmp_P_web.getpalette() # <---
data = np.array(bmp_P_web)
# second part
bmp = Image.fromarray(data)
bmp.putpalette(web_palette) # <---
不知道如何直接从 PIL 获取 web_palette
,但这里有一种使用 numpy 生成 it 的方法:
web_palette = np.zeros(3*256, int)
web_palette[30:-90] = np.mgrid[0:256:51, 0:256:51, 0:256:51].ravel('F')
所以我正在尝试将 bmp 转换为 NumPy 数组,将数组存储在某处,然后稍后再将其转换回 bmp 图像。
bmp = Image.open(fn_bmp)
data = np.array(bmp.convert('P', palette=Image.WEB))
这些数据暂时保存在另一个文件中,稍后我会去取回它。
bmp = Image.fromarray(np.array(dataset).convert('P', palette=Image.WEB))
bmp.save(fn)
请注意,数据集是一个转换回 NumPy 数组的对象,并且 np.array(dataset) == 所有索引中的数据。
出于某种原因,当我显示或保存此结果图像时,与某些调色板颜色对应的“14”被解释为灰度值并保存了一个这样的值。如何将图像保存为彩色调色板位图图像?我曾尝试在保存中添加选项(例如模式='P'、调色板=Image.WEB)但无济于事。谢谢你的帮助。
编辑:
在 PIL 文档的教程部分,它指定了转换的限制。
The library supports transformations between each supported mode and the “L” and “RGB” modes. To convert between other modes, you may have to use an intermediate image (typically an “RGB” image).
所以,为了完成我正在做的事情,我必须在第一个数组中将图像转换为 RGB,然后在第二个数组中转换回 P。
但是,图像(只有4种颜色)在从RGB转回P时出现变形,请问这是什么原因?
在这种情况下 Image.fromarray(data)
returns 灰度图像。当您将此图像转换为不同的图像模式时,它将保持灰度!
相反,您必须以调色板的形式提供颜色信息:
# first part
bmp = Image.open(fn_bmp)
bmp_P_web = bmp.convert('P', palette=Image.WEB)
web_palette = bmp_P_web.getpalette() # <---
data = np.array(bmp_P_web)
# second part
bmp = Image.fromarray(data)
bmp.putpalette(web_palette) # <---
不知道如何直接从 PIL 获取 web_palette
,但这里有一种使用 numpy 生成 it 的方法:
web_palette = np.zeros(3*256, int)
web_palette[30:-90] = np.mgrid[0:256:51, 0:256:51, 0:256:51].ravel('F')