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?

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

4 Comments

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?
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.
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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.