Customize image sequence with matplotlib Python

I am implementing kmeans clustering algorithm in Python. I would like to build at each iteration the status (image) of cluster quality. So basically I have a loop that draws an image at each iteration, and I want to animate it. I don’t know if I did it clearly. For now, I'm just using the show () command, which draws an image, but then I have to close it to continue the iteration.

So, is there a way to animate a sequence of images calculated at each step?

+4
source share
4 answers

I tried the ion() method and it works great for a small amount of data, but if you have large images or image streams in relatively fast, this method is terribly slow. As far as I understand, ion() will redraw everything every time you change your shape, including axes and labels, etc. Perhaps this is not the way you want.

This thread shows a much better way to do things.

Here is a simple example that I did showing how to do this:

 import time import numpy import matplotlib.pyplot as plt fig = plt.figure( 1 ) ax = fig.add_subplot( 111 ) ax.set_title("My Title") im = ax.imshow( numpy.zeros( ( 256, 256, 3 ) ) ) # Blank starting image fig.show() im.axes.figure.canvas.draw() tstart = time.time() for a in xrange( 100 ): data = numpy.random.random( ( 256, 256, 3 ) ) # Random image to display ax.set_title( str( a ) ) im.set_data( data ) im.axes.figure.canvas.draw() print ( 'FPS:', 100 / ( time.time() - tstart ) ) 

I get about 30 FPS on my machine with the above code. When I run the same with plt.ion() and ax.imshow( data ) instead of im.axes.figure.canvas.draw() and im.set_data( data ) , I get about 1 FPS

+4
source

Use pause() . For a set of images stored in video[t, x, y] , this makes a simple animation:

 import matplotlib.pyplot as plt for i in range(video.shape[0]): plt.imshow(video[i,:,:]) plt.pause(0.5) 
+1
source

Just enable interactive mode:

 ion() show() 

And it will work. It's a bit strange. But remember: at the end of the python script, it will close the windows. You have to call

 ion() show() 

at the end of the script, if you do not want the windows to close.

0
source

I have implemented an image sequence visualization utility that may be useful. Try here

The following is an example that draws a dynamic sine wave.

 import numpy as np def redraw_fn(f, axes): amp = float(f) / 3000 f0 = 3 t = np.arange(0.0, 1.0, 0.001) s = amp * np.sin(2 * np.pi * f0 * t) if not redraw_fn.initialized: redraw_fn.l, = axes.plot(t, s, lw=2, color='red') redraw_fn.initialized = True else: redraw_fn.l.set_ydata(s) redraw_fn.initialized = False num_time_steps = 100 videofig(num_time_steps, redraw_fn) 
0
source

Source: https://habr.com/ru/post/1403522/


All Articles