2
\$\begingroup\$

I wanted to write a code that each time I will press some button in my menu, a numpy image array will somehow be created, and this image will show up in a new window.

So the following code is the same purpose, but with the same numpy image array for all new windows (for simplifying).

Which means, for a given numpy image array, each time I will press the 'New' button in my menu, The image will show up as a new window.

I just started playing with PyQt5, so I'd love to get any feedback, because I never did these stuff before (GUI, images), so I might get stuff heavily wrong.

NewNumpyImageWindowMenu.py class (main) pressing 'New' will create a new instance of NewImage (in the other class), and will hold the object in a list, in order for all the windows to still be visible.

import cv2
import sys
from PyQt5 import QtWidgets
from NewNumpyImageWindow import NewImage


class Menu(QtWidgets.QMainWindow):

    def __init__(self, numpy_img):
        super().__init__()
        newAct = QtWidgets.QAction('New', self)
        self.numpyPicture = numpy_img
        newAct.triggered.connect(self.new_image_window)
        toolbar = self.addToolBar('Exit')
        toolbar.addAction(newAct)
        self.images_list = []
        self.setGeometry(300, 300, 350, 250)
        self.show()

    def new_image_window(self):
        self.images_list.append(NewImage(self.numpyPicture))


if __name__ == '__main__':
    currentNumpyImage = cv2.imread("capture.png") # some picture
    app = QtWidgets.QApplication(sys.argv) # converts picture to numpy array
    menu = Menu(currentNumpyImage)
    sys.exit(app.exec_())

NewNumpyImageWindow.py class

import cv2
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel
from PyQt5.QtGui import QPixmap, QImage


class NewImage(QWidget):

    def __init__(self, numpy_image):
        super().__init__()
        label = QLabel(self)
        pixmap = self.convert_numpy_img_to_qpixmap(numpy_image)
        label.setPixmap(pixmap)
        self.resize(pixmap.width(), pixmap.height())
        self.show()

    @staticmethod
    def convert_numpy_img_to_qpixmap(np_img):
        height, width, channel = np_img.shape
        bytesPerLine = 3 * width
        return QPixmap(QImage(np_img.data, width, height, bytesPerLine, QImage.Format_RGB888).rgbSwapped())


# if __name__ == '__main__':
#     app = QApplication(sys.argv)
#     current_numpy_Image = cv2.imread("capture.png")
#     window = NewImage(current_numpy_Image)
#     sys.exit(app.exec_())

Any help would be appreciated :)

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.