RuntimeError:保存并在关闭pyplot数字后删除了基础C / C ++对象

时间:2012-07-26 13:35:37

标签: python matplotlib runtime-error

我遇到了一个python错误,我一直试图解决好几天了。 我的程序创建数字,保存并关闭它们,除了这个错误,它工作正常。通常它不会妨碍保存过程,但有时保存时图片会丢失下半部分。奇怪的是,这只发生在循环到达savefig方法的第二次,这是我的代码:

for num in np.arange(file_number):
    plt.figure('abc' + str(num),figsize=(22,12),dpi=100)
    #some plots are added to the figure
    print 1
    plt.savefig(os.path.join(savepath,filename),dpi=100)
    print 2
    plt.close()                                                                    
    print 3

我使用print命令查看错误发生的位置。这是spyder的控制台输出:

Reading file1.file
1
2
3
Reading file2.file
1
Traceback (most recent call last):
  File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_qt4.py", line 151, in <lambda>
    lambda: self.close_event())
  File "/usr/lib/pymodules/python2.7/matplotlib/backend_bases.py", line 1564, in close_event
    self.callbacks.process(s, event)
RuntimeError: underlying C/C++ object has been deleted
2
3
Reading file3.file
1
2
3
Reading file4.file
1
Traceback (most recent call last):
  File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_qt4.py", line 151, in <lambda>
    lambda: self.close_event())
  File "/usr/lib/pymodules/python2.7/matplotlib/backend_bases.py", line 1564, in close_event
    self.callbacks.process(s, event)
RuntimeError: underlying C/C++ object has been deleted
2
3

根据我的理解,在保存图形(每隔一次)时已经出现错误,尽管如果省略close()命令它可以正常工作。在这种情况下,我的RAM在大约70个文件后填充,有时我需要评估几百个。这就是为什么我需要包含close()命令或类似的东西。 如果你解决这个问题(或改进我的编程,我想我这样做的保存和关闭的方式可能会被认为是丑陋的)请帮助我。

2 个答案:

答案 0 :(得分:0)

如何将后端更改为其他选项?例如:

import matplotlib as mpl
mpl.use( "agg" )

from matplotlib import pyplot as plt
import numpy as np

print plt.get_backend()

file_number = 100
for num in np.arange(file_number):
    plt.figure('abc' + str(num),figsize=(22,12),dpi=100)
    #some plots are added to the figure
    print 1
    plt.savefig("%d.png" % num,dpi=100)
    print 2
    plt.close()
    print 3

答案 1 :(得分:0)

我无法复制您的问题(部分原因是您的示例不是自包含的),但我认为您可以考虑解决稍微不同的问题。

由于你的图形定义(大小,dpi等)在整个循环中保持不变(即使它没有),你可以看看只产生一个数字,并在循环中更新它:

import matplotlib as mpl
mpl.use( "tkagg" )

from matplotlib import pyplot as plt
import numpy as np


file_number = 1000
fig = plt.figure('abc', figsize=(22,12), dpi=100)

plt.show(block=False)

for num in np.arange(file_number):
    fig.set_label('abc%s' % num)

    # add an axes to the figure
    ax = plt.axes()

    #some plots are added to the figure (I just plotted a line)
    plt.plot(range(num))

    plt.savefig("%d.png" % num, dpi=100)
    # draw the latest changes to the gui
    plt.draw()

    # remove the axes now that we have done what we want with it.
    fig.delaxes(ax)

# put in a blocking show to wait for user interaction / closure.
plt.show()

通常情况下,这不是你要做的事情(我通常会更新轴而不是每次都添加/删除一个),但也许你有充分的理由这样做。

这应该会显着提高性能。

相关问题