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中让MySQL查询结果返回字典类型的方法
Aug 22 Python
使用C语言扩展Python程序的简单入门指引
Apr 14 Python
matplotlib savefig 保存图片大小的实例
May 24 Python
Python将主机名转换为IP地址的方法
Aug 14 Python
python利用dlib获取人脸的68个landmark
Nov 27 Python
Python3.7 基于 pycryptodome 的AES加密解密、RSA加密解密、加签验签
Dec 04 Python
Python连接字符串过程详解
Jan 06 Python
Python 支持向量机分类器的实现
Jan 15 Python
TFRecord格式存储数据与队列读取实例
Jan 21 Python
Python实现发票自动校核微信机器人的方法
May 22 Python
pandas map(),apply(),applymap()区别解析
Feb 24 Python
详解Python内置模块Collections
Mar 22 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获取某个目录大小的代码
2008/09/10 PHP
用PHP查询搜索引擎排名位置的代码
2010/01/05 PHP
服务器web工具 php环境下
2010/12/29 PHP
Smarty高级应用之缓存操作技巧分析
2016/05/14 PHP
PHP中in_array的隐式转换的解决方法
2018/03/06 PHP
jQuery+json实现的简易Ajax调用实例
2015/12/14 Javascript
Bootstrap+jfinal实现省市级联下拉菜单
2016/05/30 Javascript
Jquery on绑定的事件 触发多次实例代码
2016/12/08 Javascript
浅谈react.js 之 批量添加与删除功能
2017/04/17 Javascript
解决linux下node.js全局模块找不到的问题
2018/05/15 Javascript
详解JS中统计函数执行次数与执行时间
2018/09/04 Javascript
用vue-cli开发vue时的代理设置方法
2018/09/20 Javascript
详解angularjs跨页面传参遇到的一些问题
2018/11/01 Javascript
详解vuex数据传输的两种方式及this.$store undefined的解决办法
2019/08/26 Javascript
一看就会的vuex实现登录验证(附案例)
2020/01/09 Javascript
js表达式与运算符简单操作示例
2020/02/15 Javascript
JavaScript运动原理基础知识详解
2020/04/02 Javascript
如何使用three.js 制作一个三维的推箱子游戏
2020/07/29 Javascript
openlayers实现图标拖动获取坐标
2020/09/25 Javascript
python用来获得图片exif信息的库实例分析
2015/03/16 Python
django实现web接口 python3模拟Post请求方式
2019/11/19 Python
python实现门限回归方式
2020/02/29 Python
Python semaphore evevt生产者消费者模型原理解析
2020/03/18 Python
Python下载的11种姿势(小结)
2020/11/18 Python
Pyecharts 中Geo函数常用参数的用法说明
2021/02/01 Python
Pytorch自定义Dataset和DataLoader去除不存在和空数据的操作
2021/03/03 Python
css3针对移动端卡顿问题的解决(动画性能优化)
2020/02/14 HTML / CSS
加拿大时装零售商:Influence U
2018/12/22 全球购物
学校庆元旦歌咏比赛主持词
2014/03/18 职场文书
2014年党员教师自我剖析材料
2014/09/30 职场文书
医院党建工作总结2015
2015/05/26 职场文书
教师学习十八届五中全会精神心得体会
2016/01/05 职场文书
廉洁自律承诺书2016
2016/03/25 职场文书
复制别人的成功真的会成功吗?
2019/10/17 职场文书
基于JavaScript实现省市联动效果
2021/06/22 Javascript
python实现双向链表原理
2022/05/25 Python