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代码实例
Feb 04 Python
Using Django with GAE Python 后台抓取多个网站的页面全文
Feb 17 Python
利用Python破解斗地主残局详解
Jun 30 Python
Python实现的rsa加密算法详解
Jan 24 Python
Python3多进程 multiprocessing 模块实例详解
Jun 11 Python
numpy返回array中元素的index方法
Jun 27 Python
Django框架封装外部函数示例
May 28 Python
利用Python复制文件的9种方法总结
Sep 02 Python
决策树剪枝算法的python实现方法详解
Sep 18 Python
python手写均值滤波
Feb 19 Python
如何基于matlab相机标定导出xml文件
Nov 02 Python
教你怎么用Python监控愉客行车程
Apr 29 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 抓取网页图片并且另存为的实现代码
2010/03/24 PHP
PHP模板引擎Smarty中的保留变量用法分析
2016/04/11 PHP
JavaScript中SQL语句的应用实现
2010/05/04 Javascript
jQuery操作select的实例代码
2012/06/14 Javascript
js 定时器setTimeout无法调用局部变量的解决办法
2013/11/28 Javascript
理解javascript中的回调函数(callback)
2014/09/02 Javascript
jquery实现的淡入淡出下拉菜单效果
2015/08/25 Javascript
详解JavaScript中localStorage使用要点
2016/01/13 Javascript
基于JavaScript实现单选框下拉菜单添加文件效果
2016/06/26 Javascript
Vue.js 2.0 和 React、Augular等其他前端框架大比拼
2016/10/08 Javascript
bootstrap table单元格新增行并编辑
2017/05/19 Javascript
利用vueJs实现图片轮播实例代码
2017/06/03 Javascript
jQuery结合jQuery.cookie.js插件实现换肤功能示例
2017/10/14 jQuery
Vue按需加载的具体实现
2017/12/02 Javascript
在react中使用vuex的示例代码
2018/07/30 Javascript
微信小程序 腾讯地图SDK 获取当前地址实现解析
2019/08/12 Javascript
策略模式实现 Vue 动态表单验证的方法
2019/09/16 Javascript
JavaScript实现轮播图效果代码实例
2019/09/28 Javascript
JS面向对象编程基础篇(三) 继承操作实例详解
2020/03/03 Javascript
Python性能优化的20条建议
2014/10/25 Python
在Python中使用mongoengine操作MongoDB教程
2015/04/24 Python
处理Python中的URLError异常的方法
2015/04/30 Python
Python学习入门之区块链详解
2017/07/25 Python
使用python生成目录树
2018/03/29 Python
python之验证码生成(gvcode与captcha)
2019/01/02 Python
python实现二维数组的对角线遍历
2019/03/02 Python
详解Python3之数据指纹MD5校验与对比
2019/06/11 Python
python 中如何获取列表的索引
2019/07/02 Python
PyQt5使用QTimer实现电子时钟
2019/07/29 Python
使用python模拟高斯分布例子
2019/12/09 Python
介绍一下你对SOA的认识
2016/04/24 面试题
土木工程应届生求职信
2013/10/31 职场文书
小学开学典礼主持词
2014/03/19 职场文书
十二生肖观后感
2015/06/12 职场文书
终止合同协议书范本
2016/03/22 职场文书
解决go在函数退出后子协程的退出问题
2021/04/30 Golang