'matplotlib "fail to allocate bitmap" after some iterations

I can't find a solution to avoid this crash.

I have cleaned up the attached code because it contains the issue and nothing else.

Regardless of the size of the image, the program crashes after 368 iterations.

I also tried what I could find in the forums but no solution found ( plt.close('all'), gc. collect().... ).

import matplotlib.pyplot as plt
import cv2


compteur = 0
image = cv2.imread(r"D:\OneDrive\Bureau\New folder\12345.jpg")


while True:

    print('1')
    ax_user = plt.imshow(image)

    print('2')
    plt.close('all')

    print (f'\n{compteur}:\t')
    compteur += 1 



367:
1
2

368:
1
Fail to allocate bitmap


Solution 1:[1]

According to this post, this is an issue with the TkAgg backend.

I was able to get it to work using:

reload(matplotlib)
matplotlib.use('Agg')

I'll have to beat on it some more to see if this is robust.

I saw the error message in this code:

http://search.cpan.org/src/NI-S/Tk-804.027/pTk/mTk/win/tkWinDraw.c

if(!bitmap) {
    panic("Fail to allocate bitmap\n");
    DeleteDC(dcMem);
TkWinReleaseDrawableDC(d, dc, &state);
    return;
}

It is unclear to me why the bitmap from that C source code is null, but I've noticed that the Python memory usage keeps increasing with subsequent calls to create another plot/image/figure, regardless of whether one uses plt.close('all'), plt.clf(), gc.collect(), etc, so its failure to be created may have something to do with that. I don't notice the same behaviour with, for example, the Agg backend.

One can read more about backend options in the docs, or checking the documentation for matplotlib.use():

use(backend, *, force=True)
    Select the backend used for rendering and GUI integration.
    
    Parameters
    ----------
    backend : str
        The backend to switch to.  This can either be one of the standard
        backend names, which are case-insensitive:
    
        - interactive backends:
          GTK3Agg, GTK3Cairo, MacOSX, nbAgg,
          Qt4Agg, Qt4Cairo, Qt5Agg, Qt5Cairo,
          TkAgg, TkCairo, WebAgg, WX, WXAgg, WXCairo
    
        - non-interactive backends:
          agg, cairo, pdf, pgf, ps, svg, template
    
        or a string of the form: ``module://my.module.name``.
    
    force : bool, default: True
        If True (the default), raise an `ImportError` if the backend cannot be
        set up (either because it fails to import, or because an incompatible
        GUI interactive framework is already running); if False, ignore the
        failure.
    
    See Also
    --------
    :ref:`backends`
    matplotlib.get_backend

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1