自制变焦显示错误区域

时间:2016-06-23 15:30:34

标签: python matplotlib

嘿所以我正在为我正在实习的项目进行缩放功能。通常情况下,我只会使用已经在绘图中提供的缩放以及matplotlib中提供的内容,但是有一种特殊的方式我们想要一次分析不能支持缩放的多个图像。我正在尝试编写一种缩放功能,该功能将采用数组并仅切片我要用imshow()显示的部分。这是我想要做的一个例子:

import matplotlib.pyplot as plt
from matplotlib.widgets import Button, Slider 
import numpy as np

arr = np.zeros([100,100])
for i in range(0,99):
    for j in range(0,99):
        if i % 2 == 0 and j % 2 == 0:
            arr[i][j] = 10
        if i % 3 == 0 and j % 3 == 0:
            arr[i][j] = -7
plt.figure(1)
axpic = plt.subplot2grid((1,1),(0,0), rowspan = 1, colspan = 1)

plt.figure(2)
ax1 = plt.subplot2grid((5,5),(0,0), rowspan = 1, colspan = 4)
ax2 = plt.subplot2grid((5,5),(1,0), rowspan = 1, colspan = 4)
ax3 = plt.subplot2grid((5,5),(2,0), rowspan = 1, colspan = 4)
ax4 = plt.subplot2grid((5,5),(3,0), rowspan = 1, colspan = 4)

axbutton = plt.subplot2grid((5,5),(4,4), rowspan = 1, colspan = 1)

s1 = Slider(ax1, 'Row Begin', 0, 99, valinit=0)
s2 = Slider(ax2, 'Row End', 0, 99, valinit=99)
s3 = Slider(ax3, 'Col Begin', 0, 99, valinit=0)
s4 = Slider(ax4, 'Col End', 0, 99, valinit=99)

zoom = Button(axbutton, 'Zoom')

def dat_view_doe(event):
    if event == 'Nothing':
        axpic.imshow(arr, cmap = 'RdBu')
    else:
        plt.figure(1)
        axpic.cla()
        axpic.imshow(arr[int(s1.val):int(s2.val)][int(s3.val):int(s4.val)], cmap = 'RdBu')
        plt.ylim(0, s2.val-s1.val)
        plt.xlim(0, s4.val-s3.val)

zoom.on_clicked(dat_view_doe)

dat_view_doe('Nothing')
plt.show()

缩放正在剪切太多行,并且不会剪切图像阵列的任何列。我不确定是否有一些语法明智,我做错了,或者是否有更深层次的问题。感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您的代码至少存在一个问题,即您在调用imshow时切换arr以及更改轴限制(并将这些限制从零设置为max-min)。我建议每次只需调整轴,使用以下代码:

import matplotlib.pyplot as plt
from matplotlib.widgets import Button, Slider 
import numpy as np

arr = np.zeros([100,100])
for i in range(0,99):
    for j in range(0,99):
        if i % 2 == 0 and j % 2 == 0:
            arr[i][j] = 10
        if i % 3 == 0 and j % 3 == 0:
            arr[i][j] = -7
plt.figure(1)
axpic = plt.subplot2grid((1,1),(0,0), rowspan = 1, colspan = 1)

plt.figure(2)
ax1 = plt.subplot2grid((5,5),(0,0), rowspan = 1, colspan = 4)
ax2 = plt.subplot2grid((5,5),(1,0), rowspan = 1, colspan = 4)
ax3 = plt.subplot2grid((5,5),(2,0), rowspan = 1, colspan = 4)
ax4 = plt.subplot2grid((5,5),(3,0), rowspan = 1, colspan = 4)

axbutton = plt.subplot2grid((5,5),(4,4), rowspan = 1, colspan = 1)

s1 = Slider(ax1, 'Row Begin', 0, 99, valinit=0)
s2 = Slider(ax2, 'Row End', 0, 99, valinit=99)
s3 = Slider(ax3, 'Col Begin', 0, 99, valinit=0)
s4 = Slider(ax4, 'Col End', 0, 99, valinit=99)

zoom = Button(axbutton, 'Zoom')

def dat_view_doe(event):
    if event == 'Nothing':
        axpic.imshow(arr, cmap = 'RdBu')
    else:
        plt.figure(1)
        plt.xlim(s1.val, s2.val)
        plt.ylim(s3.val, s4.val)
        plt.draw()

zoom.on_clicked(dat_view_doe)

dat_view_doe('Nothing')
plt.show()