如何使用PyQt5在QWidget上设置numpy数组图像

时间:2017-07-13 13:15:53

标签: python image qt numpy pyqt5

我正在从相机中读取一个图像作为一个numpy阵列。我的目标是将它放在pyqt5的Qwidget中并在我的mainwindow gui程序上打印,但是我收到以下错误:

TypeError: QPixmap(): argument 1 has unexpected type 'numpy.ndarray'

以下是代码:

from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from epics import PV
import numpy as np

class PanoramicGUI:
    def __init__(self):
        self.MainWindow = uic.loadUi('panoramicGUI.ui')

        self.MainWindow.SavePositionButton. clicked.connect(self.save_image)

    def save_image(self):
        detectorData = PV("CAMERA:DATA")
        self.data = detectorData.get()
        self.data = np.array(self.data).reshape(2048,2048).astype(np.int32)
        print(self.data)

        img = PrintImage(QPixmap(self.data))

        self.MainWindow.WidgetHV1X1.setLayout(QtWidgets.QVBoxLayout())
        self.MainWindow.WidgetHV1X1.layout().addWidget(img)

class PrintImage(QWidget):
    def __init__(self, pixmap, parent=None):
        QWidget.__init__(self, parent=parent)
        self.pixmap = pixmap

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.drawPixmap(self.rect(), self.pixmap)

if __name__ == "__main__":

    app = QtWidgets.QApplication(sys.argv)
    panoramic = PanoramicGUI()
    panoramic.MainWindow.show()
    app.exec_()

有人可以帮助我吗?

此致

加布里埃尔。

1 个答案:

答案 0 :(得分:1)

有很多方法可以解决这个问题。

一种选择是通过提供文件路径直接从磁盘加载图像。所以你会img = PrintImage(QPixmap(FILE_PATH)) FILE_PATH是一些字符串而不是一个numpy数组。有关更完整的示例,请参阅以下链接:https://www.tutorialspoint.com/pyqt/pyqt_qpixmap_class.htm

如果你真的想用numpy数组来处理它,那么你需要先创建一个QtGui.QImage()对象,然后将它传递给你的QtGui.QPixmap()对象,而不是直接传递给numpy数组。根据{{​​1}}的文档,您需要设置数据的格式(如果数据尚未由QtGui.QImage()识别的格式。所以以下内容应该有效:

QtGui.QImage()

#Initialze QtGui.QImage() with arguments data, height, width, and QImage.Format self.data = np.array(self.data).reshape(2048,2048).astype(np.int32) qimage = QtGui.QImage(self.data, self.data.shape[0],self.data.shape[1],QtGui.QImage.Format_RGB32) img = PrintImage(QPixmap(qimage)) 的最后一个参数可以从这里的文档列表http://srinikom.github.io/pyside-docs/PySide/QtGui/QImage.html#PySide.QtGui.PySide.QtGui.QImage.Format

更改为您想要的任何内容

对于与QtGui.QImage()相关的所有事情,最终链接总体上非常好。