Matplotlib imshow() 不显示 numpy.ones 数组
Matplotlib imshow() doesn't display numpy.ones array
所以这看起来像是一个错误,但它可能是预期的行为。
我的代码如下:
import matplotlib.pyplot as pyplot
import numpy as np
array = np.ones([10, 10])
# array[0, 0] = 0
fig, ax = pyplot.subplots(figsize=(10, 5))
ax.imshow(array, cmap=pyplot.cm.binary)
pyplot.show()
结果是一张白色图像,而不是预期的黑色图像:
这种行为的奇怪之处在于,取消注释一行似乎改变了一个像素 "fixes" 问题:
我找到的最接近的解释 online 是:
[...] The issue is that when initialising the image with a uniform array, the minimum and maximum of the colormap are identical. As we are only changing the data, not the colormap, all images are shown as being of uniform colour.
考虑到这个解释,我该如何解决这个问题?
您可以通过使用显式颜色而不是颜色映射来回避这个问题:
array = np.zeros((10, 10, 3), 'u1')
#array[0, 0, :] = 255
fig, ax = pyplot.subplots(figsize=(10, 5))
ax.imshow(array)
pyplot.show()
这样,零表示黑色,(255,255,255) 表示白色(RGB)。
如果 imshow
的 the vmin
and vmax
parameters 未指定,imshow
将它们设置为
vmin = array.min() # in this case, vmin=1
vmax = array.max() # in this case, vmax=1
然后 normalizes array
值介于 0 和 1 之间,默认使用 matplotlib.colors.Normalize
。
In [99]: norm = mcolors.Normalize(vmin=1, vmax=1)
In [100]: norm(1)
Out[100]: 0.0
因此 array
中的每个点都映射到与 0.0 关联的颜色:
In [101]: plt.cm.binary(0)
Out[101]: (1.0, 1.0, 1.0, 1.0) # white
通常 array
会包含各种值,而 matplotlib 的规范化会自动为您 "do the right thing"。但是,在 array
仅包含一个值的这些极端情况下,您可能需要明确设置 vmin
和 vmax
:
import matplotlib.pyplot as pyplot
import numpy as np
array = np.ones([10, 10])
fig, ax = pyplot.subplots(figsize=(10, 5))
ax.imshow(array, cmap=pyplot.cm.binary, vmin=0, vmax=1)
pyplot.show()
所以这看起来像是一个错误,但它可能是预期的行为。
我的代码如下:
import matplotlib.pyplot as pyplot
import numpy as np
array = np.ones([10, 10])
# array[0, 0] = 0
fig, ax = pyplot.subplots(figsize=(10, 5))
ax.imshow(array, cmap=pyplot.cm.binary)
pyplot.show()
结果是一张白色图像,而不是预期的黑色图像:
这种行为的奇怪之处在于,取消注释一行似乎改变了一个像素 "fixes" 问题:
我找到的最接近的解释 online 是:
[...] The issue is that when initialising the image with a uniform array, the minimum and maximum of the colormap are identical. As we are only changing the data, not the colormap, all images are shown as being of uniform colour.
考虑到这个解释,我该如何解决这个问题?
您可以通过使用显式颜色而不是颜色映射来回避这个问题:
array = np.zeros((10, 10, 3), 'u1')
#array[0, 0, :] = 255
fig, ax = pyplot.subplots(figsize=(10, 5))
ax.imshow(array)
pyplot.show()
这样,零表示黑色,(255,255,255) 表示白色(RGB)。
如果 imshow
的 the vmin
and vmax
parameters 未指定,imshow
将它们设置为
vmin = array.min() # in this case, vmin=1
vmax = array.max() # in this case, vmax=1
然后 normalizes array
值介于 0 和 1 之间,默认使用 matplotlib.colors.Normalize
。
In [99]: norm = mcolors.Normalize(vmin=1, vmax=1)
In [100]: norm(1)
Out[100]: 0.0
因此 array
中的每个点都映射到与 0.0 关联的颜色:
In [101]: plt.cm.binary(0)
Out[101]: (1.0, 1.0, 1.0, 1.0) # white
通常 array
会包含各种值,而 matplotlib 的规范化会自动为您 "do the right thing"。但是,在 array
仅包含一个值的这些极端情况下,您可能需要明确设置 vmin
和 vmax
:
import matplotlib.pyplot as pyplot
import numpy as np
array = np.ones([10, 10])
fig, ax = pyplot.subplots(figsize=(10, 5))
ax.imshow(array, cmap=pyplot.cm.binary, vmin=0, vmax=1)
pyplot.show()