python-QImage内存泄漏

我已经编写了一个OpenCV应用程序,该应用程序基本上是从相机抓取帧,进行一些图像处理并以两种编辑的变体形式显示图像.首先,我使用cv2.imshow()来显示图像,但是尽管OpenCV(不支持Qt的构建)无法提供现代的GUI元素,但我决定将PySide用于我的GUI.

但是由于这个,我在处理了大约830-850帧后得到了这个错误(无论使用什么定时器速率,或者我做了多少图像处理):

QImage: out of memory, returning null image

我的两个图像视图都在GUI中,然后在每个循环中执行以下操作:

OpenCV Error: Unspecified error (The numpy array of typenum=2, ndims=3 can not be created) in NumpyAllocator::allocate, file ..\..\..\opencv-3.1.0\modules\python\src2\cv2.cpp, line 184
OpenCV Error: Insufficient memory (Failed to allocate 921600 bytes) in cv::OutOfMemoryError, file ..\..\..\opencv-3.1.0\modules\core\src\alloc.cpp, line 52
Traceback (most recent call last):
  File "C:/myfile.py", line 140, in process_frame
    img = QtGui.QImage(cv2.cvtColor(thresh_img, cv2.COLOR_RGB2BGR), self.width, self.height,
cv2.error: ..\..\..\opencv-3.1.0\modules\core\src\alloc.cpp:52: error: (-4) Failed to allocate 921600 bytes in function cv::OutOfMemoryError

这是我的代码的一部分(不进行图像处理,但也会产生错误):

import cv2
import sys
from PySide import QtGui, QtCore
from threading import Thread


class MainWindow(QtGui.QMainWindow):
    def __init__(self, cam=0, parent=None):
        super(MainWindow, self).__init__(parent)

        self.camera = Camera(cam).start()
        self.title = "Cam %s" % cam
        self.counter = 0

        widget = QtGui.QWidget()
        self.layout = QtGui.QBoxLayout(QtGui.QBoxLayout.LeftToRight)

        self.video_frame = QtGui.QLabel()
        self.thresh_frame = QtGui.QLabel()

        self.layout.addWidget(self.video_frame)
        self.layout.addWidget(self.thresh_frame)
        self.layout.addStretch()

        self.setCentralWidget(widget)
        widget.setLayout(self.layout)

        self.setMinimumSize(640, 480)
        self._timer = QtCore.QTimer(self)
        self._timer.timeout.connect(self.process_frame)
        self._timer.start(20)

    def process_frame(self):
        self.counter += 1
        print(self.counter)
        self.frame = self.camera.read()
        self.height, self.width = self.frame.shape[:2]

        thresh_img = cv2.threshold(cv2.cvtColor(self.frame, cv2.COLOR_RGB2GRAY), 0, 255,
                                   cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
        thresh_img = cv2.erode(thresh_img, None, iterations=2)
        thresh_img = cv2.dilate(thresh_img, None, iterations=2)
        thresh_img = cv2.cvtColor(thresh_img, cv2.COLOR_GRAY2RGB)

        img = QtGui.QImage(cv2.cvtColor(self.frame, cv2.COLOR_RGB2BGR), self.width, self.height,
                           QtGui.QImage.Format_RGB888)
        img = QtGui.QPixmap.fromImage(img)
        self.video_frame.setPixmap(img)

        img = QtGui.QImage(cv2.cvtColor(thresh_img, cv2.COLOR_RGB2BGR), self.width, self.height,
                           QtGui.QImage.Format_RGB888)
        img = QtGui.QPixmap.fromImage(img)
        self.thresh_frame.setPixmap(img)

    def closeEvent(self, event):
        self.camera.stop()
        event.accept()


class Camera:
    def __init__(self, src=0):
        self.stream = cv2.VideoCapture(src)
        (self.grabbed, self.frame) = self.stream.read()

        self.stopped = False

    def start(self):
        Thread(target=self.update, args=()).start()
        return self

    def update(self):
        while True:
            if self.stopped:
                return
            (self.grabbed, self.frame) = self.stream.read()

    def read(self):
        return self.frame

    def stop(self):
        self.stopped = True

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    window = MainWindow(0)
    window.show()
    sys.exit(app.exec_())

在Windows任务管理器中,我可以看到程序的RAM使用情况:

python-QImage内存泄漏

在崩溃时,该应用程序使用约1.5 GB的RAM.我尝试在del img之后使用gc模块和gc.collect(),但没有成功.

我还可以做些什么?

编辑:

线程化的Camera类在这里无关紧要,没有它也会出现错误.

解决方法:

这似乎是PySide特有的错误,使用PyQt可以修复它.它甚至与OpenCV无关.看起来现在没有使用PySide的解决方案…

上一篇:javascript-使用PyQt获取动态内容


下一篇:顺序容器及其常用函数