python 二维码生成与识别

1.生成二维码

1.1 qrcode

  • 安装qrcode模块
  pip install qrcode

在这里插入图片描述

  • 示例:
  # author:mlnt
  # createdate:2022/8/14
  """
  pip install qrcode
  """
  import qrcode
  
  # 要在二维码中存储的数据
  data = "侠客行\n\
  李白\n\
  赵客缦胡缨,吴钩霜雪明。\n\
  银鞍照白马,飒沓如流星。\n\
  十步杀一人,千里不留行。\n\
  事了拂衣去,深藏身与名。\n\
  闲过信陵饮,脱剑膝前横。\n\
  将炙啖朱亥,持觞劝侯嬴。\n\
  三杯吐然诺,五岳倒为轻。\n\
  眼花耳热后,意气素霓生。\n\
  救赵挥金槌,邯郸先震惊。\n\
  千秋二壮士,烜赫大梁城。\n\
  纵死侠骨香,不惭世上英。\n\
  谁能书阁下,白首太玄经。"
  # print(data)
  
  """
  error_correction:容错能力
  L:7%
  M:15%
  Q:25%
  H:30%
  """
  # 创建QRCode对象,并设置参数
  qr_code = qrcode.QRCode(
      version=2,  # 二维码大小
      error_correction=qrcode.constants.ERROR_CORRECT_M,  # 二维码的纠错范围
      box_size=10,  # 每个点(方块)中的像素个数
      border=4  # 二维码距图像外围边框的距离
  )
  qr_code.add_data(data)  # 添加数据到二维码
  qr_code.make(fit=True)  # 将数据编译成二维码数组。fit为True,表示查找最适合数据以避免数据溢出错误
  img = qr_code.make_image()  # 将二维码数据制作成图像
  img.show()  # 显示二维码
  img.save('test.jpg')
  • 生成二维码效果:
    在这里插入图片描述

  • 扫码结果:
    在这里插入图片描述

  • 生成带logo的二维码的名片

# author:mlnt
# createdate:2022/8/20
import qrcode
from PIL import Image
from PIL.Image import Resampling

vc_str = """
BEGIN:VCARD\n
FN:张三\n
NICKNAME:法外狂徒\n
ORG:xx研究中心\n
TITLE:研究所所长\n
EMAIL:zs@163.com\n
END:VCARD
"""
# 创建QRCode对象,并设置参数
qr_code = qrcode.QRCode(
    version=5,  # 二维码大小
    error_correction=qrcode.constants.ERROR_CORRECT_M,  # 二维码的纠错范围
    box_size=10,  # 每个点(方块)中的像素个数
    border=1  # 二维码距图像外围边框的距离
)
qr_code.add_data(data=vc_str)  # 添加数据到二维码
qr_code.make(fit=True)  # 将数据编译成二维码数组。fit为True,表示查找最适合数据以避免数据溢出错误
qrcode.make()
img = qr_code.make_image(fill_color='green')  # 将二维码数据制作成图像
width, height = img.size  # QR code的宽高
# 添加logo,打开logo照片
icon = Image.open("img.jpg")
# 参数设置logo的大小
factor = 6
size_w = int(width / factor)
size_h = int(height / factor)
icon_w, icon_h = icon.size
if icon_w > size_w:
    icon_w = size_w
if icon_h > size_h:
    icon_h = size_h
# 重新设置logo的尺寸
icon = icon.resize((icon_w, icon_h), Resampling.LANCZOS)
# 得到画图的x,y坐标,居中显示
w = int((width - icon_w) // 2)
h = int((height - icon_h) // 2)
# 黏贴logo照
img.paste(icon, (w, h), mask=None)
# DeprecationWarning: ANTIALIAS is deprecated and will be removed in Pillow 10 (2023-07-01). Use Resampling.LANCZOS instead.
img = img.resize((width//2, height//2), Resampling.LANCZOS)
img.show()  # 显示二维码
img.save('qrcode.jpg') # 保存图片

在这里插入图片描述
扫描效果:
在这里插入图片描述

1.2 myqr

  • 安装MyQR模块

    pip install myqr
    

在这里插入图片描述

  • 生成二维码图片示例

    # author:mlnt
    # createdate:2022/8/14
    """
    pip install myqr
    """
    
    from MyQR import myqr
    
    """
      words: 二维码内容,不支持中文
      => supported_chars = r"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ··,.:;+-*/\~!@#$%^&`'=<>[]()?_{}|"
      version: 边长控制,二维码大小(1~40)
      level: 纠错级别 ('L','M','Q','H')
      picutre: 二维码背景,支持.jpg/.png/.bmp/.gif
      colorized: 二维码背景颜色,默认为False,黑白
      constrast: 对比度,默认为1.0
      brightness: 亮度,默认1.0
      save_name: 输出文件的名称,如'example.png'
      save_dir: 输出目录,即二维码图片保存目录
    """
    # supported_chars = r"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ··,.:;+-*/\~!@#$%^&`'=<>[]()?_{}|"
    # 不支持中文
    myqr.run(
        # words="仗剑红尘已是癫,有酒平步上青天;游星戏斗弄日月,醉卧云端笑人间。",
        # ValueError: Wrong words! Make sure the characters are supported!
        words='Sharp tools make good work.',
        version=2,
        level='M',
        save_name='test2.jpg'
    )
    
  • 生成效果:
    在这里插入图片描述

  • 扫码结果:
    在这里插入图片描述

2. 二维码识别

  • 安装pyzbar

    pip install pyzbar
    
  • 识别二维码示例

    # author:mlnt
    # createdate:2022/8/14
    """
    pip install pyzbar
    """
    import cv2 as cv
    from pyzbar import pyzbar
    
    image = cv.imread('test2.jpg')  # 加载图片
    # 将图片灰度转换
    gray_img = cv.cvtColor(image, code=cv.COLOR_BGR2GRAY)
    
    barcodes = pyzbar.decode(gray_img)  # 解码
    # print(barcodes)
    # [Decoded(data=b'Sharp tools make good work.', type='QRCODE', rect=Rect(left=35, top=35, width=262, height=262), polygon=[Point(x=35, y=35), Point(x=35, y=297), Point(x=297, y=297), Point(x=297, y=35)], quality=1, orientation='UP')]
    for barcode in barcodes:
        barcodeData = barcode.data.decode('utf-8')  # 字节类型转成字符串
        print(barcodeData)
    # Sharp tools make good work.
    

参考文章:
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐