I'm trying to use matplotlib.pyplot to view a video as I process the frames. The code below displays a plot window, but the images are never drawn.
import cv2
import matplotlib.pyplot as plt
class Viewer:
def __init__(self, video_filename):
self.cap = cv2.VideoCapture(video_filename)
self.ax1 = plt.subplot(1, 2, 1)
self.ax2 = plt.subplot(1, 2, 2)
# Grab the first frame.
frame = self.grabframe()
self.im1 = self.ax1.imshow(frame)
self.im2 = self.ax2.imshow(frame)
def grabframe(self):
ret, frame = self.cap.read()
if ret:
return frame
else:
print('[ERROR] grabframe failed')
return self.grabframe()
def update(self, frame):
"""Update the display."""
print('[INFO] updating...')
self.im1.set_data(frame)
self.im2.set_data(frame)
plt.draw()
def main():
"""Run it."""
cli = argparse.ArgumentParser()
cli.add_argument('-i', '--input', type=str, required=True)
args = cli.parse_args()
viewer = Viewer(args.input)
while True:
viewer.update(viewer.grabframe())
if __name__ == '__main__':
plt.ion()
plt.show()
main()
The update function is definitely being called and I am sure that the frames contain image data. I tried explicitly creating a figure and adding the axis to that. I also tried fig.canvas.draw
. Also I've experimented with calling plt.show()
in the main function. Nothing changed in any of those cases.
Why aren't the images drawn on the plot like I expect?