樹莓派GUI-攝像頭使用-PySidePyQTQMLPythonQt

介紹在樹莓派上使用python和qt開發一個camera程式,開發工具使用PyCharm和QtCreator,開發方式為Pyside2+QML。

1、新建專案

1。1、新建工程

開啟PyCharm,新建工程cameraViewer,如下:

樹莓派GUI-攝像頭使用-PySide/PyQT/QML/Python/Qt

1。2、新增python主程式

在專案中新建main。py 主程式如下:

import osimport sysfrom pathlib import Pathfrom PySide2。QtCore import Qt, QObject, Slot, QCoreApplicationfrom PySide2。QtQml import QQmlApplicationEnginefrom PySide2。QtWidgets import QApplicationclass Controler(QObject): def __init__(self): super()。__init__() @Slot() def exit(self): sys。exit()if __name__==‘__main__’: a = QApplication(sys。argv) a。setOverrideCursor(Qt。BlankCursor) engine = QQmlApplicationEngine() controler = Controler() context = engine。rootContext() context。setContextProperty(“_Controler”,controler) engine。load(os。fspath(Path(__file__)。resolve()。parent / “ui/camera。qml”)) if not engine。rootObjects(): sys。exit(-1) sys。exit(a。exec_())

主程式中,只用於顯示qml介面,並添加了一個退出程式的函式供介面呼叫。

1。3、新增介面檔案

在專案中新增ui資料夾,並在ui資料夾下新建camera。qml檔案,介面如下:

樹莓派GUI-攝像頭使用-PySide/PyQT/QML/Python/Qt

主要參考程式碼如下:

Camera{ id:camera viewfinder { resolution: Qt。size(800, 480) maximumFrameRate: 30 } imageProcessing{ brightness: cameraitem。brightless whiteBalanceMode: CameraImageProcessing。WhiteBalanceFlash } exposure { exposureCompensation: -1。0 exposureMode: Camera。ExposurePortrait } flash。mode: Camera。FlashRedEyeReduction imageCapture{ id:cameraCaptureImage onImageCaptured: { photopreview。source = preview console。log(“captured image:”,preview) } } digitalZoom: sliderZoom。value}VideoOutput{ id:viewer anchors。fill: parent source: camera autoOrientation: true focus: visible fillMode: VideoOutput。PreserveAspectCrop}

主要使用了Camera和VideoOutput元件來進行攝像頭操作,其他部分只是按鍵等操作控制元件使用。

使用camera元件的imageCapture來抓取當前的影象,預設圖片儲存在 樹莓派路徑:/home/pi/Pictures/ 下。

2、執行程式

2。1、上傳程式到樹莓派

在工程上右鍵將這個專案檔案上傳到樹莓派中:

樹莓派GUI-攝像頭使用-PySide/PyQT/QML/Python/Qt

2。2、執行程式

上傳後,在樹莓派對應資料夾中,執行如下命令執行程式:

python3 main。py

如果出現類似:no service found for – “org。qt-project。qt。camera” 這樣的錯誤,需要安裝對應的庫:qml-module-qtmultimedia python3-pyside2。qtmultimedia libqt5multimedia5-plugins

執行後可以看到顯示如下:

樹莓派GUI-攝像頭使用-PySide/PyQT/QML/Python/Qt

可以透過 Brightless來調節亮度,透過Zoom來調節焦距,點選下面的紅色按鈕進行照相,然後左邊按鈕為檢視當前照相的圖片,右邊為檢視所有的圖片檔案。

影片和完整程式碼請差看原文。