from PyQt5 import QtCore, QtGui
import sys
import cv2
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
main_win = QtWidgets.QMainWindow()
main_win.setWindowTitle("QLabel图像显示演示")
image_label = QtWidgets.QLabel()
txt_label = QtWidgets.QLabel()
# 方法一:使用QtGui直接显示
# pixmap = QtGui.QPixmap("./image/img1.png")
# pix = pixmap.scaled(QtCore.QSize(640, 640), QtCore.Qt.KeepAspectRatio) # 自动保持比例放缩方式
# 方法二:使用cv2显示
src = cv2.imread("./image/img1.png") # BGR
image = cv2.cvtColor(src, cv2.COLOR_BGR2RGB) # 将BGR转为RGB
h, w, c = image.shape
img = QtGui.QImage(image.data, w, h, 3*w, QtGui.QImage.Format_RGB888)
pixmap = QtGui.QPixmap(img)
pix = pixmap.scaled(QtCore.QSize(640, 640), QtCore.Qt.KeepAspectRatio) # 自动保持比例放缩方式
image_label.setPixmap(pix) # 设置图像显示
image_label.setAlignment(QtCore.Qt.AlignCenter) # label上的内容居中显示
image_label.setStyleSheet("background-color:blue;color:green") # 背景颜色设置
# main_win.setCentralWidget(image_label)
txt_label.setText("Hello, PyQT5")
txt_label.setAlignment(QtCore.Qt.AlignCenter) # label上居中显示
txt_label.setStyleSheet("background-color:pink;color:green") # 背景颜色设置
font = QtGui.QFont()
font.setBold(True)
font.setPointSizeF(32)
txt_label.setFont(font)
panel = QtWidgets.QWidget()
vboxlayout = QtWidgets.QVBoxLayout()
vboxlayout.addWidget(txt_label)
vboxlayout.addWidget(image_label)
panel.setLayout(vboxlayout)
main_win.setCentralWidget(panel)
main_win.setMinimumSize(1080, 720)
main_win.show()
app.exec_()