如何用QtPy创建Webcam扫码应用

之前分享了如何用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()

最后运行效果:

源码

https://www.codepool.biz/python-pyqt-read-barcode-webcam.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
公众号vue页面调用手机摄像头扫码功能,需要使用vue的相关组件和插件。首先,需要使用vue-router进行路由控制,将扫码页面添加到路由中。在扫码页面中,需要使用Vue Quagga组件,该组件是基于QuaggaJS开发的二维码扫描器,能够轻松地在移动设备上运行。同时,还需要使用vue-web-cam组件实现调用手机摄像头的功能。该组件支持通过getUserMedia API调用前置或后置相机,并可以实时预览相机画面。具体实现过程如下: 1. 安装Vue Quagga和vue-web-cam插件 通过npm安装Vue Quagga和vue-web-cam插件: ``` npm install vue-quagga vue-web-cam ``` 2. 在扫码页面中引入组件 在扫码页面的Vue组件中,引入Vue Quagga组件以及vue-web-cam组件: ``` import VueQuagga from 'vue-quagga' import VueWebCam from 'vue-web-cam' export default { components: { VueQuagga, VueWebCam } // ... } ``` 3. 在扫码页面中添加Quagga配置项 在扫码页面的Vue组件中,添加Quagga的配置项,并设置回调函数处理扫码结果。例如: ``` <template> <div> <vue-web-cam ref="webcam" width="100%" :videoConstraints="{facingMode:'environment'}"></vue-web-cam> <vue-quagga v-if="showCamera" :config="quaggaConfig" @detect="detectHandler"></vue-quagga> </div> </template> <script> export default { data () { return { quaggaConfig: { inputStream: { name: "Live", type: "LiveStream", constraints: { width: {min: 640}, height: {min: 480}, facingMode: "environment" } }, decoder: { readers: ['ean_reader', 'upc_reader'] }, locate: true }, showCamera: true } }, methods: { detectHandler (result) { console.log(result.codeResult.code) } } } </script> ``` 4. 在扫码按钮点击事件中开始调用摄像头 在扫码按钮的点击事件中,使用Vue Web Cam组件的start()方法开始调用前置摄像头: ``` <template> <div> <button @click="startScan">开始扫码</button> <vue-web-cam ref="webcam" width="100%" :videoConstraints="{facingMode:'environment'}"></vue-web-cam> <vue-quagga v-if="showCamera" :config="quaggaConfig" @detect="detectHandler"></vue-quagga> </div> </template> <script> export default { data () { return { quaggaConfig: { // ... }, showCamera: false } }, methods: { startScan () { this.showCamera = true this.$refs.webcam.start() }, detectHandler (result) { console.log(result.codeResult.code) } } } </script> ``` 至此,公众号vue页面调用手机摄像头扫码功能已经实现。用户在点击页面上的扫码按钮后,会弹出调用前置摄像头的提示框,扫码识别成功后会将结果输出到控制台上。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值