Python二维码生成识别实例详解


Posted in Python onJuly 16, 2019

前言

在 JavaWeb 开发中,一般使用 Zxing 来生成和识别二维码,但是,Zxing 的识别有点差强人意,不少相对模糊的二维码识别率很低。不过就最新版本的测试来说,识别率有了现显著提高。

对比

在没接触 Python 之前,曾使用 Zbar 的客户端进行识别,测了大概几百张相对模糊的图片,Zbar的识别速度要快很多,识别率也比 Zxing 稍微准确那边一丢丢,但是,稍微模糊一点就无法识别。相比之下,微信和支付宝的识别效果就逆天了。

代码案例

# -*- coding:utf-8 -*-
import os
import qrcode
import time
from PIL import Image
from pyzbar import pyzbar

"""
# 升级 pip 并安装第三方库
pip install -U pip
pip install Pillow
pip install pyzbar
pip install qrcode
"""


def make_qr_code_easy(content, save_path=None):
  """
  Generate QR Code by default
  :param content: The content encoded in QR Codeparams
  :param save_path: The path where the generated QR Code image will be saved in.
           If the path is not given the image will be opened by default.
  """
  img = qrcode.make(data=content)
  if save_path:
    img.save(save_path)
  else:
    img.show()


def make_qr_code(content, save_path=None):
  """
  Generate QR Code by given params
  :param content: The content encoded in QR Code
  :param save_path: The path where the generated QR Code image will be saved in.
           If the path is not given the image will be opened by default.
  """
  qr_code_maker = qrcode.QRCode(version=2,
                 error_correction=qrcode.constants.ERROR_CORRECT_M,
                 box_size=8,
                 border=1,
                 )
  qr_code_maker.add_data(data=content)
  qr_code_maker.make(fit=True)
  img = qr_code_maker.make_image(fill_color="black", back_color="white")
  if save_path:
    img.save(save_path)
  else:
    img.show()


def make_qr_code_with_icon(content, icon_path, save_path=None):
  """
  Generate QR Code with an icon in the center
  :param content: The content encoded in QR Code
  :param icon_path: The path of icon image
  :param save_path: The path where the generated QR Code image will be saved in.
           If the path is not given the image will be opened by default.
  :exception FileExistsError: If the given icon_path is not exist.
                This error will be raised.
  :return:
  """
  if not os.path.exists(icon_path):
    raise FileExistsError(icon_path)

  # First, generate an usual QR Code image
  qr_code_maker = qrcode.QRCode(version=4,
                 error_correction=qrcode.constants.ERROR_CORRECT_H,
                 box_size=8,
                 border=1,
                 )
  qr_code_maker.add_data(data=content)
  qr_code_maker.make(fit=True)
  qr_code_img = qr_code_maker.make_image(fill_color="black", back_color="white").convert('RGBA')

  # Second, load icon image and resize it
  icon_img = Image.open(icon_path)
  code_width, code_height = qr_code_img.size
  icon_img = icon_img.resize((code_width // 4, code_height // 4), Image.ANTIALIAS)

  # Last, add the icon to original QR Code
  qr_code_img.paste(icon_img, (code_width * 3 // 8, code_width * 3 // 8))

  if save_path:
    qr_code_img.save(save_path)
  else:
    qr_code_img.show()


def decode_qr_code(code_img_path):
  """
  Decode the given QR Code image, and return the content
  :param code_img_path: The path of QR Code image.
  :exception FileExistsError: If the given code_img_path is not exist.
                This error will be raised.
  :return: The list of decoded objects
  """
  if not os.path.exists(code_img_path):
    raise FileExistsError(code_img_path)

  # Here, set only recognize QR Code and ignore other type of code
  return pyzbar.decode(Image.open(code_img_path), symbols=[pyzbar.ZBarSymbol.QRCODE], scan_locations=True)


if __name__ == "__main__":

  # # 简易版
  # make_qr_code_easy("make_qr_code_easy", "make_qr_code_easy.png")
  # results = decode_qr_code("make_qr_code_easy.png")
  # if len(results):
  #   print(results[0].data.decode("utf-8"))
  # else:
  #   print("Can not recognize.")
  #
  # # 参数版
  # make_qr_code("make_qr_code", "make_qr_code.png")
  # results = decode_qr_code("make_qr_code.png")
  # if len(results):
  #   print(results[0].data.decode("utf-8"))
  # else:
  #   print("Can not recognize.")
  #
  # 带中间 logo 的
  # make_qr_code_with_icon("https://blog.52itstyle.vip", "icon.jpg", "make_qr_code_with_icon.png")
  # results = decode_qr_code("make_qr_code_with_icon.png")
  # if len(results):
  #   print(results[0].data.decode("utf-8"))
  # else:
  #   print("Can not recognize.")

  # 识别答题卡二维码 16 识别失败
  t1 = time.time()
  count = 0
  for i in range(1, 33):
    results = decode_qr_code(os.getcwd()+"\\img\\"+str(i)+".png")
    if len(results):
      print(results[0].data.decode("utf-8"))
    else:
      print("Can not recognize.")
      count += 1
  t2 = time.time()
  print("识别失败数量:" + str(count))
  print("测试时间:" + str(int(round(t2 * 1000))-int(round(t1 * 1000))))

测试了32张精挑细选的模糊二维码:

识别失败数量:1
测试时间:130

使用最新版的 Zxing 识别失败了三张。

源码

https://gitee.com/52itstyle/Python/tree/master/Day13

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python isinstance判断对象类型
Sep 06 Python
python中实现精确的浮点数运算详解
Nov 02 Python
一道python走迷宫算法题
Jan 22 Python
Python简单I/O操作示例
Mar 18 Python
使用python实现mqtt的发布和订阅
May 05 Python
Python安装selenium包详细过程
Jul 23 Python
python-tornado的接口用swagger进行包装的实例
Aug 29 Python
springboot配置文件抽离 git管理统 配置中心详解
Sep 02 Python
Python3变量与基本数据类型用法实例分析
Feb 14 Python
在Python中通过threshold创建mask方式
Feb 19 Python
基于pandas向csv添加新的行和列
May 25 Python
Python selenium键盘鼠标事件实现过程详解
Jul 28 Python
python3.6+selenium实现操作Frame中的页面元素
Jul 16 #Python
Python Web版语音合成实例详解
Jul 16 #Python
windows下python虚拟环境virtualenv安装和使用详解
Jul 16 #Python
Pandas中DataFrame的分组/分割/合并的实现
Jul 16 #Python
Python的matplotlib绘图如何修改背景颜色的实现
Jul 16 #Python
python调用其他文件函数或类的示例
Jul 16 #Python
Python PyQt5 Pycharm 环境搭建及配置详解(图文教程)
Jul 16 #Python
You might like
千呼万唤始出来,DOTA2勇士令状不朽宝藏Ⅱ现已推出
2020/08/25 DOTA
php array_merge下进行数组合并的代码
2008/07/22 PHP
PHP插入排序实现代码
2013/04/04 PHP
php selectradio和checkbox默认选择的实现方法详解
2013/06/29 PHP
Laravel 的数据库迁移的方法
2017/07/31 PHP
原生javascript实现无间缝滚动示例
2014/01/28 Javascript
JS实现让访问者自助选择网页文字颜色的方法
2015/02/24 Javascript
EasyUI中实现form表单提交的示例分享
2015/03/01 Javascript
javascript学习指南之回调问题
2016/04/23 Javascript
js中数组的常用方法小结
2016/12/30 Javascript
jquery事件与绑定事件
2017/03/16 Javascript
详解用vue.js和laravel实现微信支付
2017/06/23 Javascript
JScript实现表格的简单操作
2017/08/15 Javascript
Less 安装及基本用法
2018/05/05 Javascript
vue 表单验证按钮事件交由父组件触发的方法
2018/12/17 Javascript
Vue的H5页面唤起支付宝支付功能
2019/04/18 Javascript
Vuex实现购物车小功能
2020/08/17 Javascript
利用JavaScript模拟京东按键输入功能
2020/12/01 Javascript
[02:21]DOTA2英雄基础教程 蝙蝠骑士
2013/12/16 DOTA
[57:12]完美世界DOTA2联赛循环赛 Inki vs Matador BO2第一场 10.31
2020/11/02 DOTA
Python Web服务器Tornado使用小结
2014/05/06 Python
Python实现简单HTML表格解析的方法
2015/06/15 Python
Python2.7环境Flask框架安装简明教程【已测试】
2018/07/13 Python
在tensorflow中设置保存checkpoint的最大数量实例
2020/01/21 Python
Pytorch中的自动求梯度机制和Variable类实例
2020/02/29 Python
PyTorch之nn.ReLU与F.ReLU的区别介绍
2020/06/27 Python
css3学习心得分享
2013/08/19 HTML / CSS
css3 实现圆形旋转倒计时
2018/02/24 HTML / CSS
马来西亚领先的在线礼品店:Giftr
2018/08/23 全球购物
Fabletics官网:美国运动服饰品牌,由好莱坞女演员凯特·哈德森创立
2019/10/19 全球购物
区域销售经理岗位职责
2013/12/10 职场文书
数控技术应用个人求职信范文
2014/02/03 职场文书
廉洁自律承诺书2015
2015/01/22 职场文书
2015庆祝七一建党节94周年活动总结
2015/03/20 职场文书
大学生青年志愿者活动总结
2015/05/06 职场文书
ipad隐藏软件app图标方法
2022/04/19 数码科技