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中的变量的数据类型
May 13 Python
Python中用altzone()方法处理时区的教程
May 22 Python
python开发之tkinter实现图形随鼠标移动的方法
Nov 11 Python
Python+Pika+RabbitMQ环境部署及实现工作队列的实例教程
Jun 29 Python
python 简单备份文件脚本v1.0的实例
Nov 06 Python
pycharm使用matplotlib.pyplot不显示图形的解决方法
Oct 28 Python
用Python中的turtle模块画图两只小羊方法
Apr 09 Python
在VS2017中用C#调用python脚本的实现
Jul 31 Python
wxPython色环电阻计算器
Nov 18 Python
python 利用已有Ner模型进行数据清洗合并代码
Dec 24 Python
在pytorch 中计算精度、回归率、F1 score等指标的实例
Jan 18 Python
python常量折叠基础知识点讲解
Feb 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
PHP与javascript实现变量交互的示例代码
2013/07/23 PHP
php多维数组去掉重复值示例分享
2014/03/02 PHP
session 加入redis的实现代码
2016/07/15 PHP
phpwind放自动注册方法
2006/12/02 Javascript
深入认识JavaScript中的函数
2007/01/22 Javascript
javascript之Partial Application学习
2013/01/10 Javascript
尝试在让script的type属性等于text/html
2013/01/15 Javascript
JS获得URL超链接的参数值实例代码
2013/06/21 Javascript
Jquery.Form 异步提交表单的简单实例
2014/03/03 Javascript
JavaScript父子窗体间的调用方法
2015/03/31 Javascript
JavaScript模块规范之AMD规范和CMD规范
2015/10/27 Javascript
web前端开发upload上传头像js示例代码
2016/10/22 Javascript
JS实现自动阅读单词(有道单词本添加功能)
2016/11/14 Javascript
Bootstrap基本模板的使用和理解1
2016/12/14 Javascript
jQuery获取所有父级元素及同级元素及子元素的方法(推荐)
2018/01/21 jQuery
JS实现左边列表移到到右边列表功能
2018/03/28 Javascript
微信小程序vant弹窗组件的实现方式
2020/02/21 Javascript
一文读懂vue动态属性数据绑定(v-bind指令)
2020/07/20 Javascript
python正则爬取某段子网站前20页段子(request库)过程解析
2019/08/10 Python
python中sort和sorted排序的实例方法
2019/08/26 Python
浅谈Django2.0 加xadmin踩的坑
2019/11/15 Python
Python 实现opencv所使用的图片格式与 base64 转换
2020/01/09 Python
Python学习之路之pycharm的第一个项目搭建过程
2020/06/18 Python
Html5 滚动穿透的方法
2019/05/13 HTML / CSS
老师推荐信
2013/10/28 职场文书
财务出纳员岗位职责
2013/11/26 职场文书
电子商务个人自荐信
2013/12/12 职场文书
旅游业大学生创业计划书
2014/01/31 职场文书
小学生我的梦想演讲稿
2014/08/21 职场文书
委托证明书
2014/09/17 职场文书
“向国旗敬礼”主题班会活动设计方案
2014/09/27 职场文书
四风专项整治工作情况汇报
2014/10/28 职场文书
实习护士自荐信
2015/03/25 职场文书
《成长的天空》读后感3篇
2019/12/06 职场文书
vue3使用vue-router的完整步骤记录
2021/06/20 Vue.js
HttpClient实现表单提交上传文件
2022/08/14 Java/Android