下面的代码在单击按钮时崩溃,或者当信号从线程发出并在主gui中捕获时,在几次单击之后崩溃。
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QPixmap, QImage
from PyQt5.QtCore import pyqtSignal, pyqtSlot, Qt, QThread
import numpy as np
import time
from PyQt5.QtWidgets import QApplication, QDialog, QPushButton, QVBoxLayout
def convert_np_qimage(cv_img , width, height):
h, w, ch = cv_img.shape
bytes_per_line = ch * w
qim = QtGui.QImage(cv_img.data, w, h, bytes_per_line, QtGui.QImage.Format_RGB888)
print(qim.size())
return qim
class VideoThread(QThread):
change_qimage_signal = pyqtSignal(QImage)
def __init__(self):
super().__init__()
def run(self):
print("run")
width = 1280
height = 1280
cv_img = np.zeros([height,width,3],dtype=np.uint8)
cv_img.fill(255)
print("image shape: ", cv_img.shape)
qimg = convert_np_qimage(cv_img, width, height)
self.change_qimage_signal.emit(qimg)
print("emitted")
def stop(self):
self.wait()
import sys
class Dialog(QDialog):
def __init__(self):
super(Dialog, self).__init__()
Dialog.resize(self, 640, 480)
button=QPushButton("Click")
button.clicked.connect(self.startThread)
mainLayout = QVBoxLayout()
mainLayout.addWidget(button)
self.setLayout(mainLayout)
self.setWindowTitle("QImage Example")
def startThread(self):
self.thread = VideoThread()
self.thread.change_qimage_signal.connect(self.getPixmap)
self.thread.start()
def getPixmap(self, qimg):
print("got qimage")
qpixmap = QPixmap.fromImage(qimg)
if __name__ == '__main__':
app = QApplication(sys.argv)
dialog = Dialog()
sys.exit(dialog.exec_())如果高度和宽度设置为较小的数字,例如3,程序不会崩溃。如果我们在发射前将qimage转换为QPixmap,并将信号类型更改为qpixmap,程序也不会崩溃。该程序最初是为使用opencv从摄像头获取图像而编写的。opencv创建的numpy数组对于较大的图像尺寸也会崩溃。
使用的操作系统为Windows10,pyqt版本为5.12.3
知道坠机的原因是什么吗?
发布于 2020-08-29 13:13:46
在带有PyQt5 5.15的Linux中,我不会重现这个问题,但是这个错误是常见的,因为传递“数据”不会复制信息,而是数据是共享的,所以在某些时候,cv_img和所有相关的对象都会被破坏,包括“数据”,所以当通过信号传输它并在QLabel中设置它时,“数据”是被读取的,但是它不再有保留内存。这种情况下的解决方案是复制"data":
qim = QtGui.QImage(
cv_img.data.tobytes(), w, h, bytes_per_line, QtGui.QImage.Format_RGB888
)或者复制QImage。
return qim.copy()https://stackoverflow.com/questions/63643503
复制相似问题