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构成
Nov 04 Python
简单谈谈Python中的反转字符串问题
Oct 24 Python
python中import reload __import__的区别详解
Oct 16 Python
使用python生成目录树
Mar 29 Python
python3+PyQt5实现拖放功能
Apr 24 Python
pygame实现五子棋游戏
Oct 29 Python
Python: 传递列表副本方式
Dec 19 Python
Python3实现建造者模式的示例代码
Jun 28 Python
python 实现两个npy档案合并
Jul 01 Python
使用python-cv2实现视频的分解与合成的示例代码
Oct 26 Python
Python中BeautifulSoup通过查找Id获取元素信息
Dec 07 Python
OpenCV实现常见的四种图像几何变换
Apr 01 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下操作Linux消息队列完成进程间通信的方法
2010/07/24 PHP
PHP学习笔记 IIS7下安装配置php环境
2012/10/29 PHP
PHP正则表达式之捕获组与非捕获组
2015/11/06 PHP
php实现的证件照换底色功能示例【人像抠图/换背景图】
2020/05/29 PHP
用javascript实现改变TEXTAREA滚动条和按钮的颜色,以及怎样让滚动条变得扁平
2007/04/20 Javascript
Javascript & DHTML 实例编程(教程)DOM基础和基本API
2007/06/02 Javascript
国外大牛IE版本检测!现在IE都到9了,IE检测代码
2012/01/04 Javascript
Jquery AJAX POST与GET之间的区别
2013/11/14 Javascript
js实现滑动触屏事件监听的方法
2015/05/05 Javascript
javascript的BOM
2016/05/03 Javascript
JavaScript自定义浏览器滚动条兼容IE、 火狐和chrome
2017/01/05 Javascript
vue.js实现带日期星期的数字时钟功能示例
2018/08/28 Javascript
angular2 组件之间通过service互相传递的实例
2018/09/30 Javascript
微信小程序sessionid不一致问题解决
2019/08/30 Javascript
JavaScript实现滑动门效果
2020/01/18 Javascript
JS前后端实现身份证号验证代码解析
2020/07/23 Javascript
[48:45]Ti4 循环赛第二日 NEWBEE vs EG
2014/07/11 DOTA
python2.7无法使用pip的解决方法(安装easy_install)
2018/04/03 Python
python 读写文件包含多种编码格式的解决方式
2019/12/20 Python
python几种常用功能实现代码实例
2019/12/25 Python
如何通过Python实现RabbitMQ延迟队列
2020/11/28 Python
HTML5几个设计和修改的页面范例分享
2015/09/29 HTML / CSS
HTML5微信播放全屏问题的解决方法
2017/03/09 HTML / CSS
英国二手物品交易网站:Preloved
2017/10/06 全球购物
你们项目是如何进行变更控制的
2015/08/26 面试题
自动化专业职业生涯规划书范文
2014/01/16 职场文书
文秘大学生求职信
2014/02/25 职场文书
高级工程师英文求职信
2014/03/19 职场文书
四年级评语大全
2014/04/21 职场文书
小学评语大全
2014/04/22 职场文书
食品质量与安全专业毕业生求职信
2014/08/11 职场文书
副主任竞聘演讲稿
2014/08/18 职场文书
倡议书格式
2014/08/30 职场文书
入党积极分子学习党的纲领思想汇报
2014/09/13 职场文书
检讨书范文500字
2015/01/28 职场文书
幼儿教师小班个人总结
2015/02/05 职场文书