問題描述
我正在嘗試使用 OpenCV 和 PyQt5 處理圖像序列并制作結果視頻.我有一些代碼循環遍歷目錄、讀取圖像并嘗試在QGraphicsView
上顯示它們.
I'm trying to process an image sequence and make a video of the results using OpenCV and PyQt5. I've got some code that loops through a directory, reads in the images, and tries to display them on a QGraphicsView
.
def on_start(self):
for f in self.image_list:
img = cv2.imread(f)
img = cv2qimage(img, False)
self.scene.set_qimage(img)
self.scene
繼承自 QGraphicsScene
.
def set_qimage(self, qimage):
self.pixmap = QPixmap.fromImage(qimage)
self.addPixmap(self.pixmap)
問題是每次我調用 addPixmap()
時,圖像都會添加到所有其他圖像之上,很快我就會耗盡內存,一切都崩潰了.當前代碼不包含任何處理步驟,它只是將 numpy ndarry 轉換為 QImage 并將 QPixmap 添加到場景中.
The problem is everytime I call addPixmap()
the image is just added on top of all the other images and soon I run out of memory and everything crashes.
The current code doesn't include any of the processing steps, it just converts the numpy ndarry to a QImage and adds the QPixmap to the scene.
更新 QGraphicsScene 以便我可以流式傳輸一系列圖像的正確方法是什么?
推薦答案
每次使用 addPixmap()
時,您都會創建一個新的 QGraphicsPixmapItem
,從而不必要地添加內存.解決方案是創建一個 QGraphicsPixmapItem
并重用它.另外處理任務會阻塞主線程,所以必須使用線程來完成繁重的任務,并通過信號發送QImage
.
Every time you use addPixmap()
you are creating a new QGraphicsPixmapItem
adding memory unnecessarily. The solution is to create a QGraphicsPixmapItem
and reuse it. In addition the processing task can block the main thread so you must use a thread to do the heavy task and send the QImage
through signals.
class ProcessWorker(QObject):
imageChanged = pyqtSignal(QImage)
def doWork(self):
for f in self.image_list:
img = cv2.imread(f)
img = cv2qimage(img, False)
self.imageChanged.emit(img)
QThread.msleep(1)
class Widget(QWidget):
def __init__(self, parent=None):
QWidget.__init__(self, parent)
lay = QVBoxLayout(self)
gv = QGraphicsView()
lay.addWidget(gv)
scene = QGraphicsScene(self)
gv.setScene(scene)
self.pixmap_item = QGraphicsPixmapItem()
scene.addItem(self.pixmap_item)
self.workerThread = QThread()
self.worker = ProcessWorker()
self.worker.moveToThread(self.workerThread)
self.workerThread.finished.connect(self.worker.deleteLater)
self.workerThread.started.connect(self.worker.doWork)
self.worker.imageChanged.connect(self.setImage)
self.workerThread.start()
@pyqtSlot(QImage)
def setImage(self, image):
pixmap = QPixmap.fromImage(image)
self.pixmap_item.setPixmap(pixmap)
if __name__ == '__main__':
app = QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
這篇關于在 QGraphicsView 中播放圖像序列(神秘的內存泄漏)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!