I'm learning to use pyqt5
and qt designer
and I am so confused.
My goal is show a picture when I click a push button because in a future I want to combine all of this with opencv
.
Now I have a window with a push button and an image (it is a label).
Code of the conversion from .ui
to .py
:
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
# Omitted code
self.pushButton.clicked.connect(self.imagen)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "PROG PRUEBAS QT"))
self.pushButton.setText(_translate("MainWindow", "Escala de grises"))
self.label.setText(_translate("MainWindow", "<html><head/><body><p><img src=\":/chchch/img.png\"/></p></body></html>"))
#
def imagen(self):
img = cv.imread('img.png', 0)
cv.imshow('sss', img)
cv.imwrite('pichi.png', img)
#
import noe_rc
But now, when I run it with my Pycharm, it crashes in the import noe_rc
. And if I commented, the image doesn't appear.
PS: If I comment the import the imagen
function works well but the image appears in a new windows.
To display an OpenCV image, you have to convert the image into a QImage
then into a QPixmap
where you can display the image with a QLabel
from PyQt5 import QtGui, QtCore, QtWidgets
import cv2
import sys
class DisplayImageWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(DisplayImageWidget, self).__init__(parent)
self.button = QtWidgets.QPushButton('Show picture')
self.button.clicked.connect(self.show_image)
self.image_frame = QtWidgets.QLabel()
self.layout = QtWidgets.QVBoxLayout()
self.layout.addWidget(self.button)
self.layout.addWidget(self.image_frame)
self.setLayout(self.layout)
@QtCore.pyqtSlot()
def show_image(self):
self.image = cv2.imread('placeholder4.PNG')
self.image = QtGui.QImage(self.image.data, self.image.shape[1], self.image.shape[0], QtGui.QImage.Format_RGB888).rgbSwapped()
self.image_frame.setPixmap(QtGui.QPixmap.fromImage(self.image))
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
display_image_widget = DisplayImageWidget()
display_image_widget.show()
sys.exit(app.exec_())
Using this example image,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With