pyside2實時顯示realsense深度攝像頭數據

pyside2實時顯示realsense深度攝像頭數據

需求

讀取realsense每幀圖像顯示在pyside的QLabel上,使用的realsenese攝像頭型號爲D415

安裝pyside2指令

pip install pyside2

實現流程

1.引入依賴

# 這是我頁面文件引入的依賴
import time
import subprocess
import threading as th
from PySide2.QtCore import (QCoreApplication, QDate, QDateTime, QMetaObject,
    QObject, QPoint, QRect, QSize, QTime, QUrl, Qt, Signal, Slot)
from PySide2.QtGui import (QBrush, QColor, QConicalGradient, QCursor, QFont,
    QFontDatabase, QIcon, QKeySequence, QLinearGradient, QPalette, QPainter,
    QPixmap, QRadialGradient, QImage)
from PySide2.QtWidgets import *
import pyrealsense2 as rs
import numpy as np
import json

2.創建發送圖像信號

# 在對應的頁面類的內部
# 例如第六步的Ui_Main類內部,與def定義的函數同級
dis_update = Signal(QPixmap)

3.定義調用realsense函數

def open_realsense(self):
        pipeline = rs.pipeline()
        config = rs.config()
        config.enable_stream(rs.stream.depth, 1280, 720, rs.format.z16, 30)
        config.enable_stream(rs.stream.color, 1280, 720, rs.format.bgr8, 30)

        profile = pipeline.start(config)
        frames = pipeline.wait_for_frames()
        color_frame = frames.get_color_frame()
        # Color Intrinsics
        intr = color_frame.profile.as_video_stream_profile().intrinsics

        align_to = rs.stream.color
        align = rs.align(align_to)
        while True:
            frames = pipeline.wait_for_frames()
            aligned_frames = align.process(frames)

            aligned_depth_frame = aligned_frames.get_depth_frame()
            color_frame = aligned_frames.get_color_frame()
            if not aligned_depth_frame or not color_frame:
                continue
            c = np.asanyarray(color_frame.get_data())
            qimage = QImage(c, 1280, 720, QImage.Format_BGR888)
            pixmap = QPixmap.fromImage(qimage)
            self.dis_update.emit(pixmap)
            time.sleep(DELAY)
        pipeline.stop()

4.定義子線程執行開啓攝像頭

def open_camera(self):	
	# target選擇開啓攝像頭的函數
	t = th.Thread(target=self.open_realsense)
	t.start()

5.將圖像信號更新到QLabel

def camera_view(self, c):
		# 調用setPixmap函數設置顯示Pixmap
        self.label_12.setPixmap(c)
        # 調用setScaledContents將圖像比例化顯示在QLabel上
        self.label_12.setScaledContents(True)

6.定義信號與槽函數連接

在頁面對應的類與Ui設置函數裏設置信號與槽函數連接

# 你的界面類
class Ui_Main(QObject):
	def setupUi(self, Main):
		# 信號與槽函數綁定
		self.dis_update.connect(self.camera_view)

7.主線程調用

class Main(QMainWindow):
    def __init__(self):
        super(Main, self).__init__()
        self.ui = Ui_Main()
        self.ui.setupUi(self)

    def updateStatusBar(self, str):
        self.ui.statusBar.showMessage(str)

if __name__ == "__main__":
    app = QApplication([])
    widget = Main()
    widget.showFullScreen()
    widget.updateStatusBar("系統已準備,  Avatar version: 1.0")
    widget.show()
    widget.ui.open_camera()
    sys.exit(app.exec_())

測試效果

測試效果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章