如何将dtype = float的numpy NxM数组显示为纯灰度图像? [英] How to show numpy NxM array with dtype=float as plain gray scale image?
问题描述
使用dtype=float
创建numpy
数组时,使用matplotlib.pyplot.imshow
的表示方法似乎取决于这些值,因此0.50的值不仅是50%的灰度.
When creating an numpy
array with dtype=float
, the the presentation method using matplotlib.pyplot.imshow
appears to be dependent on the values, so a value of 0.50 is not just 50% gray.
使用此代码模板:
import numpy as np
import matplotlib.pyplot as plt
img = np.empty([2, 2])
img[:] = {image}
plt.imshow(img, cmap='gray')
plt.show()
然后图像[[1.0, 1.0], [0.0, 0.5]]
显示为:
但是图像[[1.0, 1.0], [1.0, 0.5]]
(仅将0.0更改为1.0)显示为:
But the image [[1.0, 1.0], [1.0, 0.5]]
, where only 0.0 is changed to 1.0, shows as:
我本来希望在两种情况下0.5(右下角)都显示为50%的灰色,但是由于某种原因,表示方法发生了变化,所以0.5的解释不同,具体取决于数组中其他元素的值.
I had expected that the 0.5 (at lower right) would show as 50% gray in both cases, but for some reason the presentation method changes, so 0.5 is interpreted differently, depending on the value of other elements in the array.
那么,如何将dtype = float的numpy NxM数组显示为纯灰度图像?
So, how to show numpy NxM array with dtype=float as plain gray scale image?
推荐答案
您必须确定色标的限制:
You have to fix the limits of the color-scale:
plt.imshow(img, cmap='gray',clim=(0,1))
要对正在发生的事情有一个很好的感觉,您可以包括一个色条,该色条可视化颜色和数值之间的转换;例如使用以下代码:
To get a good feeling of what is going on you could include a colorbar which visualizes the conversion between colors and numerical values; for example using the following code:
fig,ax = plt.subplots()
cax = plt.imshow(img, cmap='gray')
cbar = fig.colorbar(cax)
plt.show()
立即针对两个示例执行此操作,可以清楚地看到matplotlib.pyplot将色标的范围更新为数据.因此,两种情况下颜色和数值之间的转换是不同的.
Doing this for the two examples immediately makes clear that matplotlib.pyplot updates the range of the color-scale to the data. Consequently the conversion betweens colors and numerical values is different for the two cases.
这篇关于如何将dtype = float的numpy NxM数组显示为纯灰度图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!