1""" 2=================== 3Image Slices Viewer 4=================== 5 6Scroll through 2D image slices of a 3D array. 7""" 8 9import numpy as np 10import matplotlib.pyplot as plt 11 12 13# Fixing random state for reproducibility 14np.random.seed(19680801) 15 16 17class IndexTracker: 18 def __init__(self, ax, X): 19 self.ax = ax 20 ax.set_title('use scroll wheel to navigate images') 21 22 self.X = X 23 rows, cols, self.slices = X.shape 24 self.ind = self.slices//2 25 26 self.im = ax.imshow(self.X[:, :, self.ind]) 27 self.update() 28 29 def on_scroll(self, event): 30 print("%s %s" % (event.button, event.step)) 31 if event.button == 'up': 32 self.ind = (self.ind + 1) % self.slices 33 else: 34 self.ind = (self.ind - 1) % self.slices 35 self.update() 36 37 def update(self): 38 self.im.set_data(self.X[:, :, self.ind]) 39 self.ax.set_ylabel('slice %s' % self.ind) 40 self.im.axes.figure.canvas.draw() 41 42 43fig, ax = plt.subplots(1, 1) 44 45X = np.random.rand(20, 20, 40) 46 47tracker = IndexTracker(ax, X) 48 49 50fig.canvas.mpl_connect('scroll_event', tracker.on_scroll) 51plt.show() 52