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开发之字符串string操作方法实例详解
Nov 12 Python
python中WSGI是什么,Python应用WSGI详解
Nov 24 Python
python八皇后问题的解决方法
Sep 27 Python
python中正则表达式与模式匹配
May 07 Python
详解如何管理多个Python版本和虚拟环境
May 10 Python
Python代码太长换行的实现
Jul 05 Python
python内存管理机制原理详解
Aug 12 Python
Python Django2 model 查询介绍(条件、范围、模糊查询)
Mar 16 Python
python爬取企查查企业信息之selenium自动模拟登录企查查
Apr 08 Python
python状态机transitions库详解
Jun 02 Python
利用python进行数据加载
Jun 20 Python
基于Python实现nc批量转tif格式
Aug 14 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
php Ajax乱码
2008/04/09 PHP
解析PHP实现下载文件的两种方法
2013/07/05 PHP
请离开include_once和require_once
2013/07/18 PHP
js中的数组Array定义与sort方法使用示例
2013/08/29 Javascript
JS中的this变量的使用介绍
2013/10/21 Javascript
jQuery中appendTo()方法用法实例
2015/01/08 Javascript
jQuery使用load()方法载入另外一个网页文件内的指定标签内容到div标签的方法
2015/03/25 Javascript
yui3的AOP(面向切面编程)和OOP(面向对象编程)
2015/05/01 Javascript
jQuery实现智能判断固定导航条或侧边栏的方法
2016/09/04 Javascript
bootstrapfileinput实现文件自动上传
2016/11/08 Javascript
JS作用域闭包、预解释和this关键字综合实例解析
2016/12/16 Javascript
jQuery Validate表单验证插件的基本使用方法及功能拓展
2017/01/04 Javascript
在Vue.js中使用Mixins的方法
2017/09/12 Javascript
vue自定义指令directive的使用方法
2019/04/07 Javascript
nodejs中request库使用HTTPS代理的方法
2019/04/30 NodeJs
vue + typescript + video.js实现 流媒体播放 视频监控功能
2019/07/07 Javascript
Vue实现滑动拼图验证码功能
2019/09/15 Javascript
uniapp微信小程序实现一个页面多个倒计时
2020/11/01 Javascript
Python处理字符串之isspace()方法的使用
2015/05/19 Python
利用Pandas 创建空的DataFrame方法
2018/04/08 Python
查看python下OpenCV版本的方法
2018/08/03 Python
Python迭代器协议及for循环工作机制详解
2020/07/14 Python
Python 执行矩阵与线性代数运算
2020/08/01 Python
Python模拟登录和登录跳转的参考示例
2020/10/30 Python
浅析border-radius如何兼容IE
2016/04/19 HTML / CSS
iHerb台湾:维生素、保健品和健康产品
2018/01/31 全球购物
美国牛仔品牌:True Religion
2018/11/16 全球购物
自我评价是什么
2014/01/04 职场文书
酒店管理专业自荐信
2014/05/23 职场文书
民事诉讼代理授权委托书
2014/10/11 职场文书
个人公司授权委托书范本
2014/10/12 职场文书
不尊敬老师检讨书范文
2014/11/19 职场文书
Pandas自定义选项option设置
2021/07/25 Python
彻底解决MySQL使用中文乱码的方法
2022/01/22 MySQL
TV动画《史上最强大魔王转生为村民A》番宣CM公布
2022/04/01 日漫
go goth封装第三方认证库示例详解
2022/08/14 Golang