import cv2
import numpy as np
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtWidgets import QLabel, QApplication, QMainWindow, QWidget, QHBoxLayout
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
# 创建一个QWidget并通过setCentralWidget将其设置为主窗口
widget = QWidget()
self.setCentralWidget(widget)
# 创建一个QHBoxLayout并将其设置为QWidget的布局
layout = QHBoxLayout()
widget.setLayout(layout)
# 创建一个QLabel控件并将其添加至布局
self.label = QLabel()
layout.addWidget(self.label)
# 读取图像
self.image = cv2.imread('example.jpg')
# 显示图像
self.show_image(self.image)
def show_image(self, image):
# 将图像转换为QImage
height, width, channel = image.shape
bytesPerLine = 3 * width
qImg = QImage(image.data, width, height, bytesPerLine, QImage.Format_RGB888)
# 计算QPixmap的大小以使图像自适应QLabel控件大小
pixmap = QPixmap.fromImage(qImg)
scaled_pixmap = pixmap.scaled(self.label.width(), self.label.height(), aspectRatioMode=QtCore.Qt.KeepAspectRatio)
# 将QPixmap设置为QLabel控件的图像
self.label.setPixmap(scaled_pixmap)
app = QApplication([])
win = MainWindow()
win.show()
app.exec_()
PyQt5自适应显示图像
最新推荐文章于 2024-04-30 18:18:35 发布