简体   繁体   English

使用模式P将阵列转换为1通道图像

[英]Convert Array to 1-Channel Image with mode P

I'm trying to convert a numpy array with (0,10) values to a 1-channel colored image 我正在尝试将带有(0,10)值的numpy数组转换为1通道彩色图像

Example: 例:

result = [[0 0 1]
          [0 3 1]
          [1 2 2]]

to: 至:

numpy数组

I tried to use this code: 我试着使用这段代码:

cm = ListedColormap(color_map(4, True), 'pascal', 4)
plt.register_cmap(cmap=cm)
plt.imsave('outputarray.png', result, cmap='pascal')

(color_map is from: https://gist.github.com/wllhf/a4533e0adebe57e3ed06d4b50c8419ae ) (color_map来自: https//gist.github.com/wllhf/a4533e0adebe57e3ed06d4b50c8419ae

But then: 但是之后:

im = Image.open('outputarray.png')
im2 = np.array(im)
print im2.shape
print im2.min()
print im2.max()

returns: 收益:

shape: (3, 3, 4)
min: 0
max: 255

I supposed it should be: 我认为它应该是:

shape: (3, 3)
min: 0
max: 3

Thanks! 谢谢!

The shape is (3, 3, 4) since the image is a png image which has four channels, rgb and alpha. 形状为(3, 3, 4)因为图像是png图像,其具有四个通道rgb和alpha。

In order to obtain the original array shape, you can convert the image to grayscale which only has one channel. 为了获得原始阵列形状,您可以将图像转换为仅具有一个通道的灰度。

>>> im2 = im.convert("L")
>>> im2 = np.array(im2)
>>> im2
array([[  0,   0,  38],
       [  0, 113,  38],
       [ 38,  75,  75]], dtype=uint8)
>>> im2.shape
(3, 3)

And then replace the grayscale values with the smallest possible integer. 然后用尽可能小的整数替换灰度值。

>>> for i in range(3, 0, -1):
...     im2[im2==np.max(im2)] = i
>>> im2
array([[0, 0, 1],
       [0, 3, 1],
       [1, 2, 2]], dtype=uint8)
>>> im2.min
0
>>> im2.max
3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM