为什么 imshow 不能正确显示一个全为 1 的矩阵?

Why can't imshow show a matrix full of ones properly?

这是一个简单的可重现代码:

import numpy as np
import matplotlib.pyplot as plt

plt.figure()
img = np.ones((3,3))
plt.imshow(img)
plt.figure()
plt.imshow(np.array([1,1,1,1,0,1,1,1,1]).reshape(3,3))

它会给你如下图:

即使你使用

plt.imshow(img.astype(float)) or
plt.imshow(img*255)

还是那张图

我只需要 Matplotlib 将第一张图像作为黄色图像给我,就像第二张图像一样。

明确使用imshowvminvmax参数:

When using scalar data and no explicit norm, vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the supplied data. vmin, vmax are ignored if the norm parameter is used.

import numpy as np
import matplotlib.pyplot as plt

plt.figure()
img = np.ones((3, 3))
plt.imshow(img, vmin=0, vmax=1)
plt.figure()
plt.imshow(np.array([1, 1, 1, 1, 0, 1, 1, 1, 1]).reshape(3, 3))
plt.show()

对于第二个示例,数据范围是 [0 ... 1],因此默认情况下会根据该范围缩放颜色。但是,对于第一个示例,无法从数据本身(全部)中提取所需的 [0 ... 1] 数据范围,因此您必须明确提供该信息。

希望对您有所帮助!

----------------------------------------
System information
----------------------------------------
Platform:    Windows-10-10.0.16299-SP0
Python:      3.8.1
Matplotlib:  3.2.0rc3
NumPy:       1.18.1
----------------------------------------