我想绘制一个形状为[高度x宽度x3]的numpy数组,其中包含RGB值。举个简单的例子,假设你有比利时国旗:
import numpy as np
import matplotlib.pyplot as plt
flag = np.empty((1,3,3))
flag[0,0,:] = (0,0,0)
flag[0,1,:] = (254,240,71)
flag[0,2,:] = (255,55,14)
plt.imshow(flag)
plt.show()
这将导致以下输出:
![enter image description here](https://istack.dev59.com/76xjX.webp)
我想绘制一个形状为[高度x宽度x3]的numpy数组,其中包含RGB值。举个简单的例子,假设你有比利时国旗:
import numpy as np
import matplotlib.pyplot as plt
flag = np.empty((1,3,3))
flag[0,0,:] = (0,0,0)
flag[0,1,:] = (254,240,71)
flag[0,2,:] = (255,55,14)
plt.imshow(flag)
plt.show()
numpy.empty
创建的数组的默认数据类型是浮点型,imshow
对待浮点值与整数值不同。(imshow
期望浮点值在0.0到1.0的范围内。)flag = np.empty((1,3,3))
为了
flag = np.empty((1,3,3), dtype=np.uint8)
当 flag
是浮点数时,你得到这些特定颜色的原因是 imshow
显然将你的数组转换为整数,而没有检查输入值是否在 0.0 到 1.0 的范围内。在这种情况下会发生以下情况:
In [25]: flag
Out[25]:
array([[[ 0., 0., 0.],
[ 254., 240., 71.],
[ 255., 55., 14.]]])
In [26]: img = (flag*255).astype(np.uint8)
In [27]: img
Out[27]:
array([[[ 0, 0, 0],
[ 2, 16, 185],
[ 1, 201, 242]]], dtype=uint8)
如果您运行imshow(img)
,您将得到黑色、蓝色和青色的图表。
flag[0,0,:] = (0,0,0)
flag[0,1,:] = (254/255,240/255,71/255)
flag[0,2,:] = (255/255,55/255,14/255)
imshow
中使用整数值,请通过plt.imshow(flag.astype(np.uint8))
将您的数组转换为无符号整数。 - ImportanceOfBeingErnest