Matplotlib中过多的内存使用imshow
我有一个PyQT4应用程序,它在Matplotlib图中显示中等大小的图像。我正在显示的测试图像大约是5Mb(2809 x 1241像素)。顺便说一下,我使用GDAL读取数据。图像被读入一个数组中,其中无数值被掩盖。然后用标准化的值和指定的颜色表显示Matplotlib中过多的内存使用imshow
它似乎使用过多的内存来显示一个5MB文件。我所看到的是,需要140mb的内存来显示以全分辨率读入的图像。 (使用imshow的应用程序注释掉了60mb的内存,vs206)随着图像以多个图形显示,每个图像使用额外的200m内存,问题变得更加严重。在大约3或4个数字显示的应用程序开始陷入内存使用进入700-900 mb范围内。
我了解matplotlib必须存储所有像素,即使它只显示缩减采样子集以匹配屏幕分辨率。我可能最终会写程序,只读取一定数量的像素以匹配数字大小。但由于这个应用程序将在8个独立的屏幕上显示多达8个地图,我担心它仍然使用过多的内存。
所以我的问题是:
1)这看起来像是用来显示简单的彩色地图图像的过多内存吗?它对我有用。
2)有什么我可以做的,以减少这种内存使用情况?例如使用整数数据类型,释放内存等。
3)我应该使用其他什么策略来处理这种内存使用情况?例如采样(可能不以全屏幕分辨率1900x1200的非常有效),切换到64位架构等
感谢, 代码如下
import sys, os, random
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import matplotlib
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar
from matplotlib.figure import Figure
import matplotlib.colors as colors
import numpy as np
from osgeo import gdal, gdalconst
gridfile = r"i:\vistrails\workingfiles\secondseason\secondseason_workfile_2012_02_28b\brt_1\brt_prob_map.tif"
class AppForm(QMainWindow):
def __init__(self, parent=None):
QMainWindow.__init__(self, parent)
self.create_main_frame()
ds = gdal.Open(gridfile, gdal.GA_ReadOnly)
ary = ds.GetRasterBand(1).ReadAsArray(buf_ysize=500, buf_xsize=300)
ndval = ds.GetRasterBand(1).GetNoDataValue()
rasterdata = np.ma.masked_array(ary, mask=(ary==ndval))
del ary
self.axes.imshow(rasterdataint, cmap=matplotlib.cm.jet)
del rasterdata
def create_main_frame(self):
self.main_frame = QWidget()
# Create the mpl Figure and FigCanvas objects.
# 5x4 inches, 100 dots-per-inch
#
self.dpi = 100
self.fig = Figure((5.0, 4.0), dpi=self.dpi)
self.canvas = FigureCanvas(self.fig)
self.canvas.setParent(self.main_frame)
self.axes = self.fig.add_subplot(111)
self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame)
vbox = QVBoxLayout()
vbox.addWidget(self.canvas)
vbox.addWidget(self.mpl_toolbar)
self.main_frame.setLayout(vbox)
self.setCentralWidget(self.main_frame)
def main():
app = QApplication(sys.argv)
form = AppForm()
form.show()
app.exec_()
if __name__ == "__main__":
main()
与使用imshow()
内存问题已经被注意到,作为here 。
1 /升级
如这里mentionned,upgrading to latest vesion of mpl may fix the problem。
2/PIL
作为替代方案,你可以让你的PIL库。
当它转到jpg文件时,如果安装了imshow(),则使用PIL。您可以直接使用PIL模块,as documented here。
我有一个类似的问题,我通过使用'draw()'而不是'show()'和删除imshow对象来解决它。例如:'self.im = imshow(your_data)','draw()','del self.im'。我不知道这是你的情况 – maupertius 2012-04-24 15:25:53