我想将PNG图像(3通道[RGB])转换为numpy数组。如果颜色通道值为[255 255 255],则数组值应为0。如果颜色通道值为[87 136 54],则数组值应为1。如果颜色通道值为[70 105 41],则数组值应为2。
这是我将PNG转换为numpy数组的代码:
import numpy as np
from PIL import Image
I = np.asarray(Image.open('Image.png'))
print(I)
字符串
输出量:
[[[255 255 255] [87 136 54] [87 136 54] ... [255 255 255] [70 105 41] [255 255 255]]
[[255 255 255] [255 255 255] [87 136 54] ... [87 136 54] [87 136 54] [255 255 255]]
[[255 255 255] [87 136 54] [255 255 255] ... [255 255 255] [255 255 255] [255 255 255]]
...
[[70 105 41] [70 105 41] [255 255 255] ... [70 105 41] [87 136 54] [255 255 255]]
[[87 136 54] [87 136 54] [255 255 255] ... [87 136 54] [70 105 41] [255 255 255]]
[[255 255 255] [255 255 255] [255 255 255] ... [255 255 255] [255 255 255] [255 255 255]]]
型
我的预期输出:
[[0 1 1 ... 0 2 0]
[0 0 1 ... 1 1 0]
[0 1 0 ... 0 0 0]
...
[2 2 0 ... 2 1 0]
[1 1 0 ... 1 2 0]
[0 0 0 ... 0 0 0]]
型
我该怎么做?先谢谢你。
1条答案
按热度按时间qqrboqgw1#
将
np.apply_along_axis()
与axis=2
一起使用可以实现您想要的功能。字符串
注意,
convert()
函数假设I
数组中的每一种可能的颜色都在mapping
数组中定义。如果不是这样,则需要修改函数,例如,将未知颜色替换为固定索引值。