自学内容网 自学内容网

树莓派应用--AI项目实战篇来啦-14.基于OpenCV二维码识别

1. 介绍

        二维码识别是目前最为流行的支付方式之一,可以在各种场景下使用到二维码,本实验是通过使用 pyzbar 包实现,因为pyzbar 是最为老牌使用最为频繁的条码、二维码识别库,该模块是一个日本的 author 开源的一个二维码识别库。

2. 二维码介绍

        二维码又称二维条码,常见的二维码为QR Code,QR全称Quick Response,是一个近几年来移动设备上超流行的一种编码方式,它比传统的Bar Code条形码能存更多的信息,也能表示更多的数据类型。
        二维条码/二维码(2-dimensional bar code)是用某种特定的几何图形按一定规律在平面(二维方向上)分布的、黑白相间的、记录数据符号信息的图形,在代码编制上巧妙地利用构成计算机内部逻辑基础的 “0”、“1”比特流的概念。使用若干个与二进制相对应的几何形体来表示文字数值信息,通过图象输入设备或光电扫描设备自动识读以实现信息自动处理,它具有条码技术的一些共性:每种码制有其特定的字符集。每个字符占有一定的宽度:具有一定的校验功能等。同时还具有对不同行的信息自动识别功能,及处理图形旋转变化点。

3.Pyzbar库安装

        使用以下命令在命令行中安装 pybar 库:

sudo pip3 install pyzbar

4. 源程序代码

        运行程序后,程序实现两部分内容,第一是使用现有的图片识别二维码并打印显示,第二是在摄像头的图像中放置二维码图片,程序将使用 Pyzbar 库中的pyzbar. decode()函数来识别二维码,并实时通过绘画函数画出识别的方块和打印识别的内容。

# 载入必要的库
import cv2
import numpy as np
from pyzbar import pyzbar
import imutils
import sys
import time

# 线程函数操作库
import threading # 线程
import ctypes
import inspect

# 线程结束代码
def _async_raise(tid, exctype):
    tid = ctypes.c_long(tid)
    if not inspect.isclass(exctype):
        exctype = type(exctype)
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
    if res == 0:
        raise ValueError("invalid thread id")
    elif res != 1:
        ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
        raise SystemError("PyThreadState_SetAsyncExc failed")
        
def stop_thread(thread):
    _async_raise(thread.ident, SystemExit)



def bgr8_to_jpeg(value, quality=75):
    return bytes(cv2.imencode('.jpg', value)[1])
    
import traitlets
import ipywidgets.widgets as widgets
from IPython.display import display

QR_img = widgets.Image(format='jpeg', width=320, height=240)
testQRCode_img = widgets.Image(format='jpeg', width=320, height=240)

dispaly_img = widgets.HBox([testQRCode_img,QR_img])
display(dispaly_img)

# 载入图片QR二维码
import libcamera
from picamera2 import Picamera2

picamera = Picamera2()
config = picamera.create_preview_configuration(main={"format": 'RGB888', "size": (320, 240)},
                                               raw={"format": "SRGGB12", "size": (1920, 1080)})
config["transform"] = libcamera.Transform(hflip=0, vflip=1)
picamera.configure(config)
#picamera.set_controls({"ExposureTime":info['ExposureTime'], "AnalogueGain":info['AnalogueGain'], "AwbMode":info['AwbMode'], "FrameDurationLimits": (100000, 100000)})
#picamera.set_controls({"ExposureTime": 50000, "AnalogueGain": 1.0, "ColourGains": (2.522, 1.897)})
picamera.start()


# 摄像头二维码实时识别
ef Video_display():
    while True:
        frame1 = picamera.capture_array()
        frame = imutils.resize(frame1, width=400)
        barcodes = pyzbar.decode(frame)
        for barcode in barcodes:
            (x, y, w, h) = barcode.rect
            cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)
            barcodeData = barcode.data.decode("utf-8")
            barcodeType = barcode.type
            text = "{} ({})".format(barcodeData, barcodeType)
            cv2.putText(frame, text, (x, y+20),cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)  
            print(text) 
            
        QR_img.value = bgr8_to_jpeg(frame) # 实时显示图像


# 开始线程
t = threading.Thread(target=Video_display)
t.setDaemon(True)
t.start()

# 结束线程
stop_thread(t)

将手机淘宝二维码对准摄像头,则检测出来对应网址:


原文地址:https://blog.csdn.net/weixin_44845743/article/details/142829737

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!