pyqt5--加載圖片

1. 準備工做:python

1.1 新建readimage.ui, main.pyapp

2. 設計UIide

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>Dialog</class>
 <widget class="QDialog" name="Dialog">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>312</width>
    <height>300</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Dialog</string>
  </property>
  <widget class="QPushButton" name="load_btn">
   <property name="geometry">
    <rect>
     <x>14</x>
     <y>20</y>
     <width>281</width>
     <height>23</height>
    </rect>
   </property>
   <property name="text">
    <string>Load Image</string>
   </property>
  </widget>
  <widget class="QLabel" name="img_label">
   <property name="geometry">
    <rect>
     <x>10</x>
     <y>50</y>
     <width>291</width>
     <height>241</height>
    </rect>
   </property>
   <property name="layoutDirection">
    <enum>Qt::LeftToRight</enum>
   </property>
   <property name="frameShape">
    <enum>QFrame::Box</enum>
   </property>
   <property name="text">
    <string>Image</string>
   </property>
   <property name="alignment">
    <set>Qt::AlignCenter</set>
   </property>
  </widget>
 </widget>
 <resources/>
 <connections/>
</ui>

3. main.py詳細代碼以下ui

import sys
from PyQt5 import QtWidgets
from PyQt5.QtGui import QImage,QPixmap
from PyQt5.uic import loadUi
import cv2
class mywin(QtWidgets.QDialog):
    def __init__(self):
        super(mywin,self).__init__()
        loadUi('readimage.ui',self)
        self.load_btn.clicked.connect(self.loadclicked)

    def loadclicked(self):
        self.loadimage('1.jpg')

    def loadimage(self,path):
        self.image = cv2.imread(path)
        self.showimage()

    def showimage(self):
        print(self.image.shape)
        qimageformat = QImage.Format_Indexed8
        if len(self.image.shape)==3:
            if self.image.shape[2]==4:
                qimageformat = QImage.Format_RGBA8888
            else:
                qimageformat = QImage.Format_RGB888
        img = QImage(self.image,self.image.shape[1],self.image.shape[0],self.image.strides[0],qimageformat)
        img = img.rgbSwapped()
        self.img_label.setPixmap(QPixmap.fromImage(img))

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    window = mywin()
    window.show()
    window.setWindowTitle("window")
    #window.setGeometry(100,100,400,300)
    sys.exit(app.exec_())
相關文章
相關標籤/搜索