Gabriel Schubert
Gabriel Schubert

Reputation: 175

How to set an numpy array image on a QWidget using PyQt5

I'm reading an image from my camera as a numpy array. My aim is to put it inside a Qwidget from pyqt5 and print on my mainwindow gui program, but i'm getting the following error:

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

Here is the code:

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_()

Can someone help me?

Regards,

Gabriel.

Upvotes: 2

Views: 10371

Answers (1)

rigby
rigby

Reputation: 233

There are multiple ways to go about this.

One option is to load the image straight from disk by providing a file path. So you would have img = PrintImage(QPixmap(FILE_PATH)) where FILE_PATH is some string instead of a numpy array. For a more complete example see the following link: https://www.tutorialspoint.com/pyqt/pyqt_qpixmap_class.htm

If you really want to handle it with a numpy array, then you need to create a QtGui.QImage() object first and pass that into your QtGui.QPixmap() object instead of a numpy array directly. Per the documentation of QtGui.QImage(), you need to set the format of the data if it is not already in a recognized format by QtGui.QImage(). So the following should work:

#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))

The last argument for QtGui.QImage() can be changed to whatever you desire among the list from the documentation here http://srinikom.github.io/pyside-docs/PySide/QtGui/QImage.html#PySide.QtGui.PySide.QtGui.QImage.Format

That final link is really good in general for all things QtGui related.

Upvotes: 2

Related Questions