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运用于数据分析的简单教程
Mar 27 Python
在Django的URLconf中使用命名组的方法
Jul 18 Python
Python装饰器基础详解
Mar 09 Python
flask入门之文件上传与邮件发送示例
Jul 18 Python
Python爬虫的两套解析方法和四种爬虫实现过程
Jul 20 Python
python基础梳理(一)(推荐)
Apr 06 Python
python2和python3应该学哪个(python3.6与python3.7的选择)
Oct 01 Python
解决pycharm同一目录下无法import其他文件
Feb 12 Python
Django models filter筛选条件详解
Mar 16 Python
后端开发使用pycharm的技巧(推荐)
Mar 27 Python
Python验证码截取识别代码实例
May 16 Python
关于python3 opencv 图像二值化的问题(cv2.adaptiveThreshold函数)
Apr 04 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 MessagePack介绍
2013/10/06 PHP
PHP开发制作一个简单的活动日程表Calendar
2016/06/20 PHP
php组合排序简单实现方法
2016/10/15 PHP
Linux平台php命令行程序处理管道数据的方法
2016/11/10 PHP
浅析PHP数据导出知识点
2018/02/17 PHP
PHP get_html_translation_table()函数用法讲解
2019/02/16 PHP
js正确获取元素样式详解
2009/08/07 Javascript
jquery.fileEveryWhere.js 一个跨浏览器的file显示插件
2011/10/24 Javascript
js实现无需数据库的县级以上联动行政区域下拉控件
2013/08/14 Javascript
使用jquery.validate自定义方法实现"手机号码或者固话至少填写一个"的逻辑验证
2014/09/01 Javascript
JS+CSS实现的竖向简洁折叠菜单效果代码
2015/10/22 Javascript
基于bootstrap风格的弹框插件
2016/12/28 Javascript
javascript实现复选框全选或反选
2017/02/04 Javascript
vue v-on监听事件详解
2017/05/17 Javascript
认识jQuery的Promise的具体使用方法
2017/10/10 jQuery
Linux Centos7.2下安装nodejs&npm配置全局路径的教程
2018/05/15 NodeJs
使用JavaScript中的lodash编写双色球效果
2018/06/24 Javascript
jQuery AJAX与jQuery事件的分析讲解
2019/02/18 jQuery
layUI实现三级导航菜单效果
2019/07/26 Javascript
微信小程序 生成携带参数的二维码
2019/10/23 Javascript
[01:07:11]Secret vs Newbee 2019国际邀请赛小组赛 BO2 第二场 8.15
2019/08/17 DOTA
python求解水仙花数的方法
2015/05/11 Python
在Python中用keys()方法返回字典键的教程
2015/05/21 Python
Python中作用域的深入讲解
2018/12/10 Python
python实现石头剪刀布小游戏
2021/01/20 Python
python中字典按键或键值排序的实现代码
2019/08/27 Python
如何让python的运行速度得到提升
2020/07/08 Python
Urban Outfitters英国官网:美国平价服饰品牌
2016/11/25 全球购物
写求职信要注意什么问题
2014/04/12 职场文书
出国英文推荐信
2014/05/10 职场文书
班子个人四风问题整改措施
2014/10/04 职场文书
一般基层干部群众路线教育实践活动个人对照检查材料
2014/11/04 职场文书
学生评语集锦
2015/01/04 职场文书
2015迎新晚会活动总结
2015/07/16 职场文书
学习社交礼仪心得体会
2016/01/22 职场文书
CSS 鼠标点击拖拽效果的实现代码
2022/12/24 HTML / CSS