【问题标题】:OpenCV : Memory leak while using QPixmapOpenCV:使用 QPixmap 时的内存泄漏
【发布时间】:2017-02-28 14:31:32
【问题描述】:

我正在尝试使用 opencv 从 1920x1080 高清摄像机以 60fps 进行视频流。问题不在于流式传输,而是内存泄漏,在流式传输的第一分钟内,我失去了近 6GB 的内存。请帮助我如何阻止这种情况。

  from PySide.QtCore import *
  from PySide.QtGui import *
  import cv2
  import sys

  class MainApp(QWidget):

      def __init__(self):
        QWidget.__init__(self)
        self.video_size = QSize(1920, 1080)
        self.setup_ui()
        self.setup_camera()

    def setup_ui(self):
        """Initialize widgets.
        """
        self.image_label = QLabel()
        self.image_label.setFixedSize(self.video_size)

        self.quit_button = QPushButton("Quit")
        self.quit_button.clicked.connect(self.close)

        self.main_layout = QVBoxLayout()
        self.main_layout.addWidget(self.image_label)
        self.main_layout.addWidget(self.quit_button)

        self.setLayout(self.main_layout)

    def setup_camera(self):
        """Initialize camera.
        """
        self.capture = cv2.VideoCapture(0)
        self.capture.set(cv2.CAP_PROP_FRAME_WIDTH, self.video_size.width())
        self.capture.set(cv2.CAP_PROP_FRAME_HEIGHT, self.video_size.height())

        self.timer = QTimer()
        self.timer.timeout.connect(self.display_video_stream)
        self.timer.start(30)

    def display_video_stream(self):
        """Read frame from camera and repaint QLabel widget.
        """
        _, frame = self.capture.read()
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        image = QImage(frame, frame.shape[1], frame.shape[0],
                   frame.strides[0], QImage.Format_RGB888)
        self.image_label.setPixmap(QPixmap.fromImage(image))

if __name__ == "__main__":
    app = QApplication(sys.argv)
    win = MainApp()
    win.show()
    sys.exit(app.exec_())

编辑

我发现内存泄漏在哪里self.timer.start(30)如果我增加时间调用,内存泄漏会更慢。有什么建议如何阻止内存泄漏?

【问题讨论】:

    标签: memory-leaks video-streaming pyside python-3.4 qpixmap


    【解决方案1】:

    如果有人遇到同样的问题,请导入 qimage2ndarray 这个库并添加 函数 display_video_stream 的以下更改

        def display_video_stream(self):
        """Read frame from camera and repaint QLabel widget.
        """
    
        _, frame = self.capture.read()
    
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        # frame = cv2.flip(frame, 1)
        image = qimage2ndarray.array2qimage(frame) #Solution for memory leak
        self.image_label.setPixmap(QPixmap.fromImage(image))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-30
      • 1970-01-01
      • 1970-01-01
      • 2015-08-12
      • 1970-01-01
      • 1970-01-01
      • 2020-08-15
      • 1970-01-01
      相关资源
      最近更新 更多