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

下面是一个PyQt5的示例代码,可以实现将图像自适应窗口大小: ```python import sys from PyQt5.QtGui import QPixmap from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout class ImageWindow(QWidget): def __init__(self): super().__init__() self.setWindowTitle("Image Window") self.setGeometry(100, 100, 600, 400) # 创建标签 self.label = QLabel(self) self.label.setScaledContents(True) # 加载图像 self.image = QPixmap("example.jpg") self.label.setPixmap(self.image) # 创建布局并添加标签 layout = QVBoxLayout() layout.addWidget(self.label) self.setLayout(layout) # 重写resizeEvent方法 def resizeEvent(self, event): # 获取窗口大小 size = self.size() # 将图像缩放到窗口大小并更新标签 self.label.setPixmap(self.image.scaled(size, aspectRatioMode=QtCore.Qt.KeepAspectRatio)) if __name__ == "__main__": app = QApplication(sys.argv) window = ImageWindow() window.show() sys.exit(app.exec_()) ``` 在这个例子中,我们创建了一个名为ImageWindow的窗口。我们将一个QLabel控件添加到窗口中,用于显示图像。我们使用QPixmap加载一个名为example.jpg的图像,并将其设置为标签的图像。 我们还重写了resizeEvent方法。这个方法在每次窗口大小发生变化时都会被调用。在这个方法中,我们获取窗口的新大小,然后将图像缩放到该大小,并将其设置为标签的图像。我们使用了QPixmap的scaled方法来缩放图像,保持纵横比。 最后,我们创建了一个应用程序并显示了我们的ImageWindow窗口。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值