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编写简单的画图板程序的示例教程
Dec 08 Python
Python 使用SMTP发送邮件的代码小结
Sep 21 Python
python中如何使用分步式进程计算详解
Mar 22 Python
python修改字典键(key)的方法
Aug 05 Python
python字典的setdefault的巧妙用法
Aug 07 Python
python中matplotlib条件背景颜色的实现
Sep 02 Python
Python列表元素常见操作简单示例
Oct 25 Python
python中dict()的高级用法实现
Nov 13 Python
利用python实现冒泡排序算法实例代码
Dec 01 Python
Python列表切片常用操作实例解析
Mar 10 Python
使用jupyter Nodebook查看函数或方法的参数以及使用情况
Apr 14 Python
pytorch 多分类问题,计算百分比操作
Jul 09 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实现把数组按指定的个数分隔
2014/02/17 PHP
php实现扫描二维码根据浏览器类型访问不同下载地址
2014/10/15 PHP
php视频拍照上传头像功能实现代码分享
2015/10/08 PHP
用 JSON 处理缓存
2007/04/27 Javascript
捕获键盘事件(且兼容各浏览器)
2013/07/03 Javascript
javascript中创建对象的几种方法总结
2013/11/01 Javascript
利用浏览器全屏api实现js全屏
2014/01/16 Javascript
如何使用Bootstrap的modal组件自定义alert,confirm和modal对话框
2016/03/01 Javascript
js 获取元素所有兄弟节点的实现方法
2016/09/06 Javascript
移动端触摸滑动插件swiper使用方法详解
2017/08/11 Javascript
seajs模块压缩问题与解决方法实例分析
2017/10/10 Javascript
vue 自定义全局方法,在组件里面的使用介绍
2018/02/28 Javascript
微信小程序上线发布流程图文详解
2019/05/06 Javascript
JQuery常用选择器功能与用法实例分析
2019/12/23 jQuery
[54:02]2018DOTA2亚洲邀请赛 4.1 小组赛 B组 IG vs VGJ.T
2018/04/03 DOTA
[02:09]2018DOTA2亚洲邀请赛TNC赛前采访
2018/04/04 DOTA
用Python给文本创立向量空间模型的教程
2015/04/23 Python
教你用python3根据关键词爬取百度百科的内容
2016/08/18 Python
详解Django中六个常用的自定义装饰器
2018/07/04 Python
Python3匿名函数用法示例
2018/07/25 Python
Python http接口自动化测试框架实现方法示例
2018/12/06 Python
Python3按一定数据位数格式处理bin文件的方法
2019/01/24 Python
Django 框架模型操作入门教程
2019/11/05 Python
python实现mean-shift聚类算法
2020/06/10 Python
Python matplotlib模块及柱状图用法解析
2020/08/10 Python
python 如何实现遗传算法
2020/09/22 Python
CSS3动画之利用requestAnimationFrame触发重新播放功能
2019/09/11 HTML / CSS
HTML5之SVG 2D入门1—SVG(可缩放矢量图形)概述
2013/01/30 HTML / CSS
微信小程序之html5 canvas绘图并保存到系统相册
2019/06/20 HTML / CSS
澳大利亚免息网上购物:Shop Zero
2016/09/17 全球购物
NFL墨西哥官方商店:Tienda NFL
2017/11/28 全球购物
师范教师毕业鉴定
2014/01/13 职场文书
青奥会口号
2014/06/12 职场文书
电子商务求职信
2014/06/15 职场文书
质量在我心中演讲稿
2014/09/02 职场文书
Python使用OpenCV和K-Means聚类对毕业照进行图像分割
2021/06/11 Python