2

i have this code for creating a series of image from a series of matrixes, and in each image i want to add a specific text. this is my typical code :

ax = axes([0,0,1,1])

for i in range(0,5):
    text(1,1,str(i))
    ax.imshow(a[:,:,i],origin='lower')
    savefig(str("%04d" % int(i))+'.png',format="png")
    del ax.texts[-1] 

but the problem is that as the number of iteration increases, the speed decease and it becomes so so slow. It seems that there is something wrong with opening a lot of windows in background.

Any suggestion?

Blender
  • 275,078
  • 51
  • 420
  • 480
Mojtaba
  • 249
  • 5
  • 14

2 Answers2

0

Instead of creating a new image and text objects every loop reuse the objects.

ax = axes([0,0,1,1])
t = text(1,1,str(0))
img = ax.imshow(a[:,:,0],origin='lower')

for i in range(0,5):
    t.set_text(str(i)
    img.set_data(a[:,:,i])
    savefig(str("%04d" % int(i))+'.png',format="png")

also see

Visualization of 3D-numpy-array frame by frame

Community
  • 1
  • 1
tacaswell
  • 79,602
  • 19
  • 200
  • 189
  • Thanx for the answer! i simply add close(gcf()) and it works. i also tried yours, the speed is the same. but for your case, we have to define a new figure object to works. – Mojtaba Aug 08 '12 at 15:37
  • If this solved your problem please accept it, if you used a different solution, please post what you used and accept your own answer. – tacaswell Aug 18 '13 at 19:37
0

I just added this single line at the end of the loop and it works fine now. It was simply the problem of accumulating previuosly opened figures in the memory.

ax = axes([0,0,1,1])

for i in range(0,5):
    text(1,1,str(i))
    ax.imshow(a[:,:,i],origin='lower')
    savefig(str("%04d" % int(i))+'.png',format="png")
    del ax.texts[-1] 
    close(gcf())
Mojtaba
  • 249
  • 5
  • 14