matplotlib RuntimeError: Could not allocate memory for image - python

So, I'm receiving "RuntimeError: Could not allocate memory for image" from matplotlib when I try to re-size my image on the canvas. The images are large DICOM (.dcm) files that have been allocated memory using ctypes' PyMem_Malloc. They've been allocated 16 bits per pixel (they need to be Hi-Res). The problem comes after we've re-sized the canvas and attempt to draw the re-sized image using:
self.view.canvas.draw()
Here's the specific exception being thrown:
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\matplotlib\backends\backend_wx.py", line 1355, in _onMotion
FigureCanvasBase.motion_notify_event(self, x, y, guiEvent=evt)
File "C:\Python27\lib\site-packages\matplotlib\backend_bases.py", line 1625, in motion_notify_event
self.callbacks.process(s, event)
File "C:\Python27\lib\site-packages\matplotlib\cbook.py", line 265, in process
proxy(*args, **kwargs)
File "C:\Python27\lib\site-packages\matplotlib\cbook.py", line 191, in __call__
return mtd(*args, **kwargs)
File "C:\Python27\lib\site-packages\matplotlib\widgets.py", line 1258, in onmove
self.update()
File "C:\Python27\lib\site-packages\matplotlib\widgets.py", line 1236, in update
self.canvas.restore_region(self.background)
File "C:\Python27\lib\site-packages\matplotlib\backends\backend_agg.py", line 384, in restore_region
renderer = self.get_renderer()
File "C:\Python27\lib\site-packages\matplotlib\backends\backend_agg.py", line 404, in get_renderer
self.renderer = RendererAgg(w, h, self.figure.dpi)
File "C:\Python27\lib\site-packages\matplotlib\backends\backend_agg.py", line 59, in __init__
self._renderer = _RendererAgg(int(width), int(height), dpi, debug=False)
RuntimeError: Could not allocate memory for image
The images themselves shouldn't need more allocation, correct? So what could be the problem here? Does matplotlib limit the size in memory that the canvas can hold? Has anyone had this problem?

Related

Getting ZeroDivisionError on figurecanvasTkagg on one computer but not on another [matplotlib]

I've been working a lot on my code on two different computers, using a git repository to commit all of the changes.
Recently I faced a strange problem in which when using figurecanvasTkagg.draw() I get a ZeroDivisionError on one computer always, while the other one runs just fine and executes the code to completion.
It specifically says that it crashed while performing h0 = h / self.height_ratios[0] in the grid_constraints method of matplotlib/_layoutgrid.py
There is nothing I can actually change as this method is well inside the library and I have found no way to acces it or modify it. I've tried searching for days for the solution to this error but I've found nothing.
Here it is the message error I get when executing the draw() function:
File "/home/marcjou/anaconda3/envs/tMednet/lib/python3.8/site-packages/matplotlib/backends/backend_tkagg.py", line 10, in draw
super().draw()
File "/home/marcjou/anaconda3/envs/tMednet/lib/python3.8/site-packages/matplotlib/backends/backend_agg.py", line 405, in draw
self.figure.draw(self.renderer)
File "/home/marcjou/anaconda3/envs/tMednet/lib/python3.8/site-packages/matplotlib/artist.py", line 74, in draw_wrapper
result = draw(artist, renderer, *args, **kwargs)
File "/home/marcjou/anaconda3/envs/tMednet/lib/python3.8/site-packages/matplotlib/artist.py", line 51, in draw_wrapper
return draw(artist, renderer)
File "/home/marcjou/anaconda3/envs/tMednet/lib/python3.8/site-packages/matplotlib/figure.py", line 3065, in draw
self.get_layout_engine().execute(self)
File "/home/marcjou/anaconda3/envs/tMednet/lib/python3.8/site-packages/matplotlib/layout_engine.py", line 255, in execute
return do_constrained_layout(fig, w_pad=w_pad, h_pad=h_pad,
File "/home/marcjou/anaconda3/envs/tMednet/lib/python3.8/site-packages/matplotlib/_constrained_layout.py", line 104, in do_constrained_layout
layoutgrids = make_layoutgrids(fig, None, rect=rect)
File "/home/marcjou/anaconda3/envs/tMednet/lib/python3.8/site-packages/matplotlib/_constrained_layout.py", line 192, in make_layoutgrids
layoutgrids = make_layoutgrids_gs(layoutgrids, gs)
File "/home/marcjou/anaconda3/envs/tMednet/lib/python3.8/site-packages/matplotlib/_constrained_layout.py", line 234, in make_layoutgrids_gs
layoutgrids[gs] = mlayoutgrid.LayoutGrid(
File "/home/marcjou/anaconda3/envs/tMednet/lib/python3.8/site-packages/matplotlib/_layoutgrid.py", line 112, in __init__
self.add_constraints()
File "/home/marcjou/anaconda3/envs/tMednet/lib/python3.8/site-packages/matplotlib/_layoutgrid.py", line 149, in add_constraints
self.grid_constraints()
File "/home/marcjou/anaconda3/envs/tMednet/lib/python3.8/site-packages/matplotlib/_layoutgrid.py", line 247, in grid_constraints
h0 = h / self.height_ratios[0]
ZeroDivisionError: float division by zero
Thanks in advance!

Pyglet sprite.draw() crashing on iGPU

I've written the following python loop to display multiple gif files one after another. The code works fine on one of my machines with a dedicated GPU but only displays one gif on my laptop with an AMD iGPU displaying the following error msg after closing the first window (both PCs run windows 10):
import pyglet
def play_animation(ag_file):
animation = pyglet.image.load_animation(ag_file)
sprite = pyglet.sprite.Sprite(animation)
win = pyglet.window.Window(width=sprite.width, height=sprite.height)
green = 0, 1, 0, 1
pyglet.gl.glClearColor(*green)
#win.event
def on_draw():
win.clear()
sprite.draw()
pyglet.app.run()
if __name__ == '__main__':
gif_list = ['gif1.gif', 'gif2.gif']
for gif in gif_list:
print(gif)
play_animation(gif)
And the error I get after I close the first animation is:
gif1.gif
gif2.gif
Traceback (most recent call last):
File "main.py", line 226, in <module>
play_animation(Save_Name)
File "main.py", line 29, in play_animation
pyglet.app.run()
File "C:\Users\..\AppData\Roaming\Python\Python311\site-packages\pyglet\app\__init__.py", line 107, in run
event_loop.run(interval)
File "C:\Users\..\AppData\Roaming\Python\Python311\site-packages\pyglet\app\base.py", line 186, in run
timeout = self.idle()
^^^^^^^^^^^
File "C:\Users\..\AppData\Roaming\Python\Python311\site-packages\pyglet\app\base.py", line 247, in idle
self.clock.call_scheduled_functions(dt)
File "C:\Users\..\AppData\Roaming\Python\Python311\site-packages\pyglet\clock.py", line 262, in call_scheduled_functions
item.func(now - item.last_ts, *item.args, **item.kwargs)
File "C:\Users\..\AppData\Roaming\Python\Python311\site-packages\pyglet\app\base.py", line 153, in _redraw_windows
window.dispatch_event('on_draw')
File "C:\Users\..\AppData\Roaming\Python\Python311\site-packages\pyglet\window\__init__.py", line 1363, in dispatch_event
super().dispatch_event(*args)
File "C:\Users\..\AppData\Roaming\Python\Python311\site-packages\pyglet\event.py", line 415, in dispatch_event
if handler(*args):
^^^^^^^^^^^^^^
File "main.py", line 19, in on_draw
sprite.draw()
File "C:\Users\..\AppData\Roaming\Python\Python311\site-packages\pyglet\sprite.py", line 820, in draw
self._vertex_list.draw(GL_TRIANGLES)
File "C:\Users\..\AppData\Roaming\Python\Python311\site-packages\pyglet\graphics\vertexdomain.py", line 276, in draw
self.domain.draw_subset(mode, self)
File "C:\Users\..\AppData\Roaming\Python\Python311\site-packages\pyglet\graphics\vertexdomain.py", line 491, in draw_subset
self.vao.bind()
File "C:\Users\..\AppData\Roaming\Python\Python311\site-packages\pyglet\graphics\vertexarray.py", line 58, in bind
glBindVertexArray(self._id)
File "C:\Users\..\AppData\Roaming\Python\Python311\site-packages\pyglet\gl\lib.py", line 114, in errcheck
raise GLException('(0x%x): %s' % (error, msg))
pyglet.gl.lib.GLException: (0x502): Invalid operation. The specified operation is not allowed in the current state.
I updated the driver on both machines and installed the latest version of python (3.11) and pyglet (2.0.2.1) as well as all Updates for windows

savefig() causing ValueError: RGBA values should be within 0-1 range

I'm trying to create a program who will :
Retrieve data from a csv file chosen by the user
Plot the data
Display the figure on the window
Allow the user to change the plot parameters (color, linestyle ...)
Save the plot in a directory chosen by the user in the PS format
Steps 1 to 4 are working just fine, but step 5 makes me feel like I've killed matplotlib ...
I'm using the same syntax I used on a previous version for saving, which worked fine :
def savePlot(self):
self.saveDirectory = QFileDialog.getExistingDirectory(None, 'Chose where you want to save','/home',QFileDialog.ShowDirsOnly | QFileDialog.DontResolveSymlinks)
if self.plotParam==[]:
plt.savefig(self.saveDirectory + "/" + "Untiltled.ps", dpi = 1200)
else :
plt.savefig(self.saveDirectory + "/" + "%s.ps" %self.plotParam[0],format = 'ps', dpi = 1200)
Here is a link to the full code, and here is the data file I'm using.
In this portion, self.plotParam is a list which is initially empty and contains the plot parameters if the user wants to change the default ones.
Here is the error log :
Traceback (most recent call last):
File "/home/antoine/miniconda3/lib/python3.6/site-packages/matplotlib/colors.py", line 141, in to_rgba
rgba = _colors_full_map.cache[c, alpha]
TypeError: unhashable type: 'numpy.ndarray'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/antoine/CERB/courbes/courbesv2.py", line 354, in savePlot
plt.savefig(self.saveDirectory + "/" + "essai.ps", dpi = 1200)
File "/home/antoine/miniconda3/lib/python3.6/site-packages/matplotlib/pyplot.py", line 697, in savefig
res = fig.savefig(*args, **kwargs)
File "/home/antoine/miniconda3/lib/python3.6/site-packages/matplotlib/figure.py", line 1573, in savefig
self.canvas.print_figure(*args, **kwargs)
File "/home/antoine/miniconda3/lib/python3.6/site-packages/matplotlib/backends/backend_qt5agg.py", line 222, in print_figure
FigureCanvasAgg.print_figure(self, *args, **kwargs)
File "/home/antoine/miniconda3/lib/python3.6/site-packages/matplotlib/backend_bases.py", line 2252, in print_figure
**kwargs)
File "/home/antoine/miniconda3/lib/python3.6/site-packages/matplotlib/backends/backend_ps.py", line 957, in print_ps
return self._print_ps(outfile, 'ps', *args, **kwargs)
File "/home/antoine/miniconda3/lib/python3.6/site-packages/matplotlib/backends/backend_ps.py", line 988, in _print_ps
**kwargs)
File "/home/antoine/miniconda3/lib/python3.6/site-packages/matplotlib/backends/backend_ps.py", line 1078, in _print_figure
self.figure.draw(renderer)
File "/home/antoine/miniconda3/lib/python3.6/site-packages/matplotlib/artist.py", line 63, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/home/antoine/miniconda3/lib/python3.6/site-packages/matplotlib/figure.py", line 1144, in draw
renderer, self, dsu, self.suppressComposite)
File "/home/antoine/miniconda3/lib/python3.6/site-packages/matplotlib/image.py", line 139, in _draw_list_compositing_images
a.draw(renderer)
File "/home/antoine/miniconda3/lib/python3.6/site-packages/matplotlib/artist.py", line 63, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/home/antoine/miniconda3/lib/python3.6/site-packages/matplotlib/axes/_base.py", line 2426, in draw
mimage._draw_list_compositing_images(renderer, self, dsu)
File "/home/antoine/miniconda3/lib/python3.6/site-packages/matplotlib/image.py", line 139, in _draw_list_compositing_images
a.draw(renderer)
File "/home/antoine/miniconda3/lib/python3.6/site-packages/matplotlib/artist.py", line 63, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/home/antoine/miniconda3/lib/python3.6/site-packages/matplotlib/collections.py", line 354, in draw
self._offset_position)
File "/home/antoine/miniconda3/lib/python3.6/site-packages/matplotlib/backends/backend_ps.py", line 607, in draw_path_collection
offset_position)
File "/home/antoine/miniconda3/lib/python3.6/site-packages/matplotlib/backend_bases.py", line 309, in draw_path_collection
antialiaseds, urls, offset_position):
File "/home/antoine/miniconda3/lib/python3.6/site-packages/matplotlib/backend_bases.py", line 497, in _iter_collection
gc0.set_foreground(fg)
File "/home/antoine/miniconda3/lib/python3.6/site-packages/matplotlib/backend_bases.py", line 1027, in set_foreground
self._rgb = colors.to_rgba(fg)
File "/home/antoine/miniconda3/lib/python3.6/site-packages/matplotlib/colors.py", line 143, in to_rgba
rgba = _to_rgba_no_colorcycle(c, alpha)
File "/home/antoine/miniconda3/lib/python3.6/site-packages/matplotlib/colors.py", line 204, in _to_rgba_no_colorcycle
raise ValueError("RGBA values should be within 0-1 range")
ValueError: RGBA values should be within 0-1 range
I've tried using different extensions than .ps, and all of them show the same error, except .png, which saves me a disgustingly awfull image, even when it's supposed to be 1200 dpi (I can't post you a link to the saved image as I do not have enough reputation, sorry).
I've also tried doing a "clean path" with os.path.join, but it changed nothing, so I reverted back to the syntax which used to work on the previous version.
I know my code is most likely suboptimal, but I'm learning so it can't be helped ...
Do you have any clues on how to solve this ?
EDIT : Added the minimal, complete and verifiable example :
import matplotlib.pyplot as plt
data = [[1,2,3,4,5,6,7,8,9,10],[1,2,3,4,5,6,7,8,9,10],[0.2,0.2,0.2,0.2,0.2,0.2,0.2,0.2,0.2,0.2]]
def plotAttempt():
plt.errorbar(data[0],data[1],data[2],0)
path = '/home/PlotAttempt.ps'
plt.savefig(path)
Calling plotAttempt() through the console gets me the same error log
This appears to be a pyzo bug, the code worked just fine when I ran it through the console and after rebooting it also worked on pyzo.

Python Pillow - broken data stream

Pillow looks to be the solution to a lot of my problems, but I can't get it to work correctly. I think there might be something that I'm missing but I can't find any solutions that work.
from PIL import Image
img = Image.open("base64 (1).png")
print(img.size)
print(img.format)
img.show()
I have this set up to load an image, print its size and format, and then show the image. When I run the code, I get this:
(1920, 1080)
PNG
Traceback (most recent call last):
File "C:/Users/##########/PycharmProjects/weatherCanvas/imageTest.py", line 7, in <module>
img.show()
File "C:\Python27\lib\site-packages\PIL\Image.py", line 1736, in show
_show(self, title=title, command=command)
File "C:\Python27\lib\site-packages\PIL\Image.py", line 2449, in _show
_showxv(image, **options)
File "C:\Python27\lib\site-packages\PIL\Image.py", line 2454, in _showxv
ImageShow.show(image, title, **options)
File "C:\Python27\lib\site-packages\PIL\ImageShow.py", line 51, in show
if viewer.show(image, title=title, **options):
File "C:\Python27\lib\site-packages\PIL\ImageShow.py", line 75, in show
image = image.convert(base)
File "C:\Python27\lib\site-packages\PIL\Image.py", line 844, in convert
self.load()
File "C:\Python27\lib\site-packages\PIL\ImageFile.py", line 250, in load
raise_ioerror(e)
File "C:\Python27\lib\site-packages\PIL\ImageFile.py", line 59, in raise_ioerror
raise IOError(message + " when reading image file")
IOError: broken data stream when reading image file
The same thing happens if I replace img.show() with saving it. I know that PIL and Pillow save a temporary file in order to do the show() method, so I think the problem is somewhere in that.
Is there something I'm missing here?

savefig PGF - RuntimeError: Cannot get window extent w/o renderer

I'm trying to save a figure in pyplot with tight margins.
The following code works perfectly with a PDF output:
from matplotlib import pyplot as plt
plt.plot(1)
plt.savefig('test.pdf', bbox_inches='tight')
But not with PGF output
plt.savefig('test.pgf', bbox_inches='tight')
as it returns RuntimeError: Cannot get window extent w/o renderer.
Why is this happening and is there a way to work around it?
matplotlib 1.3.0rc2 on Ubuntu 13.04
python -c "from matplotlib import pyplot as plt; plt.plot(1); plt.savefig('test.pgf', bbox_inches='tight');"
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "PYTHONPATH/matplotlib-1.3.0rc2-py2.7-linux-x86_64.egg/matplotlib/pyplot.py", line 561, in savefig
return fig.savefig(*args, **kwargs)
File "PYTHONPATH/matplotlib-1.3.0rc2-py2.7-linux-x86_64.egg/matplotlib/figure.py", line 1410, in savefig
self.canvas.print_figure(*args, **kwargs)
File "PYTHONPATH/matplotlib-1.3.0rc2-py2.7-linux-x86_64.egg/matplotlib/backends/backend_qt4agg.py", line 161, in print_figure
FigureCanvasAgg.print_figure(self, *args, **kwargs)
File "PYTHONPATH/matplotlib-1.3.0rc2-py2.7-linux-x86_64.egg/matplotlib/backend_bases.py", line 2169, in print_figure
bbox_inches = self.figure.get_tightbbox(renderer)
File "PYTHONPATH/matplotlib-1.3.0rc2-py2.7-linux-x86_64.egg/matplotlib/figure.py", line 1551, in get_tightbbox
bb.append(ax.get_tightbbox(renderer))
File "PYTHONPATH/matplotlib-1.3.0rc2-py2.7-linux-x86_64.egg/matplotlib/axes.py", line 9153, in get_tightbbox
bb_xaxis = self.xaxis.get_tightbbox(renderer)
File "PYTHONPATH/matplotlib-1.3.0rc2-py2.7-linux-x86_64.egg/matplotlib/axis.py", line 1055, in get_tightbbox
renderer)
File "PYTHONPATH/matplotlib-1.3.0rc2-py2.7-linux-x86_64.egg/matplotlib/axis.py", line 1038, in _get_tick_bboxes
extent = tick.label1.get_window_extent(renderer)
File "PYTHONPATH/matplotlib-1.3.0rc2-py2.7-linux-x86_64.egg/matplotlib/text.py", line 751, in get_window_extent
raise RuntimeError('Cannot get window extent w/o renderer')
RuntimeError: Cannot get window extent w/o renderer
By the way, there is a workaround. Normally the extent of PGF/TikZ images is adjusted automatically so it matches the drawing. For preserving the figure size intended by matplotlib, these lines are added to the output:
\pgfpathrectangle{\pgfpointorigin}{\pgfqpoint{8.000000in}{6.000000in}}%
\pgfusepath{use as bounding box}%
If you remove these lines at the very top from the PGF output you should get rid of any additional space around the figure.
Using plt.tight_layout(), or better plt.figure(tight_layout=True) in version 1.3, is another way to do that (which works perfectly with PGF and PGF->PDF), although it is a bit different. It recalculates the figure's layout so it fits to the given figure size. I usually prefer that method because it also eliminates problems like overlapping text elements.

Categories

Resources