【问题标题】:Why "matplotlib.pyplot.imshow" returns shapes with a frame around them?为什么“matplotlib.pyplot.imshow”会返回带有框架的形状?
【发布时间】:2020-10-11 15:29:22
【问题描述】:

我的问题很简单:为什么我在下面编写的两段代码会给出两个略有不同的输出?

更具体地说,第一个使用形状为 (1000, 1000) 的 numpy.ndarray 填充“1.0”np.float64 值,除了我想要填充“正方形”的区域之外“0.45” np.float64 值。当我在轴上调用 plt.imshow 方法时,使用颜色图“nipy_spectral”,它返回一个正方形,但周围有一个奇怪的框架......

见下面的代码和最后的左图:

#Code1:
foreground = np.ones((1000, 1000))
foreground = foreground.astype(np.float64)

def drawSquare(centerYX : tuple = (0, 0), radius : int = 1):
    squareCoordinates = np.meshgrid([y for y in range(centerYX[0]-radius, centerYX[0]+radius+1, 1)],
                                    [x for x in range(centerYX[1]-radius, centerYX[1]+radius+1, 1)])
    return squareCoordinates

square1 = drawSquare((round(foreground.shape[0]/2), round(foreground.shape[1]/2)), 200)
foreground[square1[0], square1[1]] = 0.45

fig, ax = plt.subplots(1)
ax.imshow(foreground, cmap = "nipy_spectral", vmin = 0.0, vmax = 1.0, , interpolation = None)
plt.show();

在第二段代码中,我使用了一个形状为 (1000, 1000, 4) 的 numpy.ndarray,我用与“nipy_spectral”颜色图(我的背景)的最后一种颜色对应的 RGBA 序列填充它,除了正方形区域,我用参数“0.45”调用“nipy_spectral”颜色图获得的 RGBA 序列填充。

在这种情况下,我已经有一个 RGBA 图像/数组,不需要通过 Axes.imshow 方法的“cmap”参数进行任何转换。在这种情况下,输出是预期的:一个没有任何奇怪框架的正方形

见下方代码及最后右图:

#Code2:
foreground = np.zeros((1000, 1000, 4))
foreground[:, :] = [0.8, 0.8, 0.8, 1.0]
foreground = foreground.astype(np.float64)

def drawSquare(centerYX : tuple = (0, 0), radius : int = 1):
    squareCoordinates = np.meshgrid([y for y in range(centerYX[0]-radius, centerYX[0]+radius+1, 1)],
                                    [x for x in range(centerYX[1]-radius, centerYX[1]+radius+1, 1)])
    return squareCoordinates

square1 = drawSquare((round(foreground.shape[0]/2), round(foreground.shape[1]/2)), 200)

nipy_spectral_cm = matplotlib.cm.get_cmap("nipy_spectral")
foreground[square1[0], square1[1]] = nipy_spectral_cm(0.45)

fig, ax = plt.subplots(1)
ax.imshow(foreground)
plt.show();

为什么第一段代码 (Code1) 给出了一个带有奇怪框架的正方形?

【问题讨论】:

  • 对不起...当我在底部插入图像时,我没有意识到“[![在此处输入图像描述][1]][1]”行被插入到中间代码。请忽略该行...对不起!
  • 没问题,您可以随时编辑您的问题并删除此行(我已经为您完成了)。

标签: python-3.x image matplotlib colormap rgba


【解决方案1】:

帧是由于插值。它也出现在第二个代码中(只需放大图像即可看到),但不太明显,因为它的颜色更接近绿色方块的颜色:

代码 2 --> 内插为蓝绿色:

foreground[299:301,299:301,0]
#array([[0.8, 0.8],
#       [0.8, 0. ]])

foreground[299:301,299:301,1]
#array([[0.8       , 0.8       ],
#       [0.8       , 0.60261373]])

foreground[299:301,299:301,2]
#array([[0.8, 0.8],
#       [0.8, 0. ]])

代码 1 --> 内插为黄色:

foreground[299:301,299:301]
#array([[1.  , 1.  ],
#       [1.  , 0.45]])

使用interpolate='none' 关闭插值并获得清晰的切角。您使用了None 而不是'none'None 为默认值,预设为'antialiased',详见here

【讨论】:

  • 非常感谢您的明确回答,我认为这可能与 Axes.imshow 执行的插值有关...但我没有注意到 None 和“none”不对应对同一件事!这将使我正在开发的代码更简单!我还将看看 Antialiasing 以更好地理解我看到的这种效果。非常感谢!!
猜你喜欢
  • 1970-01-01
  • 2021-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-22
相关资源
最近更新 更多