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基础教程之自定义函数介绍
Aug 29 Python
Python实现的tab文件操作类分享
Nov 20 Python
Python素数检测实例分析
Jun 15 Python
Python正则表达式使用范例分享
Dec 04 Python
Python实现基本数据结构中队列的操作方法示例
Dec 04 Python
python批量修改图片大小的方法
Jul 24 Python
python3基于TCP实现CS架构文件传输
Jul 28 Python
在Python中字典根据多项规则排序的方法
Jan 21 Python
用pyqt5 给按钮设置图标和css样式的方法
Jun 24 Python
python实现名片管理器的示例代码
Dec 17 Python
宝塔面板成功部署Django项目流程(图文)
Jun 22 Python
Python还能这么玩之只用30行代码从excel提取个人值班表
Jun 05 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将HTML转换成文本的实现代码
2015/01/21 PHP
PHP5.4起内置web服务器使用方法
2016/08/09 PHP
PHP开发中解决并发问题的几种实现方法分析
2017/11/13 PHP
PHP使用CURL实现下载文件功能示例
2019/06/03 PHP
调用DOM对象的focus使文本框获得焦点
2014/02/19 Javascript
jQuery学习笔记之jQuery中的$
2015/01/19 Javascript
jQuery实现仿Google首页拖动效果的方法
2015/05/04 Javascript
jQuery基于ajax实现星星评论代码
2015/08/07 Javascript
w3c编程挑战_初级脚本算法实战篇
2017/06/23 Javascript
谈谈JS中的!!
2017/12/07 Javascript
vue 实现剪裁图片并上传服务器功能
2018/03/01 Javascript
JavaScript中的回调函数实例讲解
2019/01/27 Javascript
createObjectURL方法实现本地图片预览
2019/09/30 Javascript
100行代码实现vue表单校验功能(小白自编)
2019/11/19 Javascript
JavaScript中如何对多维数组(矩阵)去重的实现
2019/12/04 Javascript
python判断字符串编码的简单实现方法(使用chardet)
2016/07/01 Python
python3使用QQ邮箱发送邮件
2020/05/20 Python
python3编写ThinkPHP命令执行Getshell的方法
2019/02/26 Python
Python学习笔记之错误和异常及访问错误消息详解
2019/08/08 Python
解决django同步数据库的时候app models表没有成功创建的问题
2019/08/09 Python
Selenium启动Chrome时配置选项详解
2020/03/18 Python
Python+Xlwings 删除Excel的行和列
2020/12/19 Python
python实现无边框进度条的实例代码
2020/12/30 Python
基于tensorflow __init__、build 和call的使用小结
2021/02/26 Python
瑞典轮胎在线:Tirendo.se
2018/06/21 全球购物
与UNIX有关的几个名词
2015/09/17 面试题
运动会获奖感言
2014/02/11 职场文书
乡镇纠风工作实施方案
2014/03/22 职场文书
《锄禾》教学反思
2014/04/08 职场文书
小学二年级评语
2014/04/21 职场文书
教师读书活动总结
2014/05/07 职场文书
2014年高中班主任工作总结
2014/11/08 职场文书
《黄道婆》教学反思
2016/02/22 职场文书
使用Redis实现实时排行榜功能
2021/07/02 Redis
MySQL时区造成时差问题
2022/04/13 MySQL
Android基础入门之dataBinding的简单使用教程
2022/06/21 Java/Android