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()

结果:

相关推荐
C++ 老炮儿的技术栈19 分钟前
手动实现strcpy
c语言·开发语言·c++·算法·visual studio
仟濹32 分钟前
「Matplotlib 入门指南」 Python 数据可视化分析【数据分析全栈攻略:爬虫+处理+可视化+报告】
python·信息可视化·数据分析·matplotlib
Joomla中文网43 分钟前
joomla5去掉后台PHP版本警告信息
开发语言·php
大磕学家ZYX1 小时前
使用Nodejs尝试小程序后端服务编写:简单的待办事项管理demo
开发语言·javascript·小程序·node.js
先做个垃圾出来………1 小时前
什么是装饰器?
开发语言·python
ComputerInBook1 小时前
理解 C++ 的 this 指针
开发语言·c++·指针·this·this指针
我真不会起名字啊1 小时前
Qt如何生成和使用DLL动态链接库
开发语言·qt
风靡晚1 小时前
用于汽车毫米波雷达的四维高分辨率点云图像
人工智能·算法·机器学习·计算机视觉·汽车·信息与通信·信号处理
ayuan01192 小时前
Day54打卡 @浙大疏锦行
python
小马敲马2 小时前
[3.4] 集合通信 理论+代码
开发语言·c++·人工智能·算法·性能优化