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用于url解码和中文解析的小脚本(python url decoder)
Aug 11 Python
python解析xml文件操作实例
Oct 05 Python
python图像处理之反色实现方法
May 30 Python
Python中定时任务框架APScheduler的快速入门指南
Jul 06 Python
go和python变量赋值遇到的一个问题
Aug 31 Python
用Python+OpenCV对比图像质量的几种方法
Jul 15 Python
画pytorch模型图,以及参数计算的方法
Aug 17 Python
python图形用户接口实例详解
Dec 16 Python
Tensorflow 自定义loss的情况下初始化部分变量方式
Jan 06 Python
Python中常用的高阶函数实例详解
Feb 21 Python
Python图片处理模块PIL操作方法(pillow)
Apr 07 Python
python Matplotlib模块的使用
Sep 16 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 !function_exists("T7FC56270E7A70FA81A5935B72EACBE29"))代码解密
2011/01/07 PHP
PHP安全上传图片的方法
2015/03/21 PHP
php 人员权限管理(RBAC)实例(推荐)
2017/05/24 PHP
php使用str_replace替换多维数组的实现方法分析
2017/06/15 PHP
用jquery ajax获取网站Alexa排名的代码
2009/12/12 Javascript
javascript检测页面是否缩放的小例子
2013/05/16 Javascript
js 一个关于图片onload加载的事
2013/11/10 Javascript
jquery设置按钮停顿3秒不可用
2014/03/07 Javascript
基于Jquery+Ajax+Json实现分页显示附效果图
2014/07/30 Javascript
推荐10个2014年最佳的jQuery视频插件
2014/11/12 Javascript
深入理解JavaScript中的对象
2015/06/04 Javascript
js变形金刚文字特效代码分享
2015/08/20 Javascript
javascript高级编程之函数表达式 递归和闭包函数
2015/11/29 Javascript
JS打印组合功能
2016/08/04 Javascript
[原创]JavaScript语法高亮插件highlight.js用法详解【附highlight.js本站下载】
2016/11/01 Javascript
vue实现ToDoList简单实例
2017/02/07 Javascript
JavaScript获取select中text值的方法
2017/02/13 Javascript
require.js与bootstrap结合实现简单的页面登录和页面跳转功能
2017/05/12 Javascript
JavaScript实现省市县三级级联特效
2017/05/16 Javascript
原生JS实现N级菜单的代码
2017/05/21 Javascript
javaScript动态添加Li元素的实例
2018/02/24 Javascript
一些可能会用到的Node.js面试题
2019/06/15 Javascript
python实现中文转换url编码的方法
2016/06/14 Python
用Python将IP地址在整型和字符串之间轻松转换
2017/03/22 Python
Python中Selenium模拟JQuery滑动解锁实例
2017/07/26 Python
简单了解django索引的相关知识
2019/07/17 Python
Pandas 解决dataframe的一列进行向下顺移问题
2019/12/27 Python
Flask 上传自定义头像的实例详解
2020/01/09 Python
Python实现画图软件功能方法详解
2020/07/28 Python
Zalando Lounge瑞士:时尚与生活方式购物俱乐部
2020/03/12 全球购物
医疗器械售后服务承诺书
2014/05/21 职场文书
学雷锋倡议书
2015/01/19 职场文书
助学感谢信范文
2015/01/21 职场文书
农业项目合作意向书
2015/05/08 职场文书
CSS中妙用 drop-shadow 实现线条光影效果
2021/11/11 HTML / CSS
Python 数据可视化工具 Pyecharts 安装及应用
2022/04/20 Python