从图像的numpy数组中将颜色通道的值更改为特定值

mkh04yzy  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(129)

我想将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]]


我该怎么做?先谢谢你。

qqrboqgw

qqrboqgw1#

np.apply_along_axis()axis=2一起使用可以实现您想要的功能。

import numpy as np
from PIL import Image

I = np.asarray(Image.open('Image.png'))

# define the mapping
mapping = np.array([[255, 255, 255],
                    [87, 136, 54],
                    [70, 105, 41]])

# define conversion function
def convert(pix, cmap):
    return np.argmax((pix == cmap).all(axis=1))

# apply convert function along axis=2
I = np.apply_along_axis(convert, 2, I, mapping)

字符串
注意,convert()函数假设I数组中的每一种可能的颜色都在mapping数组中定义。如果不是这样,则需要修改函数,例如,将未知颜色替换为固定索引值。

相关问题