PIL到Qimage的转换:QImage构造函数没有释放内存

时间:2013-02-05 21:04:22

标签: python-imaging-library qimage

我正在使用 PIL 开发Qt应用程序加载图片,修改颜色和Alpha通道,然后将它们转换为QImage

这是一段有问题的代码:正常重复使用ImageQt 函数:

    # memory is filled  around 7 mB/s
    if name == 'main':
        while True:
            im = Image.open('einstein.png') #small picture
            imQt = QtGui.QImage(ImageQt.ImageQt(im)) # convert to PySide.QtGui.QImage
            imQt.save('outtest.png')# -> rendered picture is correct
            #del(imQt) and del(im) does not change anything
            time.sleep(0.02)
这里的问题是疯狂的内存填充 ,当图片应该被垃圾收集器擦除。我检查了gc.collect(),但它没有改变任何东西。

此示例显示了 imageQt 函数发生的情况,但实际上,我注意到这是由QImage引起的问题:如果您反复使用QImage构造函数的数据,则使用的内存通过python进程增加

    im= Image.load('mypic.png').convert('RGBA')
    data = im.toString('raw','RGBA')
    qIm = QtGui.QImage(data,im.size[0],im.size[1],QtGui.QImage.Format_ARGB32)
    qIm.save('myConvertedPic.png')# -> picture is perfect
如果将此代码放在循环中,则内存将增加,如第一个示例所示。从那里我有点迷失,因为这是一个PySide问题......

我尝试使用变通方法,但它也不起作用:

    #Workaround, but not working ....
if name == 'main': while True: im = Image.open('einstein.png') #small picture imRGBA = im.convert('RGBA') # convert to RGBA imRGBA.save('convtest.png') # ->picture is looks perfect imBytes = imRGBA.tostring('raw','RGBA') #print("size %d %d" % (imRGBA.size[0],imRGBA.size[1])) qImage = QtGui.QImage(imRGBA.size[0],imRGBA.size[1],QtGui.QImage.Format_ARGB32) # create new empty picture qImage.fill(QtCore.Qt.blue) # fill with blue, otherwise it catches pieces of the picture still in memory loaded = qImage.loadFromData(imBytes,'RGBA') # load from raw data print("success %d" % loaded)# -> returns 0 qImage.save('outtest.png')# -> rendered picture is blue time.sleep(0.02)
我真的被困在这里,如果你能帮助找到解决方法?因为我真的被困在这里! 另外我想讨论QImage问题。有没有可靠的方法来释放这段记忆?在这种情况下,我使用python3.2(32位)的事实可能是一个问题吗?在这种情况下,我是唯一一个人吗?

我在以下情况下使用的导入:

    import time
    import sys
    import PySide
    sys.modules['PyQt4'] = PySide # this little hack allows to solve naming problem when using PIL with Pyside (instead of PyQt4)
    from PIL import Image, ImageQt
    from PySide import QtCore,QtGui

1 个答案:

答案 0 :(得分:0)

在进一步搜索失败后,我注意到,与 QImage构造函数关联的PIL函数 image.tostring()导致了这个问题

    im = Image.open('einstein.png').convert('RGBA')
    data = im.tostring('raw','RGBA') # the tostring() function is out of the loop
    while True:
        imQt = QtGui.QImage(data,im.size[0],im.size[1],QtGui.QImage.Format_ARGB32)
        #imQt.save("testpic.png") #image is valid
        time.sleep(0.01)
        #no memory problem !
我认为我非常接近发现错误,但我无法指出。 它肯定与内存中保存的data变量有关。

相关问题