pyqt显示图片的两种方法

方法一:利用QLabel

import sys
from PyQt5.QtWidgets import (QWidget, QHBoxLayout, QLabel, QApplication)
from PyQt5.QtGui import QPixmap


class Example (QWidget):
    def __init__(self):
        super ().__init__()
        self.initUI ()

    def initUI(self):
        lbl = QLabel(self)
        pixmap = QPixmap(filename)  # 按指定路径找到图片
        lbl.setPixmap (pixmap)  # 在label上显示图片
        lbl.setScaledContents (True)  # 让图片自适应label大小
        hbox.addWidget(lbl)

        self.setLayout(hbox)
        self.move (300, 200)
        self.setWindowTitle ('pic')
        self.show ()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example ()
    sys.exit (app.exec_())

方法二:利用QGraphicsView

from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QMainWindow, QApplication, QGraphicsScene, QGraphicsPixmapItem
from PyQt5.QtGui import QImage, QPixmap
import matplotlib.pyplot as plt
from my_gui.trytry import Ui_Form


class picturezoom(QMainWindow, Ui_Form):
	'''
	Ui_Form里的QGraphicsView是这样的:
	self.segpicView = QtWidgets.QGraphicsView(Form)
    self.segpicView.setGeometry(QtCore.QRect(40, 120, 351, 341))
    self.segpicView.setObjectName("segpicView")
    '''
    def __init__(self, parent=None):
        """
        Constructor
        @param parent reference to the parent widget
        @type QWidget
        """
        super(picturezoom, self).__init__(parent)
        self.setupUi(self)
        img = plt.imread(filename)  # 读取图像

        x = img.shape[1]  # 获取图像大小
        y = img.shape[0]

        frame = QImage(img, y, x, x*3,QImage.Format_RGB888)
        # 此处x*3最好加上,否则图片会出现倾斜
        pix = QPixmap.fromImage(frame)
        item = QGraphicsPixmapItem(pix)  # 创建像素图元
        
        scene = QGraphicsScene()  # 创建场景
        scene.addItem(item)
        self.graphicsView.setScene(scene)  # 将场景添加至视图


if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    piczoom = picturezoom()
    piczoom.show()
    app.exec_()

小小总结一下:
其实还是QLabel显示图像的过程比较简单。
主要记住这几行代码

# 从本地读图
pixmap = QPixmap(filename)  # 按指定路径找到图片
lbl.setPixmap (pixmap)  # 在label上显示图片
# np数组生成的图
len_x = show_image.shape[1]  # 获取图像大小
wid_y = show_image.shape[0]
frame = QImage(show_image.data, len_x, wid_y, len_x * 3, QImage.Format_RGB888)  # 此处如果不加len_x*3,就会发生倾斜
pix = QPixmap.fromImage(frame)

方法3:利用pyqtgraph.ImageView

#image为图片

imv = pg.ImageView()
imv.setImage(image.T)
imv.view.setBackgroundColor((240, 240, 240))
imv_hist = imv.getHistogramWidget()
imv_hist.setBackground((240, 240, 240))
pg.setConfigOptions(antialias=True)

self.draw_Layout.addWidget(imv)
  • 20
    点赞
  • 140
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值