树莓派应用--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()函数来识别二维码,并实时通过绘画函数画出识别的方块和打印识别的内容。

python 复制代码
# 载入必要的库
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)

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

相关推荐
To_OC1 小时前
大模型蒸馏是啥?说白了就是大厨带徒弟的学问
人工智能·llm·agent
新手来了@click2 小时前
JAVA+AI 简化开发操作|文章被 AI Agent 技术社区收录分享
人工智能
GuWenyue2 小时前
Cursor黑盒拆解!1套LangChain.js手写Mini编程Agent,自动生成React项目,效率提升60%
前端·数据库·人工智能
GuWenyue2 小时前
传统Agent工具两大痛点!300行代码落地MCP跨语言工具,彻底解耦LLM与工具
前端·人工智能·算法
老云讲算力市场3 小时前
WAIC首日观察:国产算力与机器人加速落地,奇点算力迎来产业新机遇
人工智能·科技
糖果店的幽灵3 小时前
【DeepAgents 从入门到精通】Context Management 上下文管理
java·人工智能·后端·spring·中间件·langgraph·deepagents
小林ixn3 小时前
大模型随机说话的秘密:Temperature 和 Top K 深度解析,LangChain 实战调优
人工智能·langchain
ALINX技术博客3 小时前
ALINX 亮相 2026 WAIC 世界人工智能大会,展示 AI 视觉 FPGA+GPU 异构计算与电子后视镜解决方案
人工智能·ai·fpga·世界人工智能大会·电子后视镜
程序员老猫3 小时前
当 AI 能写 80% 的代码时,后端工程师的核心价值还剩什么?
人工智能
想会飞的蒲公英4 小时前
计算机怎样读取中文文本:编码、清洗与标准化
人工智能·python·自然语言处理