Python - OpenCV识别条形码、二维码(已封装,拿来即用)

此代码可识别条形码和二维码,已封装好,拿来即用:

复制代码
import cv2
import pyzbar.pyzbar as pyzbar
import numpy
from PIL import Image, ImageDraw, ImageFont


class CodeScan():
    def __init__(self):
        super(CodeScan, self).__init__()

    def decodeDisplay(self, imagex1):
        # 转为灰度图像
        gray = cv2.cvtColor(imagex1, cv2.COLOR_BGR2GRAY)
        barcodes = pyzbar.decode(gray)

        for barcode in barcodes:

            # 提取条形码的边界框的位置
            # 画出图像中条形码的边界框
            (x, y, w, h) = barcode.rect
            cv2.rectangle(imagex1, (x, y), (x + w, y + h), (0, 255, 0), 2)

            # 条形码数据为字节对象,所以如果我们想在输出图像上
            # 画出来,就需要先将它转换成字符串
            barcodeData = barcode.data.decode("utf-8")
            barcodeType = barcode.type

            #不能显示中文
            # 绘出图像上条形码的数据和条形码类型
            #text = "{} ({})".format(barcodeData, barcodeType)
            #cv2.putText(imagex1, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX,5, (0, 0, 125), 2)


            #更换为:
            img_PIL = Image.fromarray(cv2.cvtColor(imagex1, cv2.COLOR_BGR2RGB))

            # 参数(字体,默认大小)
            # font = ImageFont.truetype('fontx/hwst.ttf', 35)
            # 字体颜色(rgb)
            fillColor = (0,255,255)
            # 文字输出位置
            position = (x, y-10)
            # 输出内容
            str = barcodeData

            # 需要先把输出的中文字符转换成Unicode编码形式(  str.decode("utf-8)   )
            draw = ImageDraw.Draw(img_PIL)

            # 转换回OpenCV格式
            imagex1 = cv2.cvtColor(numpy.asarray(img_PIL), cv2.COLOR_RGB2BGR)

            # 向终端打印条形码数据和条形码类型
            print("Result->类别:{0} 内容:{1}".format(barcodeType, barcodeData))
        cv2.imshow("camera", imagex1)

    def detect(self):
        camera = cv2.VideoCapture(0)

        while True:
            # 读取当前帧
            ret, frame = camera.read()
            #print(ret.shape)
            self.decodeDisplay(frame)

            if(cv2.waitKey(5)==27):
                break
        camera.release()
        cv2.destroyAllWindows()


if __name__ == "__main__":
    scan = CodeScan()
    scan.detect()

结果:

相关推荐
lly2024063 小时前
Kotlin 类和对象
开发语言
是苏浙3 小时前
零基础入门C语言之C语言内存函数
c语言·开发语言
zhmhbest3 小时前
Qt 全球峰会 2025:中国站速递 —— 技术中立,拥抱更大生态
开发语言·qt·系统架构
程序员大雄学编程3 小时前
用Python来学微积分30-微分方程初步
开发语言·python·线性代数·数学·微积分
关于不上作者榜就原神启动那件事3 小时前
模拟算法乒乓球
开发语言·c++·算法
我爱学习_zwj3 小时前
App通信:HTTP与JSON全解析
python
机器学习ing.4 小时前
U-Net保姆级教程:从原理到医学细胞分割实战(PyTorch版)!
人工智能·pytorch·python·深度学习·机器学习
88号技师4 小时前
2025年7月一区SCI优化算法-Logistic-Gauss Circle optimizer-附Matlab免费代码
开发语言·算法·数学建模·matlab·优化算法
再睡一夏就好4 小时前
【C++闯关笔记】unordered_map与unordered_set的底层:哈希表(哈希桶)
开发语言·c++·笔记·学习·哈希算法·散列表
yzx9910134 小时前
基于Django的智慧园区管理系统开发全解析
后端·python·django