用python识别条形码,二维码并且定位标注

2 篇文章 0 订阅
1 篇文章 0 订阅

 

原理很简单用OpenCV处理图片pyzbar识别条形码

   python里面有一个包pyzbar可以用识别二维码和条形码,我们再结合OpenCV处理图片的功能就可以标注出二维码位置内容

  我们生活中的常见的带有二维码和条形码的图片如下图

需要导的包有

import pyzbar.pyzbar as pyzbar
import numpy
from PIL import Image, ImageDraw, ImageFont
import cv2

首先用OpenCV读取图片处理图片

    frame= cv2.imread('样本图.jpg')

    # 转为灰度图像
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

灰度后的图像就可以给pyzbar解码了

barcodes = pyzbar.decode(gray)

 打印一下barcodes

[Decoded(data=b'http://weibo.com/u/3225432640', type='QRCODE', rect=Rect(left=451, top=246, 
width=119, height=119), polygon=[Point(x=451, y=364), Point(x=570, y=365), Point(x=566,
y=247), Point(x=453, y=246)]), Decoded(data=b'6925303773908', type='EAN13', 
rect=Rect(left=70, top=214, width=217, height=134), polygon=[Point(x=70, y=313), 
Point(x=70, y=345), Point(x=173, y=347), Point(x=286, y=348), Point(x=287, y=308), 
Point(x=287, y=214), Point(x=72, y=215), Point(x=71, y=247)])]

可以看出barcodes是一个列表里面存储了识别出来的所有信息,循环读取出来,获取我们想要的信息

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

        # 条形码数据为字节对象,所以如果我们想在输出图像上
        #  画出来,就需要先将它转换成字符串
        barcodeData = barcode.data.decode("utf-8")
        # 绘出图像上条形码的数据和条形码类型
        barcodeType = barcode.type
        
        # 把cv2格式的图片转成PIL格式的图片然后在上标注二维码和条形码的内容
        img_PIL = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))

        # 参数(字体,默认大小)
        font = ImageFont.truetype('STFANGSO.TTF', 25)

        # 字体颜色
        fillColor = (0,255,0)

        # 文字输出位置
        position = (x, y-25)

        # 输出内容
        strl = barcodeData
        # 需要先把输出的中文字符转换成Unicode编码形式(str.decode("utf-8))
        
        # 创建画笔
        draw = ImageDraw.Draw(img_PIL)
        draw.text(position, strl, font=font,fill=fillColor)
        # 使用PIL中的save方法保存图片到本地
        img_PIL.save('结果图.jpg', 'jpeg')
        # 向终端打印条形码数据和条形码类型
        print("扫描结果==》 类别: {0} 内容: {1}".format(barcodeType, barcodeData))

打印结果

扫描结果==》 类别: QRCODE 内容: http://weibo.com/u/3225432640
扫描结果==》 类别: EAN13 内容: 6925303773908

 

  • 22
    点赞
  • 120
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值