为什么imshow的范围参数会翻转我的图像? [英] Why does imshow's extent argument flip my images?
问题描述
import matplotlib.pyplot as plt
import numpy as np
n = 16
im = np.eye(n)
fig = plt.figure()
ax = fig.add_subplot(121)
ax.imshow(im)
ax = fig.add_subplot(122)
ax.imshow(im, extent=(0, n, 0, n))
plt.show()
结果如下图
我原以为在这个 extent
中,两个数字(几乎)相同,但它们不是:注意 y 轴是如何翻转的.更令人讨厌的是,右边的数字是错误的:原点处的值显示为0,而显示为1.
I would have expected that with this extent
, both figures are (almost) identical, but they are not: note how the y-axis is flipped. What's more annoying is that the figure on the right is wrong: the value at the origin is show as 0 whereas it is one.
如果我翻转范围内的 y 参数,extent=(0, n, n, 0)
,我会得到预期的行为.
If I flip the y argument in the extent, extent=(0, n, n, 0)
, I get the expected behavior.
As I understand it, the description of the extent
argument of imshow
,
范围:标量(左,右,底部,顶部),可选,默认值:无
extent : scalars (left, right, bottom, top), optional, default:
None
左下角和右上角的位置,以数据坐标表示.如果 None
,则图像的位置使得像素中心落在从零开始的(行、列)索引上.
The location, in data-coordinates, of the lower-left and upper-right corners. If None
, the image is positioned such that the pixel centers fall on zero-based (row, column) indices.
对这种行为并不十分明确.
is not really explicit about that behavior.
我的问题是,为什么会发生这种翻转,为什么我们必须在一定程度上反转顶部/底部才能获得预期的行为?
My question is, why does this flip happen, why do we have to invert top/bottom in the extent to get the expected behavior?
编辑
我已阅读此问题,OP确实没有提及翻转的问题,答案也没有带来问题.
I have read this question, the OP does not mention a flipping issue and the answer does not bring the issue either.
设置 origin ='lower'
元素的确会将第一个图像像素带到(0,0)
,但是该图像随后上下颠倒显示.
Setting origin='lower'
element does bring the first image pixel at (0,0)
but the image is then displayed upside down.
我确信有一个简单的解释可以一致地解释这些行为,但目前还不能确定.
I am sure there is a simple explanation to explain these behaviors consistently but quite can't pin it yet.
推荐答案
imshow
有一个参数 origin
.默认值为 origin ="upper"
.这与 extent
的设置相冲突,根据文档,该设置应设置在数据坐标中,左下角和右上角的位置".但是,只有在设置了 origin ="lower"
的情况下,这才是正确的.
The imshow
has an argument origin
. The default is origin="upper"
. This conflicts with the setting of the extent
, which, according to the documentation, should set the "location, in data-coordinates, of the lower-left and upper-right corners." This, however is only true if origin = "lower"
is set.
我已经提议用一句话扩展文档喜欢
I have already proposed to extend the documentation with a sentence like
如果将原点设置为上",则可以反转使用范围和/或ylim指定的任何y坐标."
"If you set origin to "upper" any y coordinates you may specify using extent and/or ylim need to be reversed."
这正是您已经发现自己的情况.因此,选项为:
This is exactly what you already found out yourself. So options are:
如果您希望图像位于左上角:
If you want the image to origin in the upper left corner:
origin="upper", extent=(0, n, n, 0)
如果您希望图像起源于左下角:
If you want the image to origin in the lower left corner:
origin="lower", extent=(0, n, 0, n)
这篇关于为什么imshow的范围参数会翻转我的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!