PyQt5自适应显示图像

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_()

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值