以图像形式查看 NumPy 数组

Viewing a NumPy array as an image

我生成了一个 2D NumPy 数组,它创建的多边形周长如下所示:

0 0 0 0  0    0   0   0   0 0 0
0 0 0 0 256  256 256 256  0 0 0
0 0 0 0 256   0   0  256  0 0 0 
0 0 0 0 256   0   0  256  0 0 0 
0 0 0 0 256   0   0  256  0 0 0 
0 0 0 0 256   0   0  256  0 0 0 
0 0 0 0 256  256 256 256  0 0 0
0 0 0 0  0    0   0   0   0 0 0

当我使用:

img = Image.fromarray(array, 'L') # from PIL library
img.save('test'.png)

我希望打开图像并看到黑色背景中的白色矩形轮廓,但我却得到了奇怪的伪随机线条。我尝试用 1 替换所有的零,这只是将图像更改为 3 条垂直直线。

对我做错了什么有什么想法吗?

幸运的是 matplotlib 有一个名为 matshow 的特殊函数完全适合您的用例。

import numpy as np
import matplotlib.pyplot as plt

arr = np.array([[  0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0],
       [  0,   0,   0,   0, 256, 256, 256, 256,   0,   0,   0],
       [  0,   0,   0,   0, 256,   0,   0, 256,   0,   0,   0],
       [  0,   0,   0,   0, 256,   0,   0, 256,   0,   0,   0],
       [  0,   0,   0,   0, 256,   0,   0, 256,   0,   0,   0],
       [  0,   0,   0,   0, 256,   0,   0, 256,   0,   0,   0],
       [  0,   0,   0,   0, 256, 256, 256, 256,   0,   0,   0],
       [  0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0]])

plt.matshow(arr, cmap='gray')

您的问题是 uint8(在本例中与 PIL 一起使用的)最大为 255(不是 256)。此代码产生正确的结果:

from PIL import Image
import matplotlib.pyplot as plt
import numpy as np

im_arr = np.array(
[[0, 0, 0, 0,  0 ,   0 ,  0 ,  0 ,  0, 0 ,0],
[0, 0, 0, 0, 255,  255, 255, 255,  0, 0 ,0],
[0, 0, 0, 0, 255,   0 ,  0 , 255,  0, 0 ,0],
[0, 0, 0, 0, 255,   0 ,  0 , 255,  0, 0 ,0],
[0, 0, 0, 0, 255,   0 ,  0 , 255,  0, 0 ,0],
[0, 0, 0, 0, 255,   0 ,  0 , 255,  0, 0 ,0],
[0, 0, 0, 0, 255,  255, 255, 255,  0, 0 ,0],
[0, 0, 0, 0,  0 ,   0 ,  0 ,  0 ,  0, 0 ,0]])


im = Image.fromarray(np.uint8(im_arr))
plt.imshow(im)
plt.show()

编辑

嗨@AdamBrooks,numpy 根据列表的对象类型推断作为输入给出的列表。例如:

>>> import numpy as np 
>>> a=np.array([1,2,3]) 
>>> a 
array([1, 2, 3]) 
>>> a.dtype 
dtype('int64') 
>>> b=np.array([1,2,3.5]) 
>>> b.dtype 
dtype('float64') 

如果你想在你的案例中将它们用作图像,你需要将输入类型转换为 np.uint8。