3

I'd like to know the correct way to release memory after a plot is done since I'm getting a RuntimeError: Could not allocate memory for image error when plotting multiple images in a loop.

Currently I have the following commands in another code to supposedly do just that:

import matplotlib.pyplot as plt

# The code
.....

# Make plot
fig = plt.figure()
# Plotting stuff.
plt.imshow(...)
plt.plot(...)
plt.scatter(...)

# Save plot to file.
plt.savefig(...)

# Release memory.
plt.clf()
plt.close()

A comment in this answer states that the correct syntax is actually plt.close(fig) but the highest voted answer given here says that plt.clf() is enough and doesn't mention .close.

The questions are: what is(are) the correct command(s) to release memory after the plot is saved to file? Do I need both .clf and .close or is one of them enough?

Community
  • 1
  • 1
Gabriel
  • 40,504
  • 73
  • 230
  • 404

1 Answers1

2

I would like to suggest for you an alternate approach. Note that imshow returns a handle for you. Grab a reference on this, and use the set_data method on that object for subsequent iterations.

>>> h = plt.imshow(np.zeros([480, 640]))
>>> h
<matplotlib.image.AxesImage at 0x47a03d0>
>>> for img in my_imgs:
...     h.set_data(img)  #etc
wim
  • 338,267
  • 99
  • 616
  • 750
  • Would you mind expanding your answer a bit? What if I don't use `imshow` in my plots? What does the `set_data` call do? – Gabriel Feb 03 '14 at 14:34
  • You haven't shown how you plot your images, so `plt.imshow` was just an educated guess. `set_data` will update the `AxesImage` object in this case, with new data, rather than creating a new image object which seems to be giving you memory problems. – wim Feb 03 '14 at 14:36
  • Thanks @wim. I do make use of `imshow` occasionally but not exclusively. I also use `plt.plot()` and `plt.scatter()`, so I'm not sure how this could be applied to those cases, I'll update the question to make this more clear. – Gabriel Feb 03 '14 at 14:38
  • The same goes for each of those cases, you should keep the references returned by `plot` and `scatter` as well, and they will also have `set_data` method which you can use when iterating. – wim Feb 03 '14 at 14:42