我想使用python的pyqt5编写一个QLabel显示图片,直接读取图片为QPixmap后用setPixmap显示图片的时候正常,在使用PIL.image读取图片为PIL.Image类型后再用ImageQt.toqpixmap转换为QPixmap后就无法显示图片了,程序跑了直接退出也不报错,debug也是直接退出。这个有什么解决方案吗。ps:不直接使用Qpixmap是因为某个项目里面用到PIL.Image进行运算,运算后需要转换为Qpixmap进行显示
补充,我自己在找解决办法的时候发现,我将PIL.Image类型转化为ndarray后直接用matplotlib进行显示是可以的,但是转换为Pixmap又不行了。后面我尝试随机生成一个RGB数据数组转换为Pixmap发现也无法显示。由于程序直接退出不报错,不知道问题所在,下面是我的测试代码。
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(400, 300)
self.label = QtWidgets.QLabel(Form)
self.label.setGeometry(QtCore.QRect(60, 90, 261, 151))
self.label.setStyleSheet("background-color:rgb(85, 170, 255)")
self.label.setObjectName("label")
self.pushButton = QtWidgets.QPushButton(Form)
self.pushButton.setGeometry(QtCore.QRect(50, 30, 75, 23))
self.pushButton.setObjectName("pushButton")
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.label.setText(_translate("Form", "Label"))
self.pushButton.setText(_translate("Form", "PushButton"))
import sys
from PIL import Image, ImageQt
from PyQt5 import QtGui, QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow
import numpy as np
from testLabel import Ui_Form
import cv2
class MyMainForm(QMainWindow, Ui_Form):
def __init__(self):
super().__init__()
self.setupUi(self)
self.pushButton.clicked.connect(self.openPicture)
def openPicture(self):
# pix = Image.open('result.jpg')
# pix = ImageQt.toqpixmap(pix)
# img = cv2.imread('result.jpg')
# pix = QtGui.QPixmap('result.jpg')
# self.label.setScaledContents(True)
img = np.random.randint(0, 255, [10, 60, 3], np.uint8)
img = img.astype("uint8")
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = QtGui.QImage(img, img.shape[1], img.shape[0], img.shape[1] * 3, QtGui.QImage.Format_RGB888)
self.label.setPixmap(img)
if __name__ == '__main__':
QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
app = QtWidgets.QApplication(sys.argv)
my = MyMainForm()
my.show()
sys.exit(app.exec_())