之前分享了如何用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()
最后运行效果:
原文地址:http://blog.51cto.com/14009535/2348452