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判断变量是否为Json格式的字符串示例
May 03 Python
Python实现统计代码行的方法分析
Jul 12 Python
Python实现多进程共享数据的方法分析
Dec 04 Python
python实现百万答题自动百度搜索答案
Jan 16 Python
selenium+python 去除启动的黑色cmd窗口方法
May 22 Python
python解决字符串倒序输出的问题
Jun 25 Python
Python 做曲线拟合和求积分的方法
Dec 29 Python
对Python+opencv将图片生成视频的实例详解
Jan 08 Python
PyQt5重写QComboBox的鼠标点击事件方法
Jun 25 Python
在Python中字符串、列表、元组、字典之间的相互转换
Nov 15 Python
在pytorch 中计算精度、回归率、F1 score等指标的实例
Jan 18 Python
Anaconda3中的Jupyter notebook添加目录插件的实现
May 18 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
第四节 构造函数和析构函数 [4]
2006/10/09 PHP
thinkphp3查询mssql数据库乱码解决方法分享
2014/02/11 PHP
百度工程师讲PHP函数的实现原理及性能分析(二)
2015/05/13 PHP
PHP实现动态执行代码的方法
2016/03/25 PHP
Js之软键盘实现(js源码)
2007/01/30 Javascript
javascript动态加载实现方法一
2012/08/22 Javascript
JavaScript中的noscript元素属性位置及作用介绍
2013/04/11 Javascript
Jquery取得iframe下内容的方法
2013/11/18 Javascript
node.js中的fs.fchmod方法使用说明
2014/12/16 Javascript
jQuery插件StickUp实现网页导航置顶
2015/04/12 Javascript
jQuery实现在最后一个元素之前插入新元素的方法
2015/07/18 Javascript
理解javascript中的严格模式
2016/02/01 Javascript
关于JS 预解释的相关理解
2016/06/28 Javascript
AngularJS基础 ng-include 指令示例讲解
2016/08/01 Javascript
Javascript Function.prototype.bind详细分析
2016/12/29 Javascript
vue.js 实现评价五角星组件的实例代码
2018/08/13 Javascript
vue watch关于对象内的属性监听
2019/04/22 Javascript
vue vant Area组件使用详解
2019/12/09 Javascript
浅谈vue权限管理实现及流程
2020/04/23 Javascript
Python字符串特性及常用字符串方法的简单笔记
2016/01/04 Python
Python tkinter模块中类继承的三种方式分析
2017/08/08 Python
Python实现PS图像明亮度调整效果示例
2018/01/23 Python
python使用Tkinter实现在线音乐播放器
2018/01/30 Python
python爬虫正则表达式之处理换行符
2018/06/08 Python
python3应用windows api对后台程序窗口及桌面截图并保存的方法
2019/08/27 Python
python基于FTP实现文件传输相关功能代码实例
2019/09/28 Python
python3格式化字符串 f-string的高级用法(推荐)
2020/03/04 Python
python读取hdfs并返回dataframe教程
2020/06/05 Python
Python 实现一个简单的web服务器
2021/01/03 Python
香港优质食材和美酒专门店:FoodWise
2017/09/01 全球购物
台湾网友喜爱的综合型网路购物商城:Yahoo! 奇摩购物中心
2018/03/10 全球购物
公司市场部岗位职责
2013/12/02 职场文书
大课间活动制度
2014/01/18 职场文书
医学生毕业自我鉴定
2014/03/26 职场文书
答谢词范文
2015/01/05 职场文书
Python开发之QT解决无边框界面拖动卡屏问题(附带源码)
2021/05/27 Python