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:OneDriveBureauNew folder12345.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
Advertisement
Answer
According to this post, this is an issue with the TkAgg backend.
I was able to get it to work using:
JavaScript131reload(matplotlib)
2matplotlib.use('Agg')
3
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
JavaScript171if(!bitmap) {
2panic("Fail to allocate bitmapn");
3DeleteDC(dcMem);
4TkWinReleaseDrawableDC(d, dc, &state);
5return;
6}
7
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()
:
JavaScript130301use(backend, *, force=True)
2Select the backend used for rendering and GUI integration.
3
4Parameters
5----------
6backend : str
7The backend to switch to. This can either be one of the standard
8backend names, which are case-insensitive:
9
10- interactive backends:
11GTK3Agg, GTK3Cairo, MacOSX, nbAgg,
12Qt4Agg, Qt4Cairo, Qt5Agg, Qt5Cairo,
13TkAgg, TkCairo, WebAgg, WX, WXAgg, WXCairo
14
15- non-interactive backends:
16agg, cairo, pdf, pgf, ps, svg, template
17
18or a string of the form: ``module://my.module.name``.
19
20force : bool, default: True
21If True (the default), raise an `ImportError` if the backend cannot be
22set up (either because it fails to import, or because an incompatible
23GUI interactive framework is already running); if False, ignore the
24failure.
25
26See Also
27--------
28:ref:`backends`
29matplotlib.get_backend
30