如何用QtPy創建Webcam掃碼應用
如何用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)
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)
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掃碼應用