天天看點

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)