ach*_*nnu 5 image matplotlib rotation reshape
我有一个 3D 数组,其中前两个维度是空间的,比如 (x,y)。第三维包含点特定的信息。
print H.shape # --> (200, 480, 640) spatial extents (200,480)
Run Code Online (Sandbox Code Playgroud)
现在,通过在第三维中选择某个平面,我可以显示一个图像
imdat = H[:,:,100] # shape (200, 480)
img = ax.imshow(imdat, cmap='jet',vmin=imdat.min(),vmax=imdat.max(), animated=True, aspect='equal')
Run Code Online (Sandbox Code Playgroud)
我现在想旋转立方体,以便从 (x,y) 切换到 (y,x)。
H = np.rot90(H) # could also use H.swapaxes(0,1) or H.transpose((1,0,2))
print H.shape # --> (480, 200, 640)
Run Code Online (Sandbox Code Playgroud)
现在,当我打电话时:
imdat = H[:,:,100] # shape (480,200)
img.set_data(imdat)
ax.relim()
ax.autoscale_view(tight=True)
Run Code Online (Sandbox Code Playgroud)
我得到奇怪的行为。沿行的图像将数据显示到第 200 行,然后在 y 轴 (480) 的末尾处为黑色。x 轴从 0 延伸到 200,并显示旋转后的数据。现在,再旋转 90 度,图像显示正确(当然只是旋转 180 度)
在我看来,旋转数据后,轴限制(或图像范围?)或某些内容无法正确刷新。有人可以帮忙吗?
PS:为了沉迷于糟糕的黑客攻击,我还尝试在每次旋转后重新生成一个新图像(通过调用 ax.imshow),但我仍然得到相同的行为。
下面我将包含您的问题的解决方案。该方法resetExtent使用数据和图像将范围显式设置为所需值。希望我正确地模拟了预期的结果。
import matplotlib.pyplot as plt
import numpy as np
def resetExtent(data,im):
"""
Using the data and axes from an AxesImage, im, force the extent and
axis values to match shape of data.
"""
ax = im.get_axes()
dataShape = data.shape
if im.origin == 'upper':
im.set_extent((-0.5,dataShape[0]-.5,dataShape[1]-.5,-.5))
ax.set_xlim((-0.5,dataShape[0]-.5))
ax.set_ylim((dataShape[1]-.5,-.5))
else:
im.set_extent((-0.5,dataShape[0]-.5,-.5,dataShape[1]-.5))
ax.set_xlim((-0.5,dataShape[0]-.5))
ax.set_ylim((-.5,dataShape[1]-.5))
def main():
fig = plt.gcf()
ax = fig.gca()
H = np.zeros((200,480,10))
# make distinguishing corner of data
H[100:,...] = 1
H[100:,240:,:] = 2
imdat = H[:,:,5]
datShape = imdat.shape
im = ax.imshow(imdat,cmap='jet',vmin=imdat.min(),
vmax=imdat.max(),animated=True,
aspect='equal',
# origin='lower'
)
resetExtent(imdat,im)
fig.savefig("img1.png")
H = np.rot90(H)
imdat = H[:,:,0]
im.set_data(imdat)
resetExtent(imdat,im)
fig.savefig("img2.png")
if __name__ == '__main__':
main()
Run Code Online (Sandbox Code Playgroud)
此脚本生成两个图像: 第一个未旋转:
然后旋转:

我认为只要明确调用set_extent就可以完成所有resetExtent操作,因为如果 'autoscle' 为 True,它应该调整轴限制。但出于某种未知的原因,set_extent单独打电话是行不通的。
| 归档时间: |
|
| 查看次数: |
7076 次 |
| 最近记录: |