Lucidnonsense
Lucidnonsense

Reputation: 1243

how to make matplotlib draw sequence of images in same window

I'm trying to draw a sequence of images from earlier saved plots in the same window

for cumul, name in enumerate(name_list):
        if im is None:
            im = plt.imread(directory+name+'.png')
            fig = plt.figure()
            ax = fig.add_subplot(111)
            img = ax.imshow(im)
        else:
            img.set_data(im)
        plt.draw()
        accept = raw_input('OK? ')

But the images won't appear!

Upvotes: 3

Views: 5758

Answers (2)

Bily
Bily

Reputation: 801

I have implemented a handy script based on matplotlib that just suits your need and more. Try it out here

For your example,

def redraw_fn(f, axes):
    name = name_list[f]
    img = plt.imread(directory+name+'.png')
    if not redraw_fn.initialized:
        redraw_fn.im = axes.imshow(img, animated=True)
        redraw_fn.initialized = True
    else:
        redraw_fn.im.set_array(img)
    accept = raw_input('OK? ')

redraw_fn.initialized = False

videofig(len(name_list), redraw_fn, play_fps=30)

Upvotes: 0

Velimir Mlaker
Velimir Mlaker

Reputation: 10975

You're almost there! All ya gotta do is restructure your code a little bit. And be sure to add plt.ion() to enable interactive drawing.

Here's code that pulls all images from a specific directory and displays them in slideshow style:

import os
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
plt.ion()
plt.show()

dir = 'path/to/pics'

for fname in os.listdir(dir):
    fname = os.path.join(dir, fname)
    im = plt.imread(fname)
    img = ax.imshow(im)
    plt.draw()
    accept = raw_input('OK? ')

And here's the same structure, applied to your original code.

fig = plt.figure()
ax = fig.add_subplot(111)
plt.ion()
plt.show()

for cumul, name in enumerate(name_list):
    if im is None:
        im = plt.imread(directory+name+'.png')

        # Already done this above.
        #fig = plt.figure()
        #ax = fig.add_subplot(111)

        img = ax.imshow(im)
    else:
        img.set_data(im)
    plt.draw()
    accept = raw_input('OK? ')
    im = None

Upvotes: 2

Related Questions