Fail to allocate bitmap

Viewed 2275

I run this simple code in below to load images from a folder and after around 200 images I get this error "Fail to allocate bitmap". The problem mainly in the matplotlib.pyplot. I try to free the memory inside the loop using the 7 ways which shown in the code but unfortunately useless.

I found similar question but with no answer! I hope to receive solution for this problem.

from __future__ import division

import os
import numpy as np
import gc
from os import listdir
from os.path import isfile, join
import matplotlib.pyplot as plt
from PIL import Image


def test():
    
    entries = os.listdir(r"D:\Images")
    for entry in entries:
     if entry.endswith(".jpg"):
     
      img = np.array(Image.open(r"D:\Images\{}".format(entry)))
      fig, ax = plt.subplots(1)

      #Many ways I added to free the memory#
      plt.close('all')
      fig.clear()
      ax.clear()
      plt.clf()
      gc.collect()
      plt.close(fig)
      del img
      #####################################

UPDATE:

My Environment is Anaconda 3, OS: Windows 10

UPDATE:

I replaced this line:

fig, ax = plt.subplots(1)

With

fig, ax = plt.subplots(num=1, clear=True)

And the code became running for longer time, before I got the error after loading 185 images but now after I added "clear=true" the error appears after 369 images so this almost became the double. but the problem is still exist!

2 Answers

My guess is you never close the image file (https://pillow.readthedocs.io/en/stable/reference/Image.html). I don't even see that you plot anything this way?


with Image.open(r"D:\Images\{}".format(entry)) as im:
   img = np.array(im)

If you are still sure it is matplotlib, it would be good to see that actual error message and know what environment you are calling the above from.

I got this error while creating hundreds of plots and saving them to files. Calling the following line after each plot completely removed the above error for me:

plt.clf()

I can recommend this answer for more info.: https://stackoverflow.com/a/8228808/1935801

Related