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)

你可能感兴趣的:(pyqt,python,pyqt5)