1. 程式人生 > >如何用QtPy創建Webcam掃碼應用

如何用QtPy創建Webcam掃碼應用

decode imshow capture nor exe while 放置 map label

之前分享了如何用QtPy和Dynamsoft Barcode Reader創建一個簡單的桌面應用, 通過加載一張圖片來識別條形碼。這篇文章要分享如何加上攝像頭的支持做實時掃碼。

如何用Python和PyQt代碼顯示Camera視頻流

要獲取視頻流,最簡單的方法就是用OpenCV:

pip install opencv-python
用OpenCV來顯示視頻流的代碼很簡單,只需要一個無限循環:

import cv2
vc = cv2.VideoCapture(0)
while True:
rval, frame = vc.read()
cv2.imshow("Camera View", frame)

現在要解決的問題就是把OpenCV獲取的視頻幀數據通過Qt的Widget顯示出來。在Qt中,不能使用循環,要用timer:

def init(self):

Create a timer.

    self.timer = QTimer()
    self.timer.timeout.connect(self.nextFrameSlot)

def nextFrameSlot(self):
rval, frame = self.vc.read()
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
image = QImage(frame, frame.shape[1], frame.shape[0], QImage.Format_RGB888)

pixmap = QPixmap.fromImage(image)
self.label.setPixmap(pixmap)

    results = dbr.decodeBuffer(frame, 0x3FF | 0x2000000 | 0x4000000 | 0x8000000 | 0x10000000)
    out = ‘‘
    index = 0
    for result in results:
        out += "Index: " + str(index) + "\n"
        out += "Barcode format: " + result[0] + ‘\n‘
        out += "Barcode value: " + result[1] + ‘\n‘
        out += ‘-----------------------------------\n‘
        index += 1

    self.results.setText(out)

這裏註意下要把顏色空間從BGR轉成RGB再放到QImage中。

創建一個QHBoxLayout來放置兩個button:

button_layout = QHBoxLayout()

btnCamera = QPushButton("Open camera")
btnCamera.clicked.connect(self.openCamera)
button_layout.addWidget(btnCamera)

btnCamera = QPushButton("Stop camera")
btnCamera.clicked.connect(self.stopCamera)
button_layout.addWidget(btnCamera)

layout.addLayout(button_layout)
點擊button之後觸發和停止timer:

def openCamera(self):
self.vc = cv2.VideoCapture(0)

vc.set(5, 30) #set FPS

    self.vc.set(3, 640) #set width
    self.vc.set(4, 480) #set height

    if not self.vc.isOpened(): 
        msgBox = QMessageBox()
        msgBox.setText("Failed to open camera.")
        msgBox.exec_()
        return

    self.timer.start(1000./24)

def stopCamera(self):
self.timer.stop()
監聽關閉事件:

def closeEvent(self, event):

    msg = "Close the app?"
    reply = QMessageBox.question(self, ‘Message‘, 
                    msg, QMessageBox.Yes, QMessageBox.No)

    if reply == QMessageBox.Yes:
        event.accept()
        self.stopCamera()
    else:
        event.ignore()

最後運行效果:

如何用QtPy創建Webcam掃碼應用