[Python] Fail to allocate bitmap

Discussão em 'Python' iniciado por Stack, Julho 13, 2025.

  1. Stack

    Stack Membro Participativo

    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!

    Continue reading...

Compartilhe esta Página