我在重复使用 QTimer 时遇到问题
- 生成一个高×宽×3的numpy数组
- 将 numpy 数组转换为 Qt 友好的图像,并且
- 在 Qt 主窗口中显示图像
(最终图像不会是随机的。)
这是相关代码。
import numpy as np
from scipy.misc.pilutil import toimage
from PIL.ImageQt import ImageQt
def nparrayToQPixmap(arrayImage):
pilImage = toimage(arrayImage)
qtImage = ImageQt(pilImage)
qImage = QtGui.QImage(qtImage)
qPixmap = QtGui.QPixmap(qImage)
return qPixmap
class DetectionWidget(QtGui.QWidget):
def __init__(self):
super(DetectionWidget, self).__init__()
self.timer = QtCore.QTimer()
self.init_UI()
def init_UI(self):
self.setFixedSize(self.WIDTH, self.HEIGHT)
self.label = QtGui.QLabel(self)
self.label.resize(self.WIDTH, self.HEIGHT)
self.timer.timeout.connect(self.onTimeout)
self.timer.start(1000)
def onTimeout(self):
npImage = np.random.rand(self.HEIGHT, self.WIDTH, 3)
qPixmap = nparrayToQPixmap(npImage)
self.label.setPixmap(qPixmap)
这显示了第一张图像,但 Python 分割在第二次迭代时出现 self.label.setPixmap(qPixmap)
错误。另外,即使我不更新标签而是使用 qPixmap.save(...) 保存图像,它也会出现段错误,这让我认为生成的 qPixmap 在第一个之后以某种方式损坏了迭代。
我将不胜感激任何帮助!
最佳答案
这似乎是由于 QImage
到 QPixmap
转换中的错误所致。只要 QImage
格式正确,该代码就可以工作。
qImage = QtGui.QImage(qtImage)
变成了
qImage = QtGui.QImage(qtImage).convertToFormat(QtGui.QImage.Format_ARGB32)
关于python - 使用 NumPy 和 PyQt4 重复显示随机噪声图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15744087/